summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors
diff options
context:
space:
mode:
Diffstat (limited to 'devtools/server/actors')
-rw-r--r--devtools/server/actors/accessibility/accessibility.js140
-rw-r--r--devtools/server/actors/accessibility/accessible.js633
-rw-r--r--devtools/server/actors/accessibility/audit/contrast.js307
-rw-r--r--devtools/server/actors/accessibility/audit/keyboard.js516
-rw-r--r--devtools/server/actors/accessibility/audit/moz.build12
-rw-r--r--devtools/server/actors/accessibility/audit/text-label.js435
-rw-r--r--devtools/server/actors/accessibility/constants.js150
-rw-r--r--devtools/server/actors/accessibility/moz.build20
-rw-r--r--devtools/server/actors/accessibility/parent-accessibility.js156
-rw-r--r--devtools/server/actors/accessibility/simulator.js78
-rw-r--r--devtools/server/actors/accessibility/walker.js1313
-rw-r--r--devtools/server/actors/accessibility/worker.js105
-rw-r--r--devtools/server/actors/addon/addons.js43
-rw-r--r--devtools/server/actors/addon/moz.build10
-rw-r--r--devtools/server/actors/addon/webextension-inspected-window.js697
-rw-r--r--devtools/server/actors/animation-type-longhand.js402
-rw-r--r--devtools/server/actors/animation.js898
-rw-r--r--devtools/server/actors/array-buffer.js67
-rw-r--r--devtools/server/actors/breakpoint-list.js46
-rw-r--r--devtools/server/actors/breakpoint.js216
-rw-r--r--devtools/server/actors/changes.js122
-rw-r--r--devtools/server/actors/common.js116
-rw-r--r--devtools/server/actors/compatibility/compatibility.js169
-rw-r--r--devtools/server/actors/compatibility/lib/MDNCompatibility.js496
-rw-r--r--devtools/server/actors/compatibility/lib/moz.build11
-rw-r--r--devtools/server/actors/compatibility/lib/test/xpcshell/.eslintrc.js6
-rw-r--r--devtools/server/actors/compatibility/lib/test/xpcshell/head.js8
-rw-r--r--devtools/server/actors/compatibility/lib/test/xpcshell/test_mdn-compatibility.js186
-rw-r--r--devtools/server/actors/compatibility/lib/test/xpcshell/xpcshell.ini7
-rw-r--r--devtools/server/actors/compatibility/moz.build16
-rw-r--r--devtools/server/actors/css-properties.js121
-rw-r--r--devtools/server/actors/descriptors/moz.build12
-rw-r--r--devtools/server/actors/descriptors/process.js169
-rw-r--r--devtools/server/actors/descriptors/tab.js216
-rw-r--r--devtools/server/actors/descriptors/webextension.js252
-rw-r--r--devtools/server/actors/descriptors/worker.js253
-rw-r--r--devtools/server/actors/device.js83
-rw-r--r--devtools/server/actors/emulation/content-viewer.js128
-rw-r--r--devtools/server/actors/emulation/moz.build11
-rw-r--r--devtools/server/actors/emulation/responsive.js424
-rw-r--r--devtools/server/actors/emulation/touch-simulator.js426
-rw-r--r--devtools/server/actors/environment.js201
-rw-r--r--devtools/server/actors/errordocs.js205
-rw-r--r--devtools/server/actors/frame.js223
-rw-r--r--devtools/server/actors/framerate.js32
-rw-r--r--devtools/server/actors/heap-snapshot-file.js83
-rw-r--r--devtools/server/actors/highlighters.css963
-rw-r--r--devtools/server/actors/highlighters.js393
-rw-r--r--devtools/server/actors/highlighters/accessible.js387
-rw-r--r--devtools/server/actors/highlighters/auto-refresh.js318
-rw-r--r--devtools/server/actors/highlighters/box-model.js875
-rw-r--r--devtools/server/actors/highlighters/css-grid.js1958
-rw-r--r--devtools/server/actors/highlighters/css-transform.js265
-rw-r--r--devtools/server/actors/highlighters/eye-dropper.js581
-rw-r--r--devtools/server/actors/highlighters/flexbox.js1037
-rw-r--r--devtools/server/actors/highlighters/fonts.js122
-rw-r--r--devtools/server/actors/highlighters/geometry-editor.js796
-rw-r--r--devtools/server/actors/highlighters/measuring-tool.js763
-rw-r--r--devtools/server/actors/highlighters/moz.build28
-rw-r--r--devtools/server/actors/highlighters/node-tabbing-order.js399
-rw-r--r--devtools/server/actors/highlighters/paused-debugger.js255
-rw-r--r--devtools/server/actors/highlighters/rulers.js341
-rw-r--r--devtools/server/actors/highlighters/selector.js97
-rw-r--r--devtools/server/actors/highlighters/shapes.js3259
-rw-r--r--devtools/server/actors/highlighters/tabbing-order.js237
-rw-r--r--devtools/server/actors/highlighters/utils/accessibility.js769
-rw-r--r--devtools/server/actors/highlighters/utils/canvas.js596
-rw-r--r--devtools/server/actors/highlighters/utils/markup.js856
-rw-r--r--devtools/server/actors/highlighters/utils/moz.build7
-rw-r--r--devtools/server/actors/inspector/constants.js17
-rw-r--r--devtools/server/actors/inspector/css-logic.js1653
-rw-r--r--devtools/server/actors/inspector/custom-element-watcher.js146
-rw-r--r--devtools/server/actors/inspector/document-walker.js223
-rw-r--r--devtools/server/actors/inspector/event-collector.js1065
-rw-r--r--devtools/server/actors/inspector/inspector.js331
-rw-r--r--devtools/server/actors/inspector/moz.build21
-rw-r--r--devtools/server/actors/inspector/node-picker.js311
-rw-r--r--devtools/server/actors/inspector/node.js741
-rw-r--r--devtools/server/actors/inspector/utils.js587
-rw-r--r--devtools/server/actors/inspector/walker.js2879
-rw-r--r--devtools/server/actors/layout.js521
-rw-r--r--devtools/server/actors/manifest.js38
-rw-r--r--devtools/server/actors/media-rule.js82
-rw-r--r--devtools/server/actors/memory.js86
-rw-r--r--devtools/server/actors/moz.build94
-rw-r--r--devtools/server/actors/network-monitor/channel-event-sink.js101
-rw-r--r--devtools/server/actors/network-monitor/eventsource-actor.js86
-rw-r--r--devtools/server/actors/network-monitor/moz.build23
-rw-r--r--devtools/server/actors/network-monitor/network-content.js144
-rw-r--r--devtools/server/actors/network-monitor/network-event-actor.js550
-rw-r--r--devtools/server/actors/network-monitor/network-event.js594
-rw-r--r--devtools/server/actors/network-monitor/network-monitor.js277
-rw-r--r--devtools/server/actors/network-monitor/network-observer.js1721
-rw-r--r--devtools/server/actors/network-monitor/network-parent.js146
-rw-r--r--devtools/server/actors/network-monitor/network-response-listener.js588
-rw-r--r--devtools/server/actors/network-monitor/stack-trace-collector.js207
-rw-r--r--devtools/server/actors/network-monitor/utils/channel-map.js74
-rw-r--r--devtools/server/actors/network-monitor/utils/error-codes.js564
-rw-r--r--devtools/server/actors/network-monitor/utils/moz.build7
-rw-r--r--devtools/server/actors/network-monitor/utils/wildcard-to-regexp.js26
-rw-r--r--devtools/server/actors/network-monitor/websocket-actor.js151
-rw-r--r--devtools/server/actors/object.js810
-rw-r--r--devtools/server/actors/object/moz.build12
-rw-r--r--devtools/server/actors/object/previewers.js898
-rw-r--r--devtools/server/actors/object/property-iterator.js493
-rw-r--r--devtools/server/actors/object/stringifiers.js198
-rw-r--r--devtools/server/actors/object/symbol-iterator.js66
-rw-r--r--devtools/server/actors/object/symbol.js109
-rw-r--r--devtools/server/actors/object/utils.js541
-rw-r--r--devtools/server/actors/page-style.js1408
-rw-r--r--devtools/server/actors/pause-scoped.js98
-rw-r--r--devtools/server/actors/perf.js62
-rw-r--r--devtools/server/actors/performance-recording.js163
-rw-r--r--devtools/server/actors/performance.js163
-rw-r--r--devtools/server/actors/preference.js104
-rw-r--r--devtools/server/actors/process.js79
-rw-r--r--devtools/server/actors/reflow.js514
-rw-r--r--devtools/server/actors/resources/console-messages.js247
-rw-r--r--devtools/server/actors/resources/css-changes.js42
-rw-r--r--devtools/server/actors/resources/css-messages.js133
-rw-r--r--devtools/server/actors/resources/document-event.js52
-rw-r--r--devtools/server/actors/resources/error-messages.js158
-rw-r--r--devtools/server/actors/resources/index.js301
-rw-r--r--devtools/server/actors/resources/moz.build28
-rw-r--r--devtools/server/actors/resources/network-events-stacktraces.js203
-rw-r--r--devtools/server/actors/resources/network-events.js233
-rw-r--r--devtools/server/actors/resources/platform-messages.js53
-rw-r--r--devtools/server/actors/resources/sources.js69
-rw-r--r--devtools/server/actors/resources/storage-local-storage.js19
-rw-r--r--devtools/server/actors/resources/storage-session-storage.js19
-rw-r--r--devtools/server/actors/resources/stylesheets.js703
-rw-r--r--devtools/server/actors/resources/utils/content-process-storage.js218
-rw-r--r--devtools/server/actors/resources/utils/moz.build13
-rw-r--r--devtools/server/actors/resources/utils/nsi-console-listener-watcher.js187
-rw-r--r--devtools/server/actors/root.js608
-rw-r--r--devtools/server/actors/screenshot.js44
-rw-r--r--devtools/server/actors/source.js751
-rw-r--r--devtools/server/actors/storage.js3768
-rw-r--r--devtools/server/actors/string.js41
-rw-r--r--devtools/server/actors/style-rule.js1168
-rw-r--r--devtools/server/actors/style-sheet.js528
-rw-r--r--devtools/server/actors/style-sheets.js387
-rw-r--r--devtools/server/actors/targets/browsing-context.js1899
-rw-r--r--devtools/server/actors/targets/chrome-window.js112
-rw-r--r--devtools/server/actors/targets/content-process.js242
-rw-r--r--devtools/server/actors/targets/frame.js66
-rw-r--r--devtools/server/actors/targets/index.js12
-rw-r--r--devtools/server/actors/targets/moz.build18
-rw-r--r--devtools/server/actors/targets/parent-process.js165
-rw-r--r--devtools/server/actors/targets/target-actor-mixin.js121
-rw-r--r--devtools/server/actors/targets/target-actor-registry.jsm79
-rw-r--r--devtools/server/actors/targets/webextension.js430
-rw-r--r--devtools/server/actors/targets/worker.js114
-rw-r--r--devtools/server/actors/thread.js2258
-rw-r--r--devtools/server/actors/utils/accessibility.js125
-rw-r--r--devtools/server/actors/utils/actor-registry.js441
-rw-r--r--devtools/server/actors/utils/breakpoint-actor-map.js72
-rw-r--r--devtools/server/actors/utils/capture-screenshot.js212
-rw-r--r--devtools/server/actors/utils/css-grid-utils.js77
-rw-r--r--devtools/server/actors/utils/dbg-source.js97
-rw-r--r--devtools/server/actors/utils/event-breakpoints.js478
-rw-r--r--devtools/server/actors/utils/event-loop.js201
-rw-r--r--devtools/server/actors/utils/inactive-property-helper.js1072
-rw-r--r--devtools/server/actors/utils/logEvent.js97
-rw-r--r--devtools/server/actors/utils/make-debugger.js110
-rw-r--r--devtools/server/actors/utils/moz.build28
-rw-r--r--devtools/server/actors/utils/shapes-utils.js149
-rw-r--r--devtools/server/actors/utils/source-map-utils.js53
-rw-r--r--devtools/server/actors/utils/source-url.js38
-rw-r--r--devtools/server/actors/utils/sources-manager.js503
-rw-r--r--devtools/server/actors/utils/stack.js183
-rw-r--r--devtools/server/actors/utils/style-utils.js185
-rw-r--r--devtools/server/actors/utils/track-change-emitter.js26
-rw-r--r--devtools/server/actors/utils/walker-search.js313
-rw-r--r--devtools/server/actors/utils/watchpoint-map.js163
-rw-r--r--devtools/server/actors/watcher.js530
-rw-r--r--devtools/server/actors/watcher/WatchedDataHelpers.jsm124
-rw-r--r--devtools/server/actors/watcher/WatcherRegistry.jsm346
-rw-r--r--devtools/server/actors/watcher/moz.build14
-rw-r--r--devtools/server/actors/watcher/target-helpers/frame-helper.js204
-rw-r--r--devtools/server/actors/watcher/target-helpers/moz.build12
-rw-r--r--devtools/server/actors/watcher/target-helpers/process-helper.js281
-rw-r--r--devtools/server/actors/watcher/target-helpers/utils.js126
-rw-r--r--devtools/server/actors/watcher/target-helpers/worker-helper.js144
-rw-r--r--devtools/server/actors/webbrowser.js790
-rw-r--r--devtools/server/actors/webconsole.js2215
-rw-r--r--devtools/server/actors/webconsole/commands.js245
-rw-r--r--devtools/server/actors/webconsole/content-process-forward.js143
-rw-r--r--devtools/server/actors/webconsole/eager-ecma-allowlist.js158
-rw-r--r--devtools/server/actors/webconsole/eager-function-allowlist.js72
-rw-r--r--devtools/server/actors/webconsole/eval-with-debugger.js619
-rw-r--r--devtools/server/actors/webconsole/listeners/console-api.js203
-rw-r--r--devtools/server/actors/webconsole/listeners/console-file-activity.js129
-rw-r--r--devtools/server/actors/webconsole/listeners/console-reflow.js93
-rw-r--r--devtools/server/actors/webconsole/listeners/console-service.js176
-rw-r--r--devtools/server/actors/webconsole/listeners/content-process.js50
-rw-r--r--devtools/server/actors/webconsole/listeners/document-events.js78
-rw-r--r--devtools/server/actors/webconsole/listeners/moz.build14
-rw-r--r--devtools/server/actors/webconsole/message-manager-mock.js70
-rw-r--r--devtools/server/actors/webconsole/moz.build22
-rw-r--r--devtools/server/actors/webconsole/utils.js685
-rw-r--r--devtools/server/actors/webconsole/webidl-deprecated-list.js43
-rw-r--r--devtools/server/actors/webconsole/webidl-pure-allowlist.js72
-rw-r--r--devtools/server/actors/webconsole/worker-listeners.js35
-rw-r--r--devtools/server/actors/worker/moz.build14
-rw-r--r--devtools/server/actors/worker/push-subscription.js41
-rw-r--r--devtools/server/actors/worker/service-worker-process.js41
-rw-r--r--devtools/server/actors/worker/service-worker-registration-list.js113
-rw-r--r--devtools/server/actors/worker/service-worker-registration.js335
-rw-r--r--devtools/server/actors/worker/service-worker.js45
-rw-r--r--devtools/server/actors/worker/worker-descriptor-actor-list.js212
211 files changed, 73900 insertions, 0 deletions
diff --git a/devtools/server/actors/accessibility/accessibility.js b/devtools/server/actors/accessibility/accessibility.js
new file mode 100644
index 0000000000..034edc5c74
--- /dev/null
+++ b/devtools/server/actors/accessibility/accessibility.js
@@ -0,0 +1,140 @@
+/* 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";
+
+const Services = require("Services");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { accessibilitySpec } = require("devtools/shared/specs/accessibility");
+
+loader.lazyRequireGetter(
+ this,
+ "AccessibleWalkerActor",
+ "devtools/server/actors/accessibility/walker",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "SimulatorActor",
+ "devtools/server/actors/accessibility/simulator",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isWebRenderEnabled",
+ "devtools/server/actors/utils/accessibility",
+ true
+);
+
+/**
+ * The AccessibilityActor is a top level container actor that initializes
+ * accessible walker and is the top-most point of interaction for accessibility
+ * tools UI for a top level content process.
+ */
+const AccessibilityActor = ActorClassWithSpec(accessibilitySpec, {
+ initialize(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ // This event is fired when accessibility service is initialized or shut
+ // down. "init" and "shutdown" events are only relayed when the enabled
+ // state matches the event (e.g. the event came from the same process as
+ // the actor).
+ Services.obs.addObserver(this, "a11y-init-or-shutdown");
+ this.targetActor = targetActor;
+ },
+
+ getTraits: function() {
+ // The traits are used to know if accessibility actors support particular
+ // API on the server side.
+ return {
+ // @backward-compat { version 84 } Fixed on the server by Bug 1654956.
+ tabbingOrder: true,
+ };
+ },
+
+ bootstrap() {
+ return {
+ enabled: this.enabled,
+ };
+ },
+
+ get enabled() {
+ return Services.appinfo.accessibilityEnabled;
+ },
+
+ /**
+ * Observe Accessibility service init and shutdown events. It relays these
+ * events to AccessibilityFront if the event is fired for the a11y service
+ * that lives in the same process.
+ *
+ * @param {null} subject
+ * Not used.
+ * @param {String} topic
+ * Name of the a11y service event: "a11y-init-or-shutdown".
+ * @param {String} data
+ * "0" corresponds to shutdown and "1" to init.
+ */
+ observe(subject, topic, data) {
+ const enabled = data === "1";
+ if (enabled && this.enabled) {
+ this.emit("init");
+ } else if (!enabled && !this.enabled) {
+ if (this.walker) {
+ this.walker.reset();
+ }
+
+ this.emit("shutdown");
+ }
+ },
+
+ /**
+ * Get or create AccessibilityWalker actor, similar to WalkerActor.
+ *
+ * @return {Object}
+ * AccessibleWalkerActor for the current tab.
+ */
+ getWalker() {
+ if (!this.walker) {
+ this.walker = new AccessibleWalkerActor(this.conn, this.targetActor);
+ this.manage(this.walker);
+ }
+ return this.walker;
+ },
+
+ /**
+ * Get or create Simulator actor, managed by AccessibilityActor,
+ * only if webrender is enabled. Simulator applies color filters on an entire
+ * viewport. This needs to be done using webrender and not an SVG
+ * <feColorMatrix> since it is accelerated and scrolling with filter applied
+ * needs to be smooth (Bug1431466).
+ *
+ * @return {Object|null}
+ * SimulatorActor for the current tab.
+ */
+ getSimulator() {
+ // TODO: Remove this check after Bug1570667
+ if (!isWebRenderEnabled(this.targetActor.window)) {
+ return null;
+ }
+
+ if (!this.simulator) {
+ this.simulator = new SimulatorActor(this.conn, this.targetActor);
+ this.manage(this.simulator);
+ }
+
+ return this.simulator;
+ },
+
+ /**
+ * Destroy accessibility actor. This method also shutsdown accessibility
+ * service if possible.
+ */
+ async destroy() {
+ Actor.prototype.destroy.call(this);
+ Services.obs.removeObserver(this, "a11y-init-or-shutdown");
+ this.walker = null;
+ this.targetActor = null;
+ },
+});
+
+exports.AccessibilityActor = AccessibilityActor;
diff --git a/devtools/server/actors/accessibility/accessible.js b/devtools/server/actors/accessibility/accessible.js
new file mode 100644
index 0000000000..b81997ada4
--- /dev/null
+++ b/devtools/server/actors/accessibility/accessible.js
@@ -0,0 +1,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";
+
+const { Ci, Cu } = require("chrome");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { accessibleSpec } = require("devtools/shared/specs/accessibility");
+const {
+ accessibility: { AUDIT_TYPE },
+} = require("devtools/shared/constants");
+
+loader.lazyRequireGetter(
+ this,
+ "getContrastRatioFor",
+ "devtools/server/actors/accessibility/audit/contrast",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "auditKeyboard",
+ "devtools/server/actors/accessibility/audit/keyboard",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "auditTextLabel",
+ "devtools/server/actors/accessibility/audit/text-label",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isDefunct",
+ "devtools/server/actors/utils/accessibility",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "findCssSelector",
+ "devtools/shared/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(this, "events", "devtools/shared/event-emitter");
+loader.lazyRequireGetter(
+ this,
+ "getBounds",
+ "devtools/server/actors/highlighters/utils/accessibility",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isRemoteFrame",
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "ContentDOMReference",
+ "resource://gre/modules/ContentDOMReference.jsm",
+ true
+);
+
+const RELATIONS_TO_IGNORE = new Set([
+ Ci.nsIAccessibleRelation.RELATION_CONTAINING_APPLICATION,
+ Ci.nsIAccessibleRelation.RELATION_CONTAINING_TAB_PANE,
+ Ci.nsIAccessibleRelation.RELATION_CONTAINING_WINDOW,
+ Ci.nsIAccessibleRelation.RELATION_PARENT_WINDOW_OF,
+ Ci.nsIAccessibleRelation.RELATION_SUBWINDOW_OF,
+]);
+
+const nsIAccessibleRole = Ci.nsIAccessibleRole;
+const TEXT_ROLES = new Set([
+ nsIAccessibleRole.ROLE_TEXT_LEAF,
+ nsIAccessibleRole.ROLE_STATICTEXT,
+]);
+
+const STATE_DEFUNCT = Ci.nsIAccessibleStates.EXT_STATE_DEFUNCT;
+const CSS_TEXT_SELECTOR = "#text";
+
+/**
+ * Get node inforamtion such as nodeType and the unique CSS selector for the node.
+ * @param {DOMNode} node
+ * Node for which to get the information.
+ * @return {Object}
+ * Information about the type of the node and how to locate it.
+ */
+function getNodeDescription(node) {
+ if (!node || Cu.isDeadWrapper(node)) {
+ return { nodeType: undefined, nodeCssSelector: "" };
+ }
+
+ const { nodeType } = node;
+ return {
+ nodeType,
+ // If node is a text node, we find a unique CSS selector for its parent and add a
+ // CSS_TEXT_SELECTOR postfix to indicate that it's a text node.
+ nodeCssSelector:
+ nodeType === Node.TEXT_NODE
+ ? `${findCssSelector(node.parentNode)}${CSS_TEXT_SELECTOR}`
+ : findCssSelector(node),
+ };
+}
+
+/**
+ * Get a snapshot of the nsIAccessible object including its subtree. None of the subtree
+ * queried here is cached via accessible walker's refMap.
+ * @param {nsIAccessible} acc
+ * Accessible object to take a snapshot of.
+ * @param {nsIAccessibilityService} a11yService
+ * Accessibility service instance in the current process, used to get localized
+ * string representation of various accessible properties.
+ * @return {JSON}
+ * JSON snapshot of the accessibility tree with root at current accessible.
+ */
+function getSnapshot(acc, a11yService) {
+ if (isDefunct(acc)) {
+ return {
+ states: [a11yService.getStringStates(0, STATE_DEFUNCT)],
+ };
+ }
+
+ const actions = [];
+ for (let i = 0; i < acc.actionCount; i++) {
+ actions.push(acc.getActionDescription(i));
+ }
+
+ const attributes = {};
+ if (acc.attributes) {
+ for (const { key, value } of acc.attributes.enumerate()) {
+ attributes[key] = value;
+ }
+ }
+
+ const state = {};
+ const extState = {};
+ acc.getState(state, extState);
+ const states = [...a11yService.getStringStates(state.value, extState.value)];
+
+ const children = [];
+ for (let child = acc.firstChild; child; child = child.nextSibling) {
+ children.push(getSnapshot(child, a11yService));
+ }
+
+ const { nodeType, nodeCssSelector } = getNodeDescription(acc.DOMNode);
+ const snapshot = {
+ name: acc.name,
+ role: a11yService.getStringRole(acc.role),
+ actions,
+ value: acc.value,
+ nodeCssSelector,
+ nodeType,
+ description: acc.description,
+ keyboardShortcut: acc.accessKey || acc.keyboardShortcut,
+ childCount: acc.childCount,
+ indexInParent: acc.indexInParent,
+ states,
+ children,
+ attributes,
+ };
+ const remoteFrame =
+ acc.role === Ci.nsIAccessibleRole.ROLE_INTERNAL_FRAME &&
+ isRemoteFrame(acc.DOMNode);
+ if (remoteFrame) {
+ snapshot.remoteFrame = remoteFrame;
+ snapshot.childCount = 1;
+ snapshot.contentDOMReference = ContentDOMReference.get(acc.DOMNode);
+ }
+
+ return snapshot;
+}
+
+/**
+ * The AccessibleActor provides information about a given accessible object: its
+ * role, name, states, etc.
+ */
+const AccessibleActor = ActorClassWithSpec(accessibleSpec, {
+ initialize(walker, rawAccessible) {
+ Actor.prototype.initialize.call(this, null);
+ this.walker = walker;
+ this.rawAccessible = rawAccessible;
+
+ /**
+ * Indicates if the raw accessible is no longer alive.
+ *
+ * @return Boolean
+ */
+ Object.defineProperty(this, "isDefunct", {
+ get() {
+ const defunct = isDefunct(this.rawAccessible);
+ if (defunct) {
+ delete this.isDefunct;
+ this.isDefunct = true;
+ return this.isDefunct;
+ }
+
+ return defunct;
+ },
+ configurable: true,
+ });
+ },
+
+ /**
+ * Instead of storing a connection object, the NodeActor gets its connection
+ * from its associated walker.
+ */
+ get conn() {
+ return this.walker.conn;
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+ this.walker = null;
+ this.rawAccessible = null;
+ },
+
+ get role() {
+ if (this.isDefunct) {
+ return null;
+ }
+ return this.walker.a11yService.getStringRole(this.rawAccessible.role);
+ },
+
+ get name() {
+ if (this.isDefunct) {
+ return null;
+ }
+ return this.rawAccessible.name;
+ },
+
+ get value() {
+ if (this.isDefunct) {
+ return null;
+ }
+ return this.rawAccessible.value;
+ },
+
+ get description() {
+ if (this.isDefunct) {
+ return null;
+ }
+ return this.rawAccessible.description;
+ },
+
+ get keyboardShortcut() {
+ if (this.isDefunct) {
+ return null;
+ }
+ // Gecko accessibility exposes two key bindings: Accessible::AccessKey and
+ // Accessible::KeyboardShortcut. The former is used for accesskey, where the latter
+ // is used for global shortcuts defined by XUL menu items, etc. Here - do what the
+ // Windows implementation does: try AccessKey first, and if that's empty, use
+ // KeyboardShortcut.
+ return this.rawAccessible.accessKey || this.rawAccessible.keyboardShortcut;
+ },
+
+ get childCount() {
+ if (this.isDefunct) {
+ return 0;
+ }
+ // In case of a remote frame declare at least one child (the #document
+ // element) so that they can be expanded.
+ if (this.remoteFrame) {
+ return 1;
+ }
+
+ return this.rawAccessible.childCount;
+ },
+
+ get domNodeType() {
+ if (this.isDefunct) {
+ return 0;
+ }
+ return this.rawAccessible.DOMNode ? this.rawAccessible.DOMNode.nodeType : 0;
+ },
+
+ get parentAcc() {
+ if (this.isDefunct) {
+ return null;
+ }
+ return this.walker.addRef(this.rawAccessible.parent);
+ },
+
+ children() {
+ const children = [];
+ if (this.isDefunct) {
+ return children;
+ }
+
+ for (
+ let child = this.rawAccessible.firstChild;
+ child;
+ child = child.nextSibling
+ ) {
+ children.push(this.walker.addRef(child));
+ }
+ return children;
+ },
+
+ get indexInParent() {
+ if (this.isDefunct) {
+ return -1;
+ }
+
+ try {
+ return this.rawAccessible.indexInParent;
+ } catch (e) {
+ // Accessible is dead.
+ return -1;
+ }
+ },
+
+ get actions() {
+ const actions = [];
+ if (this.isDefunct) {
+ return actions;
+ }
+
+ for (let i = 0; i < this.rawAccessible.actionCount; i++) {
+ actions.push(this.rawAccessible.getActionDescription(i));
+ }
+ return actions;
+ },
+
+ get states() {
+ if (this.isDefunct) {
+ return [];
+ }
+
+ const state = {};
+ const extState = {};
+ this.rawAccessible.getState(state, extState);
+ return [
+ ...this.walker.a11yService.getStringStates(state.value, extState.value),
+ ];
+ },
+
+ get attributes() {
+ if (this.isDefunct || !this.rawAccessible.attributes) {
+ return {};
+ }
+
+ const attributes = {};
+ for (const { key, value } of this.rawAccessible.attributes.enumerate()) {
+ attributes[key] = value;
+ }
+
+ return attributes;
+ },
+
+ get bounds() {
+ if (this.isDefunct) {
+ return null;
+ }
+
+ let x = {},
+ y = {},
+ w = {},
+ h = {};
+ try {
+ this.rawAccessible.getBoundsInCSSPixels(x, y, w, h);
+ x = x.value;
+ y = y.value;
+ w = w.value;
+ h = h.value;
+ } catch (e) {
+ return null;
+ }
+
+ // Check if accessible bounds are invalid.
+ const left = x,
+ right = x + w,
+ top = y,
+ bottom = y + h;
+ if (left === right || top === bottom) {
+ return null;
+ }
+
+ return { x, y, w, h };
+ },
+
+ async getRelations() {
+ const relationObjects = [];
+ if (this.isDefunct) {
+ return relationObjects;
+ }
+
+ const relations = [
+ ...this.rawAccessible.getRelations().enumerate(Ci.nsIAccessibleRelation),
+ ];
+ if (relations.length === 0) {
+ return relationObjects;
+ }
+
+ const doc = await this.walker.getDocument();
+ if (this.isDestroyed()) {
+ // This accessible actor is destroyed.
+ return relationObjects;
+ }
+ relations.forEach(relation => {
+ if (RELATIONS_TO_IGNORE.has(relation.relationType)) {
+ return;
+ }
+
+ const type = this.walker.a11yService.getStringRelationType(
+ relation.relationType
+ );
+ const targets = [...relation.getTargets().enumerate(Ci.nsIAccessible)];
+ let relationObject;
+ for (const target of targets) {
+ let targetAcc;
+ try {
+ targetAcc = this.walker.attachAccessible(target, doc.rawAccessible);
+ } catch (e) {
+ // Target is not available.
+ }
+
+ if (targetAcc) {
+ if (!relationObject) {
+ relationObject = { type, targets: [] };
+ }
+
+ relationObject.targets.push(targetAcc);
+ }
+ }
+
+ if (relationObject) {
+ relationObjects.push(relationObject);
+ }
+ });
+
+ return relationObjects;
+ },
+
+ get remoteFrame() {
+ if (this.isDefunct) {
+ return false;
+ }
+
+ return (
+ this.rawAccessible.role === Ci.nsIAccessibleRole.ROLE_INTERNAL_FRAME &&
+ isRemoteFrame(this.rawAccessible.DOMNode)
+ );
+ },
+
+ form() {
+ return {
+ actor: this.actorID,
+ role: this.role,
+ name: this.name,
+ remoteFrame: this.remoteFrame,
+ childCount: this.childCount,
+ checks: this._lastAudit,
+ };
+ },
+
+ /**
+ * Provide additional (full) information about the accessible object that is
+ * otherwise missing from the form.
+ *
+ * @return {Object}
+ * Object that contains accessible object information such as states,
+ * actions, attributes, etc.
+ */
+ hydrate() {
+ return {
+ value: this.value,
+ description: this.description,
+ keyboardShortcut: this.keyboardShortcut,
+ domNodeType: this.domNodeType,
+ indexInParent: this.indexInParent,
+ states: this.states,
+ actions: this.actions,
+ attributes: this.attributes,
+ };
+ },
+
+ _isValidTextLeaf(rawAccessible) {
+ return (
+ !isDefunct(rawAccessible) &&
+ TEXT_ROLES.has(rawAccessible.role) &&
+ rawAccessible.name &&
+ rawAccessible.name.trim().length > 0
+ );
+ },
+
+ /**
+ * Calculate the contrast ratio of the given accessible.
+ */
+ async _getContrastRatio() {
+ if (!this._isValidTextLeaf(this.rawAccessible)) {
+ return null;
+ }
+
+ const { bounds } = this;
+ if (!bounds) {
+ return null;
+ }
+
+ const { DOMNode: rawNode } = this.rawAccessible;
+ const win = rawNode.ownerGlobal;
+
+ // Keep the reference to the walker actor in case the actor gets destroyed
+ // during the colour contrast ratio calculation.
+ const { walker } = this;
+ await walker.clearStyles(win);
+ const contrastRatio = await getContrastRatioFor(rawNode.parentNode, {
+ bounds: getBounds(win, bounds),
+ win,
+ appliedColorMatrix: this.walker.colorMatrix,
+ });
+
+ if (this.isDestroyed()) {
+ // This accessible actor is destroyed.
+ return null;
+ }
+ await walker.restoreStyles(win);
+
+ return contrastRatio;
+ },
+
+ /**
+ * Run an accessibility audit for a given audit type.
+ * @param {String} type
+ * Type of an audit (Check AUDIT_TYPE in devtools/shared/constants
+ * to see available audit types).
+ *
+ * @return {null|Object}
+ * Object that contains accessible audit data for a given type or null
+ * if there's nothing to report for this accessible.
+ */
+ _getAuditByType(type) {
+ switch (type) {
+ case AUDIT_TYPE.CONTRAST:
+ return this._getContrastRatio();
+ case AUDIT_TYPE.KEYBOARD:
+ // Determine if keyboard accessibility is lacking where it is necessary.
+ return auditKeyboard(this.rawAccessible);
+ case AUDIT_TYPE.TEXT_LABEL:
+ // Determine if text alternative is missing for an accessible where it
+ // is necessary.
+ return auditTextLabel(this.rawAccessible);
+ default:
+ return null;
+ }
+ },
+
+ /**
+ * Audit the state of the accessible object.
+ *
+ * @param {Object} options
+ * Options for running audit, may include:
+ * - types: Array of audit types to be performed during audit.
+ *
+ * @return {Object|null}
+ * Audit results for the accessible object.
+ */
+ audit(options = {}) {
+ if (this._auditing) {
+ return this._auditing;
+ }
+
+ const { types } = options;
+ let auditTypes = Object.values(AUDIT_TYPE);
+ if (types && types.length > 0) {
+ auditTypes = auditTypes.filter(auditType => types.includes(auditType));
+ }
+
+ // For some reason keyboard checks for focus styling affect values (that are
+ // used by other types of checks (text names and values)) returned by
+ // accessible objects. This happens only when multiple checks are run at the
+ // same time (asynchronously) and the audit might return unexpected
+ // failures. We thus split the execution of the checks into two parts, first
+ // performing keyboard checks and only after the rest of the checks. See bug
+ // 1594743 for more detail.
+ let keyboardAuditResult;
+ const keyboardAuditIndex = auditTypes.indexOf(AUDIT_TYPE.KEYBOARD);
+ if (keyboardAuditIndex > -1) {
+ // If we are performing a keyboard audit, remove its value from the
+ // complete list and run it.
+ auditTypes.splice(keyboardAuditIndex, 1);
+ keyboardAuditResult = this._getAuditByType(AUDIT_TYPE.KEYBOARD);
+ }
+
+ this._auditing = Promise.resolve(keyboardAuditResult)
+ .then(keyboardResult => {
+ const audits = auditTypes.map(auditType =>
+ this._getAuditByType(auditType)
+ );
+
+ // If we are also performing a keyboard audit, add its type and its
+ // result back to the complete list of audits.
+ if (keyboardAuditIndex > -1) {
+ auditTypes.splice(keyboardAuditIndex, 0, AUDIT_TYPE.KEYBOARD);
+ audits.splice(keyboardAuditIndex, 0, keyboardResult);
+ }
+
+ return Promise.all(audits);
+ })
+ .then(results => {
+ if (this.isDefunct || this.isDestroyed()) {
+ return null;
+ }
+
+ const audit = results.reduce((auditResults, result, index) => {
+ auditResults[auditTypes[index]] = result;
+ return auditResults;
+ }, {});
+ this._lastAudit = this._lastAudit || {};
+ Object.assign(this._lastAudit, audit);
+ events.emit(this, "audited", audit);
+
+ return audit;
+ })
+ .catch(error => {
+ if (!this.isDefunct && !this.isDestroyed()) {
+ throw error;
+ }
+ return null;
+ })
+ .finally(() => {
+ this._auditing = null;
+ });
+
+ return this._auditing;
+ },
+
+ snapshot() {
+ return getSnapshot(this.rawAccessible, this.walker.a11yService);
+ },
+});
+
+exports.AccessibleActor = AccessibleActor;
diff --git a/devtools/server/actors/accessibility/audit/contrast.js b/devtools/server/actors/accessibility/audit/contrast.js
new file mode 100644
index 0000000000..4fad31893e
--- /dev/null
+++ b/devtools/server/actors/accessibility/audit/contrast.js
@@ -0,0 +1,307 @@
+/* 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";
+
+loader.lazyRequireGetter(this, "colorUtils", "devtools/shared/css/color", true);
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getCurrentZoom",
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "addPseudoClassLock",
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "removePseudoClassLock",
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getContrastRatioAgainstBackground",
+ "devtools/shared/accessibility",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getTextProperties",
+ "devtools/shared/accessibility",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "DevToolsWorker",
+ "devtools/shared/worker/worker",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "InspectorActorUtils",
+ "devtools/server/actors/inspector/utils"
+);
+
+const WORKER_URL = "resource://devtools/server/actors/accessibility/worker.js";
+const HIGHLIGHTED_PSEUDO_CLASS = ":-moz-devtools-highlighted";
+const {
+ LARGE_TEXT: { BOLD_LARGE_TEXT_MIN_PIXELS, LARGE_TEXT_MIN_PIXELS },
+} = require("devtools/shared/accessibility");
+
+loader.lazyGetter(this, "worker", () => new DevToolsWorker(WORKER_URL));
+
+/**
+ * Get canvas rendering context for the current target window bound by the bounds of the
+ * accessible objects.
+ * @param {Object} win
+ * Current target window.
+ * @param {Object} bounds
+ * Bounds for the accessible object.
+ * @param {Object} zoom
+ * Current zoom level for the window.
+ * @param {Object} scale
+ * Scale value to scale down the drawn image.
+ * @param {null|DOMNode} node
+ * If not null, a node that corresponds to the accessible object to be used to
+ * make its text color transparent.
+ * @return {CanvasRenderingContext2D}
+ * Canvas rendering context for the current window.
+ */
+function getImageCtx(win, bounds, zoom, scale, node) {
+ const doc = win.document;
+ const canvas = doc.createElementNS("http://www.w3.org/1999/xhtml", "canvas");
+
+ const { left, top, width, height } = bounds;
+ canvas.width = width * zoom * scale;
+ canvas.height = height * zoom * scale;
+ const ctx = canvas.getContext("2d", { alpha: false });
+ ctx.imageSmoothingEnabled = false;
+ ctx.scale(scale, scale);
+
+ // If node is passed, make its color related text properties invisible.
+ if (node) {
+ addPseudoClassLock(node, HIGHLIGHTED_PSEUDO_CLASS);
+ }
+
+ ctx.drawWindow(
+ win,
+ left * zoom,
+ top * zoom,
+ width * zoom,
+ height * zoom,
+ "#fff",
+ ctx.DRAWWINDOW_USE_WIDGET_LAYERS
+ );
+
+ // Restore all inline styling.
+ if (node) {
+ removePseudoClassLock(node, HIGHLIGHTED_PSEUDO_CLASS);
+ }
+
+ return ctx;
+}
+
+/**
+ * Calculate the transformed RGBA when a color matrix is set in docShell by
+ * multiplying the color matrix with the RGBA vector.
+ *
+ * @param {Array} rgba
+ * Original RGBA array which we want to transform.
+ * @param {Array} colorMatrix
+ * Flattened 4x5 color matrix that is set in docShell.
+ * A 4x5 matrix of the form:
+ * 1 2 3 4 5
+ * 6 7 8 9 10
+ * 11 12 13 14 15
+ * 16 17 18 19 20
+ * will be set in docShell as:
+ * [1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20]
+ * @return {Array}
+ * Transformed RGBA after the color matrix is multiplied with the original RGBA.
+ */
+function getTransformedRGBA(rgba, colorMatrix) {
+ const transformedRGBA = [0, 0, 0, 0];
+
+ // Only use the first four columns of the color matrix corresponding to R, G, B and A
+ // color channels respectively. The fifth column is a fixed offset that does not need
+ // to be considered for the matrix multiplication. We end up multiplying a 4x4 color
+ // matrix with a 4x1 RGBA vector.
+ for (let i = 0; i < 16; i++) {
+ const row = i % 4;
+ const col = Math.floor(i / 4);
+ transformedRGBA[row] += colorMatrix[i] * rgba[col];
+ }
+
+ return transformedRGBA;
+}
+
+/**
+ * Find RGBA or a range of RGBAs for the background pixels under the text.
+ *
+ * @param {DOMNode} node
+ * Node for which we want to get the background color data.
+ * @param {Object} options
+ * - bounds {Object}
+ * Bounds for the accessible object.
+ * - win {Object}
+ * Target window.
+ * - size {Number}
+ * Font size of the selected text node
+ * - isBoldText {Boolean}
+ * True if selected text node is bold
+ * @return {Object}
+ * Object with one or more of the following RGBA fields: value, min, max
+ */
+function getBackgroundFor(node, { win, bounds, size, isBoldText }) {
+ const zoom = 1 / getCurrentZoom(win);
+ // When calculating colour contrast, we traverse image data for text nodes that are
+ // drawn both with and without transparent text. Image data arrays are typically really
+ // big. In cases when the font size is fairly large or when the page is zoomed in image
+ // data is especially large (retrieving it and/or traversing it takes significant amount
+ // of time). Here we optimize the size of the image data by scaling down the drawn nodes
+ // to a size where their text size equals either BOLD_LARGE_TEXT_MIN_PIXELS or
+ // LARGE_TEXT_MIN_PIXELS (lower threshold for large text size) depending on the font
+ // weight.
+ //
+ // IMPORTANT: this optimization, in some cases where background colour is non-uniform
+ // (gradient or image), can result in small (not noticeable) blending of the background
+ // colours. In turn this might affect the reported values of the contrast ratio. The
+ // delta is fairly small (<0.1) to noticeably skew the results.
+ //
+ // NOTE: this optimization does not help in cases where contrast is being calculated for
+ // nodes with a lot of text.
+ let scale =
+ ((isBoldText ? BOLD_LARGE_TEXT_MIN_PIXELS : LARGE_TEXT_MIN_PIXELS) / size) *
+ zoom;
+ // We do not need to scale the images if the font is smaller than large or if the page
+ // is zoomed out (scaling in this case would've been scaling up).
+ scale = scale > 1 ? 1 : scale;
+
+ const textContext = getImageCtx(win, bounds, zoom, scale);
+ const backgroundContext = getImageCtx(win, bounds, zoom, scale, node);
+
+ const { data: dataText } = textContext.getImageData(
+ 0,
+ 0,
+ bounds.width * scale,
+ bounds.height * scale
+ );
+ const { data: dataBackground } = backgroundContext.getImageData(
+ 0,
+ 0,
+ bounds.width * scale,
+ bounds.height * scale
+ );
+
+ return worker.performTask(
+ "getBgRGBA",
+ {
+ dataTextBuf: dataText.buffer,
+ dataBackgroundBuf: dataBackground.buffer,
+ },
+ [dataText.buffer, dataBackground.buffer]
+ );
+}
+
+/**
+ * Calculates the contrast ratio of the referenced DOM node.
+ *
+ * @param {DOMNode} node
+ * The node for which we want to calculate the contrast ratio.
+ * @param {Object} options
+ * - bounds {Object}
+ * Bounds for the accessible object.
+ * - win {Object}
+ * Target window.
+ * - appliedColorMatrix {Array|null}
+ * Simulation color matrix applied to
+ * to the viewport, if it exists.
+ * @return {Object}
+ * An object that may contain one or more of the following fields: error,
+ * isLargeText, value, min, max values for contrast.
+ */
+async function getContrastRatioFor(node, options = {}) {
+ const computedStyle = CssLogic.getComputedStyle(node);
+ const props = computedStyle ? getTextProperties(computedStyle) : null;
+
+ if (!props) {
+ return {
+ error: true,
+ };
+ }
+
+ const { isLargeText, isBoldText, size, opacity } = props;
+ const { appliedColorMatrix } = options;
+ const color = appliedColorMatrix
+ ? getTransformedRGBA(props.color, appliedColorMatrix)
+ : props.color;
+ let rgba = await getBackgroundFor(node, {
+ ...options,
+ isBoldText,
+ size,
+ });
+
+ if (!rgba) {
+ // Fallback (original) contrast calculation algorithm. It tries to get the
+ // closest background colour for the node and use it to calculate contrast.
+ const backgroundColor = InspectorActorUtils.getClosestBackgroundColor(node);
+ const backgroundImage = InspectorActorUtils.getClosestBackgroundImage(node);
+
+ if (backgroundImage !== "none") {
+ // Both approaches failed, at this point we don't have a better one yet.
+ return {
+ error: true,
+ };
+ }
+
+ let { r, g, b, a } = colorUtils.colorToRGBA(backgroundColor, true);
+ // If the element has opacity in addition to background alpha value, take it
+ // into account. TODO: this does not handle opacity set on ancestor
+ // elements (see bug https://bugzilla.mozilla.org/show_bug.cgi?id=1544721).
+ if (opacity < 1) {
+ a = opacity * a;
+ }
+
+ return getContrastRatioAgainstBackground(
+ {
+ value: appliedColorMatrix
+ ? getTransformedRGBA([r, g, b, a], appliedColorMatrix)
+ : [r, g, b, a],
+ },
+ {
+ color,
+ isLargeText,
+ }
+ );
+ }
+
+ if (appliedColorMatrix) {
+ rgba = rgba.value
+ ? {
+ value: getTransformedRGBA(rgba.value, appliedColorMatrix),
+ }
+ : {
+ min: getTransformedRGBA(rgba.min, appliedColorMatrix),
+ max: getTransformedRGBA(rgba.max, appliedColorMatrix),
+ };
+ }
+
+ return getContrastRatioAgainstBackground(rgba, {
+ color,
+ isLargeText,
+ });
+}
+
+exports.getContrastRatioFor = getContrastRatioFor;
+exports.getBackgroundFor = getBackgroundFor;
diff --git a/devtools/server/actors/accessibility/audit/keyboard.js b/devtools/server/actors/accessibility/audit/keyboard.js
new file mode 100644
index 0000000000..75539dc58c
--- /dev/null
+++ b/devtools/server/actors/accessibility/audit/keyboard.js
@@ -0,0 +1,516 @@
+/* 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";
+
+const { Ci, Cu } = require("chrome");
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getCSSStyleRules",
+ "devtools/shared/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(this, "InspectorUtils", "InspectorUtils");
+loader.lazyRequireGetter(
+ this,
+ "nodeConstants",
+ "devtools/shared/dom-node-constants"
+);
+loader.lazyRequireGetter(
+ this,
+ ["isDefunct", "getAriaRoles"],
+ "devtools/server/actors/utils/accessibility",
+ true
+);
+
+const {
+ accessibility: {
+ AUDIT_TYPE: { KEYBOARD },
+ ISSUE_TYPE: {
+ [KEYBOARD]: {
+ FOCUSABLE_NO_SEMANTICS,
+ FOCUSABLE_POSITIVE_TABINDEX,
+ INTERACTIVE_NO_ACTION,
+ INTERACTIVE_NOT_FOCUSABLE,
+ MOUSE_INTERACTIVE_ONLY,
+ NO_FOCUS_VISIBLE,
+ },
+ },
+ SCORES: { FAIL, WARNING },
+ },
+} = require("devtools/shared/constants");
+
+// Specified by the author CSS rule type.
+const STYLE_RULE = 1;
+
+// Accessible action for showing long description.
+const CLICK_ACTION = "click";
+
+/**
+ * Focus specific pseudo classes that the keyboard audit simulates to determine
+ * focus styling.
+ */
+const FOCUS_PSEUDO_CLASS = ":focus";
+const MOZ_FOCUSRING_PSEUDO_CLASS = ":-moz-focusring";
+
+const KEYBOARD_FOCUSABLE_ROLES = new Set([
+ Ci.nsIAccessibleRole.ROLE_BUTTONMENU,
+ Ci.nsIAccessibleRole.ROLE_CHECKBUTTON,
+ Ci.nsIAccessibleRole.ROLE_COMBOBOX,
+ Ci.nsIAccessibleRole.ROLE_EDITCOMBOBOX,
+ Ci.nsIAccessibleRole.ROLE_ENTRY,
+ Ci.nsIAccessibleRole.ROLE_LINK,
+ Ci.nsIAccessibleRole.ROLE_LISTBOX,
+ Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT,
+ Ci.nsIAccessibleRole.ROLE_PUSHBUTTON,
+ Ci.nsIAccessibleRole.ROLE_RADIOBUTTON,
+ Ci.nsIAccessibleRole.ROLE_SLIDER,
+ Ci.nsIAccessibleRole.ROLE_SPINBUTTON,
+ Ci.nsIAccessibleRole.ROLE_SUMMARY,
+ Ci.nsIAccessibleRole.ROLE_SWITCH,
+ Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON,
+]);
+
+const INTERACTIVE_ROLES = new Set([
+ ...KEYBOARD_FOCUSABLE_ROLES,
+ Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM,
+ Ci.nsIAccessibleRole.ROLE_CHECK_RICH_OPTION,
+ Ci.nsIAccessibleRole.ROLE_COMBOBOX_OPTION,
+ Ci.nsIAccessibleRole.ROLE_MENUITEM,
+ Ci.nsIAccessibleRole.ROLE_OPTION,
+ Ci.nsIAccessibleRole.ROLE_OUTLINE,
+ Ci.nsIAccessibleRole.ROLE_OUTLINEITEM,
+ Ci.nsIAccessibleRole.ROLE_PAGETAB,
+ Ci.nsIAccessibleRole.ROLE_PARENT_MENUITEM,
+ Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM,
+ Ci.nsIAccessibleRole.ROLE_RICH_OPTION,
+]);
+
+const INTERACTIVE_IF_FOCUSABLE_ROLES = new Set([
+ // If article is focusable, we can assume it is inside a feed.
+ Ci.nsIAccessibleRole.ROLE_ARTICLE,
+ // Column header can be focusable.
+ Ci.nsIAccessibleRole.ROLE_COLUMNHEADER,
+ Ci.nsIAccessibleRole.ROLE_GRID_CELL,
+ Ci.nsIAccessibleRole.ROLE_MENUBAR,
+ Ci.nsIAccessibleRole.ROLE_MENUPOPUP,
+ Ci.nsIAccessibleRole.ROLE_PAGETABLIST,
+ // Row header can be focusable.
+ Ci.nsIAccessibleRole.ROLE_ROWHEADER,
+ Ci.nsIAccessibleRole.ROLE_SCROLLBAR,
+ Ci.nsIAccessibleRole.ROLE_SEPARATOR,
+ Ci.nsIAccessibleRole.ROLE_TOOLBAR,
+]);
+
+/**
+ * Determine if a node is dead or is not an element node.
+ *
+ * @param {DOMNode} node
+ * Node to be tested for validity.
+ *
+ * @returns {Boolean}
+ * True if the node is either dead or is not an element node.
+ */
+function isInvalidNode(node) {
+ return (
+ !node ||
+ Cu.isDeadWrapper(node) ||
+ node.nodeType !== nodeConstants.ELEMENT_NODE ||
+ !node.ownerGlobal
+ );
+}
+
+/**
+ * Determine if accessible is focusable with the keyboard.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible for which to determine if it is keyboard focusable.
+ *
+ * @returns {Boolean}
+ * True if focusable with the keyboard.
+ */
+function isKeyboardFocusable(accessible) {
+ const state = {};
+ accessible.getState(state, {});
+ // State will be focusable even if the tabindex is negative.
+ return (
+ state.value & Ci.nsIAccessibleStates.STATE_FOCUSABLE &&
+ // Platform accessibility will still report STATE_FOCUSABLE even with the
+ // tabindex="-1" so we need to check that it is >= 0 to be considered
+ // keyboard focusable.
+ accessible.DOMNode.tabIndex > -1
+ );
+}
+
+/**
+ * Determine if a current node has focus specific styling by applying a
+ * focus-related pseudo class (such as :focus or :-moz-focusring) to a focusable
+ * node.
+ *
+ * @param {DOMNode} focusableNode
+ * Node to apply focus-related pseudo class to.
+ * @param {DOMNode} currentNode
+ * Node to be checked for having focus specific styling.
+ * @param {String} pseudoClass
+ * A focus related pseudo-class to be simulated for style comparison.
+ *
+ * @returns {Boolean}
+ * True if the currentNode has focus specific styling.
+ */
+function hasStylesForFocusRelatedPseudoClass(
+ focusableNode,
+ currentNode,
+ pseudoClass
+) {
+ const defaultRules = getCSSStyleRules(currentNode);
+
+ InspectorUtils.addPseudoClassLock(focusableNode, pseudoClass);
+
+ // Determine a set of properties that are specific to CSS rules that are only
+ // present when a focus related pseudo-class is locked in.
+ const tempRules = getCSSStyleRules(currentNode);
+ const properties = new Set();
+ for (const rule of tempRules) {
+ if (rule.type !== STYLE_RULE) {
+ continue;
+ }
+
+ if (!defaultRules.includes(rule)) {
+ for (let index = 0; index < rule.style.length; index++) {
+ properties.add(rule.style.item(index));
+ }
+ }
+ }
+
+ // If there are no focus specific CSS rules or properties, currentNode does
+ // node have any focus specific styling, we are done.
+ if (properties.size === 0) {
+ InspectorUtils.removePseudoClassLock(focusableNode, pseudoClass);
+ return false;
+ }
+
+ // Determine values for properties that are focus specific.
+ const tempStyle = CssLogic.getComputedStyle(currentNode);
+ const focusStyle = {};
+ for (const name of properties.values()) {
+ focusStyle[name] = tempStyle.getPropertyValue(name);
+ }
+
+ InspectorUtils.removePseudoClassLock(focusableNode, pseudoClass);
+
+ // If values for focus specific properties are different from default style
+ // values, assume we have focus spefic styles for the currentNode.
+ const defaultStyle = CssLogic.getComputedStyle(currentNode);
+ for (const name of properties.values()) {
+ if (defaultStyle.getPropertyValue(name) !== focusStyle[name]) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Check if an element node (currentNode) has distinct focus styling. This
+ * function also takes into account a case when focus styling is applied to a
+ * descendant too.
+ *
+ * @param {DOMNode} focusableNode
+ * Node to apply focus-related pseudo class to.
+ * @param {DOMNode} currentNode
+ * Node to be checked for having focus specific styling.
+ *
+ * @returns {Boolean}
+ * True if the node or its descendant has distinct focus styling.
+ */
+function hasFocusStyling(focusableNode, currentNode) {
+ if (isInvalidNode(currentNode)) {
+ return false;
+ }
+
+ // Check if an element node has distinct :-moz-focusring styling.
+ const hasStylesForMozFocusring = hasStylesForFocusRelatedPseudoClass(
+ focusableNode,
+ currentNode,
+ MOZ_FOCUSRING_PSEUDO_CLASS
+ );
+ if (hasStylesForMozFocusring) {
+ return true;
+ }
+
+ // Check if an element node has distinct :focus styling.
+ const hasStylesForFocus = hasStylesForFocusRelatedPseudoClass(
+ focusableNode,
+ currentNode,
+ FOCUS_PSEUDO_CLASS
+ );
+ if (hasStylesForFocus) {
+ return true;
+ }
+
+ // If no element specific focus styles where found, check if its element
+ // children have them.
+ for (
+ let child = currentNode.firstElementChild;
+ child;
+ child = currentNode.nextnextElementSibling
+ ) {
+ if (hasFocusStyling(focusableNode, child)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+/**
+ * A rule that determines if a focusable accessible object has appropriate focus
+ * styling.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible to be checked for being focusable and having focus
+ * styling.
+ *
+ * @return {null|Object}
+ * Null if accessible has keyboard focus styling, audit report object
+ * otherwise.
+ */
+function focusStyleRule(accessible) {
+ const { DOMNode } = accessible;
+ if (isInvalidNode(DOMNode)) {
+ return null;
+ }
+
+ // Ignore non-focusable elements.
+ if (!isKeyboardFocusable(accessible)) {
+ return null;
+ }
+
+ if (hasFocusStyling(DOMNode, DOMNode)) {
+ return null;
+ }
+
+ // If no browser or author focus styling was found, check if the node is a
+ // widget that is themed by platform native theme.
+ if (InspectorUtils.isElementThemed(DOMNode)) {
+ return null;
+ }
+
+ return { score: WARNING, issue: NO_FOCUS_VISIBLE };
+}
+
+/**
+ * A rule that determines if an interactive accessible has any associated
+ * accessible actions with it. If the element is interactive but and has no
+ * actions, assistive technology users will not be able to interact with it.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible to be checked for being interactive and having accessible
+ * actions.
+ *
+ * @return {null|Object}
+ * Null if accessible is not interactive or if it is and it has
+ * accessible action associated with it, audit report object otherwise.
+ */
+function interactiveRule(accessible) {
+ if (!INTERACTIVE_ROLES.has(accessible.role)) {
+ return null;
+ }
+
+ if (accessible.actionCount > 0) {
+ return null;
+ }
+
+ return { score: FAIL, issue: INTERACTIVE_NO_ACTION };
+}
+
+/**
+ * A rule that determines if an interactive accessible is also focusable when
+ * not disabled.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible to be checked for being interactive and being focusable
+ * when enabled.
+ *
+ * @return {null|Object}
+ * Null if accessible is not interactive or if it is and it is focusable
+ * when enabled, audit report object otherwise.
+ */
+function focusableRule(accessible) {
+ if (!KEYBOARD_FOCUSABLE_ROLES.has(accessible.role)) {
+ return null;
+ }
+
+ const state = {};
+ accessible.getState(state, {});
+ // We only expect in interactive accessible object to be focusable if it is
+ // not disabled.
+ if (state.value & Ci.nsIAccessibleStates.STATE_UNAVAILABLE) {
+ return null;
+ }
+
+ if (isKeyboardFocusable(accessible)) {
+ return null;
+ }
+
+ const ariaRoles = getAriaRoles(accessible);
+ if (
+ ariaRoles &&
+ (ariaRoles.includes("combobox") || ariaRoles.includes("listbox"))
+ ) {
+ // Do not force ARIA combobox or listbox to be focusable.
+ return null;
+ }
+
+ return { score: FAIL, issue: INTERACTIVE_NOT_FOCUSABLE };
+}
+
+/**
+ * A rule that determines if a focusable accessible has an associated
+ * interactive role.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible to be checked for having an interactive role if it is
+ * focusable.
+ *
+ * @return {null|Object}
+ * Null if accessible is not interactive or if it is and it has an
+ * interactive role, audit report object otherwise.
+ */
+function semanticsRule(accessible) {
+ if (
+ INTERACTIVE_ROLES.has(accessible.role) ||
+ // Visible listboxes will have focusable state when inside comboboxes.
+ accessible.role === Ci.nsIAccessibleRole.ROLE_COMBOBOX_LIST
+ ) {
+ return null;
+ }
+
+ if (isKeyboardFocusable(accessible)) {
+ if (INTERACTIVE_IF_FOCUSABLE_ROLES.has(accessible.role)) {
+ return null;
+ }
+
+ // ROLE_TABLE is used for grids too which are considered interactive.
+ if (accessible.role === Ci.nsIAccessibleRole.ROLE_TABLE) {
+ const ariaRoles = getAriaRoles(accessible);
+ if (ariaRoles && ariaRoles.includes("grid")) {
+ return null;
+ }
+ }
+
+ return { score: WARNING, issue: FOCUSABLE_NO_SEMANTICS };
+ }
+
+ const state = {};
+ accessible.getState(state, {});
+ if (
+ // Ignore text leafs.
+ accessible.role === Ci.nsIAccessibleRole.ROLE_TEXT_LEAF ||
+ // Ignore accessibles with no accessible actions.
+ accessible.actionCount === 0 ||
+ // Ignore labels that have a label for relation with their target because
+ // they are clickable.
+ (accessible.role === Ci.nsIAccessibleRole.ROLE_LABEL &&
+ accessible.getRelationByType(Ci.nsIAccessibleRelation.RELATION_LABEL_FOR)
+ .targetsCount > 0) ||
+ // Ignore images that are inside an anchor (have linked state).
+ (accessible.role === Ci.nsIAccessibleRole.ROLE_GRAPHIC &&
+ state.value & Ci.nsIAccessibleStates.STATE_LINKED)
+ ) {
+ return null;
+ }
+
+ // Ignore anything but a click action in the list of actions.
+ for (let i = 0; i < accessible.actionCount; i++) {
+ if (accessible.getActionName(i) === CLICK_ACTION) {
+ return { score: FAIL, issue: MOUSE_INTERACTIVE_ONLY };
+ }
+ }
+
+ return null;
+}
+
+/**
+ * A rule that determines if an element associated with a focusable accessible
+ * has a positive tabindex.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible to be checked for having an element with positive tabindex
+ * attribute.
+ *
+ * @return {null|Object}
+ * Null if accessible is not focusable or if it is and its element's
+ * tabindex attribute is less than 1, audit report object otherwise.
+ */
+function tabIndexRule(accessible) {
+ const { DOMNode } = accessible;
+ if (isInvalidNode(DOMNode)) {
+ return null;
+ }
+
+ if (!isKeyboardFocusable(accessible)) {
+ return null;
+ }
+
+ if (DOMNode.tabIndex > 0) {
+ return { score: WARNING, issue: FOCUSABLE_POSITIVE_TABINDEX };
+ }
+
+ return null;
+}
+
+function auditKeyboard(accessible) {
+ if (isDefunct(accessible)) {
+ return null;
+ }
+ // Do not test anything on accessible objects for documents or frames.
+ if (
+ accessible.role === Ci.nsIAccessibleRole.ROLE_DOCUMENT ||
+ accessible.role === Ci.nsIAccessibleRole.ROLE_INTERNAL_FRAME
+ ) {
+ return null;
+ }
+
+ // Check if interactive accessible can be used by the assistive
+ // technology.
+ let issue = interactiveRule(accessible);
+ if (issue) {
+ return issue;
+ }
+
+ // Check if interactive accessible is also focusable when enabled.
+ issue = focusableRule(accessible);
+ if (issue) {
+ return issue;
+ }
+
+ // Check if accessible object has an element with a positive tabindex.
+ issue = tabIndexRule(accessible);
+ if (issue) {
+ return issue;
+ }
+
+ // Check if a focusable accessible has interactive semantics.
+ issue = semanticsRule(accessible);
+ if (issue) {
+ return issue;
+ }
+
+ // Check if focusable accessible has associated focus styling.
+ issue = focusStyleRule(accessible);
+ if (issue) {
+ return issue;
+ }
+
+ return issue;
+}
+
+module.exports.auditKeyboard = auditKeyboard;
diff --git a/devtools/server/actors/accessibility/audit/moz.build b/devtools/server/actors/accessibility/audit/moz.build
new file mode 100644
index 0000000000..01bd0af849
--- /dev/null
+++ b/devtools/server/actors/accessibility/audit/moz.build
@@ -0,0 +1,12 @@
+# 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/.
+
+DevToolsModules(
+ "contrast.js",
+ "keyboard.js",
+ "text-label.js",
+)
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Accessibility Tools")
diff --git a/devtools/server/actors/accessibility/audit/text-label.js b/devtools/server/actors/accessibility/audit/text-label.js
new file mode 100644
index 0000000000..02f3b31b2a
--- /dev/null
+++ b/devtools/server/actors/accessibility/audit/text-label.js
@@ -0,0 +1,435 @@
+/* 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";
+
+const { Ci } = require("chrome");
+
+const {
+ accessibility: {
+ AUDIT_TYPE: { TEXT_LABEL },
+ ISSUE_TYPE,
+ SCORES: { BEST_PRACTICES, FAIL, WARNING },
+ },
+} = require("devtools/shared/constants");
+
+const {
+ AREA_NO_NAME_FROM_ALT,
+ DIALOG_NO_NAME,
+ DOCUMENT_NO_TITLE,
+ EMBED_NO_NAME,
+ FIGURE_NO_NAME,
+ FORM_FIELDSET_NO_NAME,
+ FORM_FIELDSET_NO_NAME_FROM_LEGEND,
+ FORM_NO_NAME,
+ FORM_NO_VISIBLE_NAME,
+ FORM_OPTGROUP_NO_NAME_FROM_LABEL,
+ FRAME_NO_NAME,
+ HEADING_NO_CONTENT,
+ HEADING_NO_NAME,
+ IFRAME_NO_NAME_FROM_TITLE,
+ IMAGE_NO_NAME,
+ INTERACTIVE_NO_NAME,
+ MATHML_GLYPH_NO_NAME,
+ TOOLBAR_NO_NAME,
+} = ISSUE_TYPE[TEXT_LABEL];
+
+/**
+ * Check if the accessible is visible to the assistive technology.
+ * @param {nsIAccessible} accessible
+ * Accessible object to be tested for visibility.
+ *
+ * @returns {Boolean}
+ * True if accessible object is visible to assistive technology.
+ */
+function isVisible(accessible) {
+ const state = {};
+ accessible.getState(state, {});
+ return !(state.value & Ci.nsIAccessibleStates.STATE_INVISIBLE);
+}
+
+/**
+ * Get related accessible objects that are targets of labelled by relation e.g.
+ * labels.
+ * @param {nsIAccessible} accessible
+ * Accessible objects to get labels for.
+ *
+ * @returns {Array}
+ * A list of accessible objects that are labels for a given accessible.
+ */
+function getLabels(accessible) {
+ const relation = accessible.getRelationByType(
+ Ci.nsIAccessibleRelation.RELATION_LABELLED_BY
+ );
+ return [...relation.getTargets().enumerate(Ci.nsIAccessible)];
+}
+
+/**
+ * Get a trimmed name of the accessible object.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible objects to get a name for.
+ *
+ * @returns {null|String}
+ * Trimmed name of the accessible object if available.
+ */
+function getAccessibleName(accessible) {
+ return accessible.name && accessible.name.trim();
+}
+
+/**
+ * A text label rule for accessible objects that must have a non empty
+ * accessible name.
+ *
+ * @returns {null|Object}
+ * Failure audit report if accessible object has no or empty name, null
+ * otherwise.
+ */
+const mustHaveNonEmptyNameRule = function(issue, accessible) {
+ const name = getAccessibleName(accessible);
+ return name ? null : { score: FAIL, issue };
+};
+
+/**
+ * A text label rule for accessible objects that should have a non empty
+ * accessible name as a best practice.
+ *
+ * @returns {null|Object}
+ * Best practices audit report if accessible object has no or empty
+ * name, null otherwise.
+ */
+const shouldHaveNonEmptyNameRule = function(issue, accessible) {
+ const name = getAccessibleName(accessible);
+ return name ? null : { score: BEST_PRACTICES, issue };
+};
+
+/**
+ * A text label rule for accessible objects that can be activated via user
+ * action and must have a non-empty name.
+ *
+ * @returns {null|Object}
+ * Failure audit report if interactive accessible object has no or
+ * empty name, null otherwise.
+ */
+const interactiveRule = mustHaveNonEmptyNameRule.bind(
+ null,
+ INTERACTIVE_NO_NAME
+);
+
+/**
+ * A text label rule for accessible objects that correspond to dialogs and thus
+ * should have a non-empty name.
+ *
+ * @returns {null|Object}
+ * Best practices audit report if dialog accessible object has no or
+ * empty name, null otherwise.
+ */
+const dialogRule = shouldHaveNonEmptyNameRule.bind(null, DIALOG_NO_NAME);
+
+/**
+ * A text label rule for accessible objects that provide visual information
+ * (images, canvas, etc.) and must have a defined name (that can be empty, e.g.
+ * "").
+ *
+ * @returns {null|Object}
+ * Failure audit report if interactive accessible object has no name,
+ * null otherwise.
+ */
+const imageRule = function(accessible) {
+ const name = getAccessibleName(accessible);
+ return name != null ? null : { score: FAIL, issue: IMAGE_NO_NAME };
+};
+
+/**
+ * A text label rule for accessible objects that correspond to form elements.
+ * These objects must have a non-empty name and must have a visible label.
+ *
+ * @returns {null|Object}
+ * Failure audit report if form element accessible object has no name,
+ * warning if the name does not come from a visible label, null
+ * otherwise.
+ */
+const formRule = function(accessible) {
+ const name = getAccessibleName(accessible);
+ if (!name) {
+ return { score: FAIL, issue: FORM_NO_NAME };
+ }
+
+ const labels = getLabels(accessible);
+ const hasNameFromVisibleLabel = labels.some(label => isVisible(label));
+
+ return hasNameFromVisibleLabel
+ ? null
+ : { score: WARNING, issue: FORM_NO_VISIBLE_NAME };
+};
+
+/**
+ * A text label rule for elements that map to ROLE_GROUPING:
+ * * <OPTGROUP> must have a non-empty name and must be provided via the
+ * "label" attribute.
+ * * <FIELDSET> must have a non-empty name and must be provided via the
+ * corresponding <LEGEND> element.
+ *
+ * @returns {null|Object}
+ * Failure audit report if form grouping accessible object has no name,
+ * or has a name that is not derived from a required location, null
+ * otherwise.
+ */
+const formGroupingRule = function(accessible) {
+ const name = getAccessibleName(accessible);
+ const { DOMNode } = accessible;
+
+ switch (DOMNode.nodeName) {
+ case "OPTGROUP":
+ return name && DOMNode.label && DOMNode.label.trim() === name
+ ? null
+ : {
+ score: FAIL,
+ issue: FORM_OPTGROUP_NO_NAME_FROM_LABEL,
+ };
+ case "FIELDSET":
+ if (!name) {
+ return { score: FAIL, issue: FORM_FIELDSET_NO_NAME };
+ }
+
+ const labels = getLabels(accessible);
+ const hasNameFromLegend = labels.some(
+ label =>
+ label.DOMNode.nodeName === "LEGEND" &&
+ label.name &&
+ label.name.trim() === name &&
+ isVisible(label)
+ );
+
+ return hasNameFromLegend
+ ? null
+ : {
+ score: WARNING,
+ issue: FORM_FIELDSET_NO_NAME_FROM_LEGEND,
+ };
+ default:
+ return null;
+ }
+};
+
+/**
+ * A text label rule for elements that map to ROLE_TEXT_CONTAINER:
+ * * <METER> mapps to ROLE_TEXT_CONTAINER and must have a name provided via
+ * the visible label. Note: Will only work when bug 559770 is resolved (right
+ * now, unlabelled meters are not mapped to an accessible object).
+ *
+ * @returns {null|Object}
+ * Failure audit report depending on requirements for dialogs or form
+ * meter element, null otherwise.
+ */
+const textContainerRule = function(accessible) {
+ const { DOMNode } = accessible;
+
+ switch (DOMNode.nodeName) {
+ case "DIALOG":
+ return dialogRule(accessible);
+ case "METER":
+ return formRule(accessible);
+ default:
+ return null;
+ }
+};
+
+/**
+ * A text label rule for elements that map to ROLE_INTERNAL_FRAME:
+ * * <OBJECT> maps to ROLE_INTERNAL_FRAME. Check the type attribute and whether
+ * it includes "image/" (e.g. image/jpeg, image/png, image/gif). If so, audit
+ * it the same way other image roles are audited.
+ * * <EMBED> maps to ROLE_INTERNAL_FRAME and must have a non-empty name.
+ * * <FRAME> and <IFRAME> map to ROLE_INTERNAL_FRAME and must have a non-empty
+ * title attribute.
+ *
+ * @returns {null|Object}
+ * Failure audit report if the internal frame accessible object name is
+ * not provided or if it is not derived from a required location, null
+ * otherwise.
+ */
+const internalFrameRule = function(accessible) {
+ const { DOMNode } = accessible;
+ switch (DOMNode.nodeName) {
+ case "FRAME":
+ return mustHaveNonEmptyNameRule(FRAME_NO_NAME, accessible);
+ case "IFRAME":
+ const name = getAccessibleName(accessible);
+ const title = DOMNode.title && DOMNode.title.trim();
+
+ return title && title === name
+ ? null
+ : { score: FAIL, issue: IFRAME_NO_NAME_FROM_TITLE };
+ case "OBJECT":
+ const type = DOMNode.getAttribute("type");
+ if (!type || !type.startsWith("image/")) {
+ return null;
+ }
+
+ return imageRule(accessible);
+ case "EMBED":
+ return mustHaveNonEmptyNameRule(EMBED_NO_NAME, accessible);
+ default:
+ return null;
+ }
+};
+
+/**
+ * A text label rule for accessible objects that represent documents and should
+ * have title element provided.
+ *
+ * @returns {null|Object}
+ * Failure audit report if document accessible object has no or empty
+ * title, null otherwise.
+ */
+const documentRule = function(accessible) {
+ const title = accessible.DOMNode.title && accessible.DOMNode.title.trim();
+ return title ? null : { score: FAIL, issue: DOCUMENT_NO_TITLE };
+};
+
+/**
+ * A text label rule for accessible objects that correspond to headings and thus
+ * must be non-empty.
+ *
+ * @returns {null|Object}
+ * Failure audit report if heading accessible object has no or
+ * empty name or if its text content is empty, null otherwise.
+ */
+const headingRule = function(accessible) {
+ const name = getAccessibleName(accessible);
+ if (!name) {
+ return { score: FAIL, issue: HEADING_NO_NAME };
+ }
+
+ const content =
+ accessible.DOMNode.textContent && accessible.DOMNode.textContent.trim();
+ return content ? null : { score: WARNING, issue: HEADING_NO_CONTENT };
+};
+
+/**
+ * A text label rule for accessible objects that represent toolbars and must
+ * have a non-empty name if there is more than one toolbar present.
+ *
+ * @returns {null|Object}
+ * Failure audit report if toolbar accessible object is not the only
+ * toolbar in the document and has no or empty title, null otherwise.
+ */
+const toolbarRule = function(accessible) {
+ const toolbars = accessible.DOMNode.ownerDocument.querySelectorAll(
+ `[role="toolbar"]`
+ );
+
+ return toolbars.length > 1
+ ? mustHaveNonEmptyNameRule(TOOLBAR_NO_NAME, accessible)
+ : null;
+};
+
+/**
+ * A text label rule for accessible objects that represent link (anchors, areas)
+ * and must have a non-empty name.
+ *
+ * @returns {null|Object}
+ * Failure audit report if link accessible object has no or empty name,
+ * or in case when it's an <area> element with href attribute the name
+ * is not specified by an alt attribute, null otherwise.
+ */
+const linkRule = function(accessible) {
+ const { DOMNode } = accessible;
+ if (DOMNode.nodeName === "AREA" && DOMNode.hasAttribute("href")) {
+ const alt = DOMNode.getAttribute("alt");
+ const name = getAccessibleName(accessible);
+ return alt && alt.trim() === name
+ ? null
+ : { score: FAIL, issue: AREA_NO_NAME_FROM_ALT };
+ }
+
+ return interactiveRule(accessible);
+};
+
+/**
+ * A text label rule for accessible objects that are used to display
+ * non-standard symbols where existing Unicode characters are not available and
+ * must have a non-empty name.
+ *
+ * @returns {null|Object}
+ * Failure audit report if mglyph accessible object has no or empty
+ * name, and no or empty alt attribute, null otherwise.
+ */
+const mathmlGlyphRule = function(accessible) {
+ const name = getAccessibleName(accessible);
+ if (name) {
+ return null;
+ }
+
+ const { DOMNode } = accessible;
+ const alt = DOMNode.getAttribute("alt");
+ return alt && alt.trim()
+ ? null
+ : { score: FAIL, issue: MATHML_GLYPH_NO_NAME };
+};
+
+const RULES = {
+ [Ci.nsIAccessibleRole.ROLE_BUTTONMENU]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_CANVAS]: imageRule,
+ [Ci.nsIAccessibleRole.ROLE_CHECKBUTTON]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_CHECK_RICH_OPTION]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_COLUMNHEADER]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_COMBOBOX]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_COMBOBOX_OPTION]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_DIAGRAM]: imageRule,
+ [Ci.nsIAccessibleRole.ROLE_DIALOG]: dialogRule,
+ [Ci.nsIAccessibleRole.ROLE_DOCUMENT]: documentRule,
+ [Ci.nsIAccessibleRole.ROLE_EDITCOMBOBOX]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_ENTRY]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_FIGURE]: shouldHaveNonEmptyNameRule.bind(
+ null,
+ FIGURE_NO_NAME
+ ),
+ [Ci.nsIAccessibleRole.ROLE_GRAPHIC]: imageRule,
+ [Ci.nsIAccessibleRole.ROLE_GROUPING]: formGroupingRule,
+ [Ci.nsIAccessibleRole.ROLE_HEADING]: headingRule,
+ [Ci.nsIAccessibleRole.ROLE_IMAGE_MAP]: imageRule,
+ [Ci.nsIAccessibleRole.ROLE_INTERNAL_FRAME]: internalFrameRule,
+ [Ci.nsIAccessibleRole.ROLE_LINK]: linkRule,
+ [Ci.nsIAccessibleRole.ROLE_LISTBOX]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_MATHML_GLYPH]: mathmlGlyphRule,
+ [Ci.nsIAccessibleRole.ROLE_MENUITEM]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_OPTION]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_OUTLINEITEM]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_PAGETAB]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_PASSWORD_TEXT]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_PROGRESSBAR]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_PUSHBUTTON]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_RADIOBUTTON]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_ROWHEADER]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_SLIDER]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_SPINBUTTON]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_SWITCH]: formRule,
+ [Ci.nsIAccessibleRole.ROLE_TEXT_CONTAINER]: textContainerRule,
+ [Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON]: interactiveRule,
+ [Ci.nsIAccessibleRole.ROLE_TOOLBAR]: toolbarRule,
+};
+
+/**
+ * Perform audit for WCAG 1.1 criteria related to providing alternative text
+ * depending on the type of content.
+ * @param {nsIAccessible} accessible
+ * Accessible object to be tested to determine if it requires and has
+ * an appropriate text alternative.
+ *
+ * @return {null|Object}
+ * Null if accessible does not need or has the right text alternative,
+ * audit data otherwise. This data is used in the accessibility panel
+ * for its audit filters, audit badges, sidebar checks section and
+ * highlighter.
+ */
+function auditTextLabel(accessible) {
+ const rule = RULES[accessible.role];
+ return rule ? rule(accessible) : null;
+}
+
+module.exports.auditTextLabel = auditTextLabel;
diff --git a/devtools/server/actors/accessibility/constants.js b/devtools/server/actors/accessibility/constants.js
new file mode 100644
index 0000000000..30956fb34b
--- /dev/null
+++ b/devtools/server/actors/accessibility/constants.js
@@ -0,0 +1,150 @@
+/* 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";
+
+const {
+ accessibility: {
+ SIMULATION_TYPE: {
+ ACHROMATOPSIA,
+ DEUTERANOPIA,
+ PROTANOPIA,
+ TRITANOPIA,
+ CONTRAST_LOSS,
+ },
+ },
+} = require("devtools/shared/constants");
+
+/**
+ * Constants used in accessibility actors.
+ */
+
+// Color blindness matrix values taken from Machado et al. (2009), https://doi.org/10.1109/TVCG.2009.113:
+// https://www.inf.ufrgs.br/~oliveira/pubs_files/CVD_Simulation/CVD_Simulation.html
+// Contrast loss matrix values are for 50% contrast (see https://docs.rainmeter.net/tips/colormatrix-guide/,
+// and https://stackoverflow.com/questions/23865511/contrast-with-color-matrix). The matrices are flattened
+// 4x5 matrices, needed for docShell setColorMatrix method. i.e. A 4x5 matrix of the form:
+// 1 2 3 4 5
+// 6 7 8 9 10
+// 11 12 13 14 15
+// 16 17 18 19 20
+// will be need to be set in docShell as:
+// [1, 6, 11, 16, 2, 7, 12, 17, 3, 8, 13, 18, 4, 9, 14, 19, 5, 10, 15, 20]
+const COLOR_TRANSFORMATION_MATRICES = {
+ NONE: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0],
+ [ACHROMATOPSIA]: [
+ 0.299,
+ 0.299,
+ 0.299,
+ 0,
+ 0.587,
+ 0.587,
+ 0.587,
+ 0,
+ 0.114,
+ 0.114,
+ 0.114,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ ],
+ [PROTANOPIA]: [
+ 0.152286,
+ 0.114503,
+ -0.003882,
+ 0,
+ 1.052583,
+ 0.786281,
+ -0.048116,
+ 0,
+ -0.204868,
+ 0.099216,
+ 1.051998,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ ],
+ [DEUTERANOPIA]: [
+ 0.367322,
+ 0.280085,
+ -0.01182,
+ 0,
+ 0.860646,
+ 0.672501,
+ 0.04294,
+ 0,
+ -0.227968,
+ 0.047413,
+ 0.968881,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ ],
+ [TRITANOPIA]: [
+ 1.255528,
+ -0.078411,
+ 0.004733,
+ 0,
+ -0.076749,
+ 0.930809,
+ 0.691367,
+ 0,
+ -0.178779,
+ 0.147602,
+ 0.3039,
+ 0,
+ 0,
+ 0,
+ 0,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ ],
+ [CONTRAST_LOSS]: [
+ 0.5,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0.5,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0.5,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0.5,
+ 0.25,
+ 0.25,
+ 0.25,
+ 0,
+ ],
+};
+
+exports.simulation = {
+ COLOR_TRANSFORMATION_MATRICES,
+};
diff --git a/devtools/server/actors/accessibility/moz.build b/devtools/server/actors/accessibility/moz.build
new file mode 100644
index 0000000000..4da1cd0b24
--- /dev/null
+++ b/devtools/server/actors/accessibility/moz.build
@@ -0,0 +1,20 @@
+# 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/.
+
+DIRS += [
+ "audit",
+]
+
+DevToolsModules(
+ "accessibility.js",
+ "accessible.js",
+ "constants.js",
+ "parent-accessibility.js",
+ "simulator.js",
+ "walker.js",
+ "worker.js",
+)
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Accessibility Tools")
diff --git a/devtools/server/actors/accessibility/parent-accessibility.js b/devtools/server/actors/accessibility/parent-accessibility.js
new file mode 100644
index 0000000000..dd314d9bf7
--- /dev/null
+++ b/devtools/server/actors/accessibility/parent-accessibility.js
@@ -0,0 +1,156 @@
+/* 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";
+
+const { Cc, Ci } = require("chrome");
+const Services = require("Services");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const {
+ parentAccessibilitySpec,
+} = require("devtools/shared/specs/accessibility");
+
+const PREF_ACCESSIBILITY_FORCE_DISABLED = "accessibility.force_disabled";
+
+const ParentAccessibilityActor = ActorClassWithSpec(parentAccessibilitySpec, {
+ initialize(conn) {
+ Actor.prototype.initialize.call(this, conn);
+
+ this.userPref = Services.prefs.getIntPref(
+ PREF_ACCESSIBILITY_FORCE_DISABLED
+ );
+
+ if (this.enabled && !this.accService) {
+ // Set a local reference to an accessibility service if accessibility was
+ // started elsewhere to ensure that parent process a11y service does not
+ // get GC'ed away.
+ this.accService = Cc["@mozilla.org/accessibilityService;1"].getService(
+ Ci.nsIAccessibilityService
+ );
+ }
+
+ Services.obs.addObserver(this, "a11y-consumers-changed");
+ Services.prefs.addObserver(PREF_ACCESSIBILITY_FORCE_DISABLED, this);
+ },
+
+ bootstrap() {
+ return {
+ canBeDisabled: this.canBeDisabled,
+ canBeEnabled: this.canBeEnabled,
+ };
+ },
+
+ observe(subject, topic, data) {
+ if (topic === "a11y-consumers-changed") {
+ // This event is fired when accessibility service consumers change. Since
+ // this observer lives in parent process there are 2 possible consumers of
+ // a11y service: XPCOM and PlatformAPI (e.g. screen readers). We only care
+ // about PlatformAPI consumer changes because when set, we can no longer
+ // disable accessibility service.
+ const { PlatformAPI } = JSON.parse(data);
+ this.emit("can-be-disabled-change", !PlatformAPI);
+ } else if (
+ !this.disabling &&
+ topic === "nsPref:changed" &&
+ data === PREF_ACCESSIBILITY_FORCE_DISABLED
+ ) {
+ // PREF_ACCESSIBILITY_FORCE_DISABLED preference change event. When set to
+ // >=1, it means that the user wants to disable accessibility service and
+ // prevent it from starting in the future. Note: we also check
+ // this.disabling state when handling this pref change because this is how
+ // we disable the accessibility inspector itself.
+ this.emit("can-be-enabled-change", this.canBeEnabled);
+ }
+ },
+
+ /**
+ * A getter that indicates if accessibility service is enabled.
+ *
+ * @return {Boolean}
+ * True if accessibility service is on.
+ */
+ get enabled() {
+ return Services.appinfo.accessibilityEnabled;
+ },
+
+ /**
+ * A getter that indicates if the accessibility service can be disabled.
+ *
+ * @return {Boolean}
+ * True if accessibility service can be disabled.
+ */
+ get canBeDisabled() {
+ if (this.enabled) {
+ const a11yService = Cc["@mozilla.org/accessibilityService;1"].getService(
+ Ci.nsIAccessibilityService
+ );
+ const { PlatformAPI } = JSON.parse(a11yService.getConsumers());
+ return !PlatformAPI;
+ }
+
+ return true;
+ },
+
+ /**
+ * A getter that indicates if the accessibility service can be enabled.
+ *
+ * @return {Boolean}
+ * True if accessibility service can be enabled.
+ */
+ get canBeEnabled() {
+ return Services.prefs.getIntPref(PREF_ACCESSIBILITY_FORCE_DISABLED) < 1;
+ },
+
+ /**
+ * Enable accessibility service (via XPCOM service).
+ */
+ enable() {
+ if (this.enabled || !this.canBeEnabled) {
+ return;
+ }
+
+ this.accService = Cc["@mozilla.org/accessibilityService;1"].getService(
+ Ci.nsIAccessibilityService
+ );
+ },
+
+ /**
+ * Force disable accessibility service. This method removes the reference to
+ * the XPCOM a11y service object and flips the
+ * PREF_ACCESSIBILITY_FORCE_DISABLED preference on and off to shutdown a11y
+ * service.
+ */
+ disable() {
+ if (!this.enabled || !this.canBeDisabled) {
+ return;
+ }
+
+ this.disabling = true;
+ this.accService = null;
+ // Set PREF_ACCESSIBILITY_FORCE_DISABLED to 1 to force disable
+ // accessibility service. This is the only way to guarantee an immediate
+ // accessibility service shutdown in all processes. This also prevents
+ // accessibility service from starting up in the future.
+ Services.prefs.setIntPref(PREF_ACCESSIBILITY_FORCE_DISABLED, 1);
+ // Set PREF_ACCESSIBILITY_FORCE_DISABLED back to previous default or user
+ // set value. This will not start accessibility service until the user
+ // activates it again. It simply ensures that accessibility service can
+ // start again (when value is below 1).
+ Services.prefs.setIntPref(PREF_ACCESSIBILITY_FORCE_DISABLED, this.userPref);
+ delete this.disabling;
+ },
+
+ /**
+ * Destroy thie helper class, remove all listeners and if possible disable
+ * accessibility service in the parent process.
+ */
+ destroy() {
+ Actor.prototype.destroy.call(this);
+ Services.obs.removeObserver(this, "a11y-consumers-changed");
+ Services.prefs.removeObserver(PREF_ACCESSIBILITY_FORCE_DISABLED, this);
+ this.accService = null;
+ },
+});
+
+exports.ParentAccessibilityActor = ParentAccessibilityActor;
diff --git a/devtools/server/actors/accessibility/simulator.js b/devtools/server/actors/accessibility/simulator.js
new file mode 100644
index 0000000000..6340ee2a47
--- /dev/null
+++ b/devtools/server/actors/accessibility/simulator.js
@@ -0,0 +1,78 @@
+/* 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";
+
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { simulatorSpec } = require("devtools/shared/specs/accessibility");
+const {
+ simulation: { COLOR_TRANSFORMATION_MATRICES },
+} = require("devtools/server/actors/accessibility/constants");
+
+/**
+ * The SimulatorActor is responsible for setting color matrices
+ * based on the simulation type specified.
+ */
+const SimulatorActor = ActorClassWithSpec(simulatorSpec, {
+ initialize(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ },
+
+ /**
+ * Simulates a type of visual impairment (i.e. color blindness or contrast loss).
+ *
+ * @param {Object} options
+ * Properties: {Array} types
+ * Contains the types of visual impairment(s) to be simulated.
+ * Set default color matrix if array is empty.
+ * @return {Boolean}
+ * True if matrix was successfully applied, false otherwise.
+ */
+ simulate(options) {
+ if (options.types.length > 1) {
+ return false;
+ }
+
+ return this.setColorMatrix(
+ COLOR_TRANSFORMATION_MATRICES[
+ options.types.length === 1 ? options.types[0] : "NONE"
+ ]
+ );
+ },
+
+ setColorMatrix(colorMatrix) {
+ if (!this.docShell) {
+ return false;
+ }
+
+ try {
+ this.docShell.setColorMatrix(colorMatrix);
+ } catch (error) {
+ return false;
+ }
+
+ return true;
+ },
+
+ /**
+ * Disables all simulations by setting the default color matrix.
+ */
+ disable() {
+ this.simulate({ types: [] });
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ this.disable();
+ this.targetActor = null;
+ },
+
+ get docShell() {
+ return this.targetActor && this.targetActor.docShell;
+ },
+});
+
+exports.SimulatorActor = SimulatorActor;
diff --git a/devtools/server/actors/accessibility/walker.js b/devtools/server/actors/accessibility/walker.js
new file mode 100644
index 0000000000..85d9388ef5
--- /dev/null
+++ b/devtools/server/actors/accessibility/walker.js
@@ -0,0 +1,1313 @@
+/* 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";
+
+const { Cc, Ci } = require("chrome");
+const Services = require("Services");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { accessibleWalkerSpec } = require("devtools/shared/specs/accessibility");
+const {
+ simulation: { COLOR_TRANSFORMATION_MATRICES },
+} = require("devtools/server/actors/accessibility/constants");
+
+loader.lazyRequireGetter(
+ this,
+ "AccessibleActor",
+ "devtools/server/actors/accessibility/accessible",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["CustomHighlighterActor"],
+ "devtools/server/actors/highlighters",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "DevToolsUtils",
+ "devtools/shared/DevToolsUtils"
+);
+loader.lazyRequireGetter(this, "events", "devtools/shared/event-emitter");
+loader.lazyRequireGetter(
+ this,
+ ["getCurrentZoom", "isWindowIncluded", "isRemoteFrame"],
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(this, "InspectorUtils", "InspectorUtils");
+loader.lazyRequireGetter(
+ this,
+ "isXUL",
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ [
+ "isDefunct",
+ "loadSheetForBackgroundCalculation",
+ "removeSheetForBackgroundCalculation",
+ ],
+ "devtools/server/actors/utils/accessibility",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "accessibility",
+ "devtools/shared/constants",
+ true
+);
+
+const kStateHover = 0x00000004; // NS_EVENT_STATE_HOVER
+
+const {
+ EVENT_TEXT_CHANGED,
+ EVENT_TEXT_INSERTED,
+ EVENT_TEXT_REMOVED,
+ EVENT_ACCELERATOR_CHANGE,
+ EVENT_ACTION_CHANGE,
+ EVENT_DEFACTION_CHANGE,
+ EVENT_DESCRIPTION_CHANGE,
+ EVENT_DOCUMENT_ATTRIBUTES_CHANGED,
+ EVENT_HIDE,
+ EVENT_NAME_CHANGE,
+ EVENT_OBJECT_ATTRIBUTE_CHANGED,
+ EVENT_REORDER,
+ EVENT_STATE_CHANGE,
+ EVENT_TEXT_ATTRIBUTE_CHANGED,
+ EVENT_VALUE_CHANGE,
+} = Ci.nsIAccessibleEvent;
+
+// TODO: We do not need this once bug 1422913 is fixed. We also would not need
+// to fire a name change event for an accessible that has an updated subtree and
+// that has its name calculated from the said subtree.
+const NAME_FROM_SUBTREE_RULE_ROLES = new Set([
+ Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWN,
+ Ci.nsIAccessibleRole.ROLE_BUTTONDROPDOWNGRID,
+ Ci.nsIAccessibleRole.ROLE_BUTTONMENU,
+ Ci.nsIAccessibleRole.ROLE_CELL,
+ Ci.nsIAccessibleRole.ROLE_CHECKBUTTON,
+ Ci.nsIAccessibleRole.ROLE_CHECK_MENU_ITEM,
+ Ci.nsIAccessibleRole.ROLE_CHECK_RICH_OPTION,
+ Ci.nsIAccessibleRole.ROLE_COLUMN,
+ Ci.nsIAccessibleRole.ROLE_COLUMNHEADER,
+ Ci.nsIAccessibleRole.ROLE_COMBOBOX_OPTION,
+ Ci.nsIAccessibleRole.ROLE_DEFINITION,
+ Ci.nsIAccessibleRole.ROLE_GRID_CELL,
+ Ci.nsIAccessibleRole.ROLE_HEADING,
+ Ci.nsIAccessibleRole.ROLE_HELPBALLOON,
+ Ci.nsIAccessibleRole.ROLE_HTML_CONTAINER,
+ Ci.nsIAccessibleRole.ROLE_KEY,
+ Ci.nsIAccessibleRole.ROLE_LABEL,
+ Ci.nsIAccessibleRole.ROLE_LINK,
+ Ci.nsIAccessibleRole.ROLE_LISTITEM,
+ Ci.nsIAccessibleRole.ROLE_MATHML_IDENTIFIER,
+ Ci.nsIAccessibleRole.ROLE_MATHML_NUMBER,
+ Ci.nsIAccessibleRole.ROLE_MATHML_OPERATOR,
+ Ci.nsIAccessibleRole.ROLE_MATHML_TEXT,
+ Ci.nsIAccessibleRole.ROLE_MATHML_STRING_LITERAL,
+ Ci.nsIAccessibleRole.ROLE_MATHML_GLYPH,
+ Ci.nsIAccessibleRole.ROLE_MENUITEM,
+ Ci.nsIAccessibleRole.ROLE_OPTION,
+ Ci.nsIAccessibleRole.ROLE_OUTLINEITEM,
+ Ci.nsIAccessibleRole.ROLE_PAGETAB,
+ Ci.nsIAccessibleRole.ROLE_PARENT_MENUITEM,
+ Ci.nsIAccessibleRole.ROLE_PUSHBUTTON,
+ Ci.nsIAccessibleRole.ROLE_RADIOBUTTON,
+ Ci.nsIAccessibleRole.ROLE_RADIO_MENU_ITEM,
+ Ci.nsIAccessibleRole.ROLE_RICH_OPTION,
+ Ci.nsIAccessibleRole.ROLE_ROW,
+ Ci.nsIAccessibleRole.ROLE_ROWHEADER,
+ Ci.nsIAccessibleRole.ROLE_SUMMARY,
+ Ci.nsIAccessibleRole.ROLE_SWITCH,
+ Ci.nsIAccessibleRole.ROLE_TABLE_COLUMN_HEADER,
+ Ci.nsIAccessibleRole.ROLE_TABLE_ROW_HEADER,
+ Ci.nsIAccessibleRole.ROLE_TEAR_OFF_MENU_ITEM,
+ Ci.nsIAccessibleRole.ROLE_TERM,
+ Ci.nsIAccessibleRole.ROLE_TOGGLE_BUTTON,
+ Ci.nsIAccessibleRole.ROLE_TOOLTIP,
+]);
+
+const IS_OSX = Services.appinfo.OS === "Darwin";
+
+const {
+ SCORES: { BEST_PRACTICES, FAIL, WARNING },
+} = accessibility;
+
+/**
+ * Helper function that determines if nsIAccessible object is in stale state. When an
+ * object is stale it means its subtree is not up to date.
+ *
+ * @param {nsIAccessible} accessible
+ * object to be tested.
+ * @return {Boolean}
+ * True if accessible object is stale, false otherwise.
+ */
+function isStale(accessible) {
+ const extraState = {};
+ accessible.getState({}, extraState);
+ // extraState.value is a bitmask. We are applying bitwise AND to mask out
+ // irrelevant states.
+ return !!(extraState.value & Ci.nsIAccessibleStates.EXT_STATE_STALE);
+}
+
+/**
+ * Get accessibility audit starting with the passed accessible object as a root.
+ *
+ * @param {Object} acc
+ * AccessibileActor to be used as the root for the audit.
+ * @param {Object} options
+ * Options for running audit, may include:
+ * - types: Array of audit types to be performed during audit.
+ * @param {Map} report
+ * An accumulator map to be used to store audit information.
+ * @param {Object} progress
+ * An audit project object that is used to track the progress of the
+ * audit and send progress "audit-event" events to the client.
+ */
+function getAudit(acc, options, report, progress) {
+ if (acc.isDefunct) {
+ return;
+ }
+
+ // Audit returns a promise, save the actual value in the report.
+ report.set(
+ acc,
+ acc.audit(options).then(result => {
+ report.set(acc, result);
+ progress.increment();
+ })
+ );
+
+ for (const child of acc.children()) {
+ getAudit(child, options, report, progress);
+ }
+}
+
+/**
+ * A helper class that is used to track audit progress and send progress events
+ * to the client.
+ */
+class AuditProgress {
+ constructor(walker) {
+ this.completed = 0;
+ this.percentage = 0;
+ this.walker = walker;
+ }
+
+ setTotal(size) {
+ this.size = size;
+ }
+
+ notify() {
+ this.walker.emit("audit-event", {
+ type: "progress",
+ progress: {
+ total: this.size,
+ percentage: this.percentage,
+ completed: this.completed,
+ },
+ });
+ }
+
+ increment() {
+ this.completed++;
+ const { completed, size } = this;
+ if (!size) {
+ return;
+ }
+
+ const percentage = Math.round((completed / size) * 100);
+ if (percentage > this.percentage) {
+ this.percentage = percentage;
+ this.notify();
+ }
+ }
+
+ destroy() {
+ this.walker = null;
+ }
+}
+
+/**
+ * The AccessibleWalkerActor stores a cache of AccessibleActors that represent
+ * accessible objects in a given document.
+ *
+ * It is also responsible for implicitely initializing and shutting down
+ * accessibility engine by storing a reference to the XPCOM accessibility
+ * service.
+ */
+const AccessibleWalkerActor = ActorClassWithSpec(accessibleWalkerSpec, {
+ initialize(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ this.refMap = new Map();
+ this._loadedSheets = new WeakMap();
+ this.setA11yServiceGetter();
+ this.onPick = this.onPick.bind(this);
+ this.onHovered = this.onHovered.bind(this);
+ this._preventContentEvent = this._preventContentEvent.bind(this);
+ this.onKey = this.onKey.bind(this);
+ this.onFocusIn = this.onFocusIn.bind(this);
+ this.onFocusOut = this.onFocusOut.bind(this);
+ this.onHighlighterEvent = this.onHighlighterEvent.bind(this);
+ },
+
+ get highlighter() {
+ if (!this._highlighter) {
+ this._highlighter = CustomHighlighterActor(this, "AccessibleHighlighter");
+
+ this.manage(this._highlighter);
+ this._highlighter.on("highlighter-event", this.onHighlighterEvent);
+ }
+
+ return this._highlighter;
+ },
+
+ get tabbingOrderHighlighter() {
+ if (!this._tabbingOrderHighlighter) {
+ this._tabbingOrderHighlighter = CustomHighlighterActor(
+ this,
+ "TabbingOrderHighlighter"
+ );
+
+ this.manage(this._tabbingOrderHighlighter);
+ }
+
+ return this._tabbingOrderHighlighter;
+ },
+
+ setA11yServiceGetter() {
+ DevToolsUtils.defineLazyGetter(this, "a11yService", () => {
+ Services.obs.addObserver(this, "accessible-event");
+ return Cc["@mozilla.org/accessibilityService;1"].getService(
+ Ci.nsIAccessibilityService
+ );
+ });
+ },
+
+ get rootWin() {
+ return this.targetActor && this.targetActor.window;
+ },
+
+ get rootDoc() {
+ return this.targetActor && this.targetActor.window.document;
+ },
+
+ get isXUL() {
+ return isXUL(this.rootWin);
+ },
+
+ get colorMatrix() {
+ if (!this.targetActor.docShell) {
+ return null;
+ }
+
+ const colorMatrix = this.targetActor.docShell.getColorMatrix();
+ if (
+ colorMatrix.length === 0 ||
+ colorMatrix === COLOR_TRANSFORMATION_MATRICES.NONE
+ ) {
+ return null;
+ }
+
+ return colorMatrix;
+ },
+
+ reset() {
+ try {
+ Services.obs.removeObserver(this, "accessible-event");
+ } catch (e) {
+ // Accessible event observer might not have been initialized if a11y
+ // service was never used.
+ }
+
+ this.cancelPick();
+
+ // Clean up accessible actors cache.
+ this.clearRefs();
+
+ this._childrenPromise = null;
+ delete this.a11yService;
+ this.setA11yServiceGetter();
+ },
+
+ /**
+ * Remove existing cache (of accessible actors) from tree.
+ */
+ clearRefs() {
+ for (const actor of this.refMap.values()) {
+ actor.destroy();
+ }
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ this.reset();
+
+ if (this._highlighter) {
+ this._highlighter.off("highlighter-event", this.onHighlighterEvent);
+ this._highlighter = null;
+ }
+
+ if (this._tabbingOrderHighlighter) {
+ this._tabbingOrderHighlighter = null;
+ }
+
+ this.targetActor = null;
+ this.refMap = null;
+ },
+
+ getRef(rawAccessible) {
+ return this.refMap.get(rawAccessible);
+ },
+
+ addRef(rawAccessible) {
+ let actor = this.refMap.get(rawAccessible);
+ if (actor) {
+ return actor;
+ }
+
+ actor = new AccessibleActor(this, rawAccessible);
+ // Add the accessible actor as a child of this accessible walker actor,
+ // assigning it an actorID.
+ this.manage(actor);
+ this.refMap.set(rawAccessible, actor);
+
+ return actor;
+ },
+
+ /**
+ * Clean up accessible actors cache for a given accessible's subtree.
+ *
+ * @param {null|nsIAccessible} rawAccessible
+ */
+ purgeSubtree(rawAccessible) {
+ if (!rawAccessible) {
+ return;
+ }
+
+ try {
+ for (
+ let child = rawAccessible.firstChild;
+ child;
+ child = child.nextSibling
+ ) {
+ this.purgeSubtree(child);
+ }
+ } catch (e) {
+ // rawAccessible or its descendants are defunct.
+ }
+
+ const actor = this.getRef(rawAccessible);
+ if (actor) {
+ actor.destroy();
+ }
+ },
+
+ unmanage: function(actor) {
+ if (actor instanceof AccessibleActor) {
+ this.refMap.delete(actor.rawAccessible);
+ }
+ Actor.prototype.unmanage.call(this, actor);
+ },
+
+ /**
+ * A helper method. Accessibility walker is assumed to have only 1 child which
+ * is the top level document.
+ */
+ async children() {
+ if (this._childrenPromise) {
+ return this._childrenPromise;
+ }
+
+ this._childrenPromise = Promise.all([this.getDocument()]);
+ const children = await this._childrenPromise;
+ this._childrenPromise = null;
+ return children;
+ },
+
+ /**
+ * A promise for a root document accessible actor that only resolves when its
+ * corresponding document accessible object is fully loaded.
+ *
+ * @return {Promise}
+ */
+ getDocument() {
+ if (!this.rootDoc || !this.rootDoc.documentElement) {
+ return this.once("document-ready").then(docAcc => this.addRef(docAcc));
+ }
+
+ if (this.isXUL) {
+ const doc = this.addRef(this.getRawAccessibleFor(this.rootDoc));
+ return Promise.resolve(doc);
+ }
+
+ const doc = this.getRawAccessibleFor(this.rootDoc);
+ if (!doc || isStale(doc)) {
+ return this.once("document-ready").then(docAcc => this.addRef(docAcc));
+ }
+
+ return Promise.resolve(this.addRef(doc));
+ },
+
+ /**
+ * Get an accessible actor for a domnode actor.
+ * @param {Object} domNode
+ * domnode actor for which accessible actor is being created.
+ * @return {Promse}
+ * A promise that resolves when accessible actor is created for a
+ * domnode actor.
+ */
+ getAccessibleFor(domNode) {
+ // We need to make sure that the document is loaded processed by a11y first.
+ return this.getDocument().then(() => {
+ const rawAccessible = this.getRawAccessibleFor(domNode.rawNode);
+ // Not all DOM nodes have corresponding accessible objects. It's usually
+ // the case where there is no semantics or relevance to the accessibility
+ // client.
+ if (!rawAccessible) {
+ return null;
+ }
+
+ return this.addRef(rawAccessible);
+ });
+ },
+
+ /**
+ * Get a raw accessible object for a raw node.
+ * @param {DOMNode} rawNode
+ * Raw node for which accessible object is being retrieved.
+ * @return {nsIAccessible}
+ * Accessible object for a given DOMNode.
+ */
+ getRawAccessibleFor(rawNode) {
+ // Accessible can only be retrieved iff accessibility service is enabled.
+ if (!Services.appinfo.accessibilityEnabled) {
+ return null;
+ }
+
+ return this.a11yService.getAccessibleFor(rawNode);
+ },
+
+ async getAncestry(accessible) {
+ if (!accessible || accessible.indexInParent === -1) {
+ return [];
+ }
+ const doc = await this.getDocument();
+ const ancestry = [];
+ if (accessible === doc) {
+ return ancestry;
+ }
+
+ try {
+ let parent = accessible;
+ while (parent && (parent = parent.parentAcc) && parent != doc) {
+ ancestry.push(parent);
+ }
+ ancestry.push(doc);
+ } catch (error) {
+ throw new Error(`Failed to get ancestor for ${accessible}: ${error}`);
+ }
+
+ return ancestry.map(parent => ({
+ accessible: parent,
+ children: parent.children(),
+ }));
+ },
+
+ /**
+ * Run accessibility audit and return relevant ancestries for AccessibleActors
+ * that have non-empty audit checks.
+ *
+ * @param {Object} options
+ * Options for running audit, may include:
+ * - types: Array of audit types to be performed during audit.
+ *
+ * @return {Promise}
+ * A promise that resolves when the audit is complete and all relevant
+ * ancestries are calculated.
+ */
+ async audit(options) {
+ const doc = await this.getDocument();
+ const report = new Map();
+ this._auditProgress = new AuditProgress(this);
+ getAudit(doc, options, report, this._auditProgress);
+ this._auditProgress.setTotal(report.size);
+ await Promise.all(report.values());
+
+ const ancestries = [];
+ for (const [acc, audit] of report.entries()) {
+ // Filter out audits that have no failing checks.
+ if (
+ audit &&
+ Object.values(audit).some(
+ check =>
+ check != null &&
+ !check.error &&
+ [BEST_PRACTICES, FAIL, WARNING].includes(check.score)
+ )
+ ) {
+ ancestries.push(this.getAncestry(acc));
+ }
+ }
+
+ return Promise.all(ancestries);
+ },
+
+ /**
+ * Start accessibility audit. The result of this function will not be an audit
+ * report. Instead, an "audit-event" event will be fired when the audit is
+ * completed or fails.
+ *
+ * @param {Object} options
+ * Options for running audit, may include:
+ * - types: Array of audit types to be performed during audit.
+ */
+ startAudit(options) {
+ // Audit is already running, wait for the "audit-event" event.
+ if (this._auditing) {
+ return;
+ }
+
+ this._auditing = this.audit(options)
+ // We do not want to block on audit request, instead fire "audit-event"
+ // event when internal audit is finished or failed.
+ .then(ancestries =>
+ this.emit("audit-event", {
+ type: "completed",
+ ancestries,
+ })
+ )
+ .catch(() => this.emit("audit-event", { type: "error" }))
+ .finally(() => {
+ this._auditing = null;
+ this._auditProgress.destroy();
+ this._auditProgress = null;
+ });
+ },
+
+ onHighlighterEvent: function(data) {
+ this.emit("highlighter-event", data);
+ },
+
+ /**
+ * Accessible event observer function.
+ *
+ * @param {Ci.nsIAccessibleEvent} subject
+ * accessible event object.
+ */
+ // eslint-disable-next-line complexity
+ observe(subject) {
+ const event = subject.QueryInterface(Ci.nsIAccessibleEvent);
+ const rawAccessible = event.accessible;
+ const accessible = this.getRef(rawAccessible);
+
+ if (rawAccessible instanceof Ci.nsIAccessibleDocument && !accessible) {
+ const rootDocAcc = this.getRawAccessibleFor(this.rootDoc);
+ if (rawAccessible === rootDocAcc && !isStale(rawAccessible)) {
+ this.clearRefs();
+ // If it's a top level document notify listeners about the document
+ // being ready.
+ events.emit(this, "document-ready", rawAccessible);
+ }
+ }
+
+ switch (event.eventType) {
+ case EVENT_STATE_CHANGE:
+ const { state, isEnabled } = event.QueryInterface(
+ Ci.nsIAccessibleStateChangeEvent
+ );
+ const isBusy = state & Ci.nsIAccessibleStates.STATE_BUSY;
+ if (accessible) {
+ // Only propagate state change events for active accessibles.
+ if (isBusy && isEnabled) {
+ if (rawAccessible instanceof Ci.nsIAccessibleDocument) {
+ // Remove existing cache from tree.
+ this.clearRefs();
+ }
+ return;
+ }
+ events.emit(accessible, "states-change", accessible.states);
+ }
+
+ break;
+ case EVENT_NAME_CHANGE:
+ if (accessible) {
+ events.emit(
+ accessible,
+ "name-change",
+ rawAccessible.name,
+ event.DOMNode == this.rootDoc
+ ? undefined
+ : this.getRef(rawAccessible.parent)
+ );
+ }
+ break;
+ case EVENT_VALUE_CHANGE:
+ if (accessible) {
+ events.emit(accessible, "value-change", rawAccessible.value);
+ }
+ break;
+ case EVENT_DESCRIPTION_CHANGE:
+ if (accessible) {
+ events.emit(
+ accessible,
+ "description-change",
+ rawAccessible.description
+ );
+ }
+ break;
+ case EVENT_REORDER:
+ if (accessible) {
+ accessible
+ .children()
+ .forEach(child =>
+ events.emit(child, "index-in-parent-change", child.indexInParent)
+ );
+ events.emit(accessible, "reorder", rawAccessible.childCount);
+ }
+ break;
+ case EVENT_HIDE:
+ if (event.DOMNode == this.rootDoc) {
+ this.clearRefs();
+ } else {
+ this.purgeSubtree(rawAccessible);
+ }
+ break;
+ case EVENT_DEFACTION_CHANGE:
+ case EVENT_ACTION_CHANGE:
+ if (accessible) {
+ events.emit(accessible, "actions-change", accessible.actions);
+ }
+ break;
+ case EVENT_TEXT_CHANGED:
+ case EVENT_TEXT_INSERTED:
+ case EVENT_TEXT_REMOVED:
+ if (accessible) {
+ events.emit(accessible, "text-change");
+ if (NAME_FROM_SUBTREE_RULE_ROLES.has(rawAccessible.role)) {
+ events.emit(
+ accessible,
+ "name-change",
+ rawAccessible.name,
+ event.DOMNode == this.rootDoc
+ ? undefined
+ : this.getRef(rawAccessible.parent)
+ );
+ }
+ }
+ break;
+ case EVENT_DOCUMENT_ATTRIBUTES_CHANGED:
+ case EVENT_OBJECT_ATTRIBUTE_CHANGED:
+ case EVENT_TEXT_ATTRIBUTE_CHANGED:
+ if (accessible) {
+ events.emit(accessible, "attributes-change", accessible.attributes);
+ }
+ break;
+ // EVENT_ACCELERATOR_CHANGE is currently not fired by gecko accessibility.
+ case EVENT_ACCELERATOR_CHANGE:
+ if (accessible) {
+ events.emit(
+ accessible,
+ "shortcut-change",
+ accessible.keyboardShortcut
+ );
+ }
+ break;
+ default:
+ break;
+ }
+ },
+
+ /**
+ * Ensure that nothing interferes with the audit for an accessible object
+ * (CSS, overlays) by load accessibility highlighter style sheet used for
+ * preventing transitions and applying transparency when calculating colour
+ * contrast as well as temporarily hiding accessible highlighter overlay.
+ * @param {Object} win
+ * Window where highlighting happens.
+ */
+ async clearStyles(win) {
+ const requests = this._loadedSheets.get(win);
+ if (requests != null) {
+ this._loadedSheets.set(win, requests + 1);
+ return;
+ }
+
+ // Disable potential mouse driven transitions (This is important because accessibility
+ // highlighter temporarily modifies text color related CSS properties. In case where
+ // there are transitions that affect them, there might be unexpected side effects when
+ // taking a snapshot for contrast measurement).
+ loadSheetForBackgroundCalculation(win);
+ this._loadedSheets.set(win, 1);
+ await this.hideHighlighter();
+ },
+
+ /**
+ * Restore CSS and overlays that could've interfered with the audit for an
+ * accessible object by unloading accessibility highlighter style sheet used
+ * for preventing transitions and applying transparency when calculating
+ * colour contrast and potentially restoring accessible highlighter overlay.
+ * @param {Object} win
+ * Window where highlighting was happenning.
+ */
+ async restoreStyles(win) {
+ const requests = this._loadedSheets.get(win);
+ if (!requests) {
+ return;
+ }
+
+ if (requests > 1) {
+ this._loadedSheets.set(win, requests - 1);
+ return;
+ }
+
+ await this.showHighlighter();
+ removeSheetForBackgroundCalculation(win);
+ this._loadedSheets.delete(win);
+ },
+
+ async hideHighlighter() {
+ // TODO: Fix this workaround that temporarily removes higlighter bounds
+ // overlay that can interfere with the contrast ratio calculation.
+ if (this._highlighter) {
+ const highlighter = this._highlighter.instance;
+ await highlighter.isReady;
+ highlighter.hideAccessibleBounds();
+ }
+ },
+
+ async showHighlighter() {
+ // TODO: Fix this workaround that temporarily removes higlighter bounds
+ // overlay that can interfere with the contrast ratio calculation.
+ if (this._highlighter) {
+ const highlighter = this._highlighter.instance;
+ await highlighter.isReady;
+ highlighter.showAccessibleBounds();
+ }
+ },
+
+ /**
+ * Public method used to show an accessible object highlighter on the client
+ * side.
+ *
+ * @param {Object} accessible
+ * AccessibleActor to be highlighted.
+ * @param {Object} options
+ * Object used for passing options. Available options:
+ * - duration {Number}
+ * Duration of time that the highlighter should be shown.
+ * @return {Boolean}
+ * True if highlighter shows the accessible object.
+ */
+ async highlightAccessible(accessible, options = {}) {
+ this.unhighlight();
+ // Do not highlight if accessible is dead.
+ if (!accessible || accessible.isDefunct || accessible.indexInParent < 0) {
+ return false;
+ }
+
+ this._highlightingAccessible = accessible;
+ const { bounds } = accessible;
+ if (!bounds) {
+ return false;
+ }
+
+ const { DOMNode: rawNode } = accessible.rawAccessible;
+ const audit = await accessible.audit();
+ if (this._highlightingAccessible !== accessible) {
+ return false;
+ }
+
+ const { name, role } = accessible;
+ const { highlighter } = this;
+ await highlighter.instance.isReady;
+ if (this._highlightingAccessible !== accessible) {
+ return false;
+ }
+
+ const shown = highlighter.show(
+ { rawNode },
+ { ...options, ...bounds, name, role, audit, isXUL: this.isXUL }
+ );
+ this._highlightingAccessible = null;
+
+ return shown;
+ },
+
+ /**
+ * Public method used to hide an accessible object highlighter on the client
+ * side.
+ */
+ unhighlight() {
+ if (!this._highlighter) {
+ return;
+ }
+
+ this.highlighter.hide();
+ this._highlightingAccessible = null;
+ },
+
+ /**
+ * Picking state that indicates if picking is currently enabled and, if so,
+ * what the current and hovered accessible objects are.
+ */
+ _isPicking: false,
+ _currentAccessible: null,
+
+ /**
+ * Check is event handling is allowed.
+ */
+ _isEventAllowed: function({ view }) {
+ return (
+ this.rootWin instanceof Ci.nsIDOMChromeWindow ||
+ isWindowIncluded(this.rootWin, view)
+ );
+ },
+
+ /**
+ * Check if the DOM event received when picking shold be ignored.
+ * @param {Event} event
+ */
+ _ignoreEventWhenPicking(event) {
+ return (
+ !this._isPicking ||
+ // If the DOM event is about a remote frame, only the WalkerActor for that
+ // remote frame target should emit RDP events (hovered/picked/...). And
+ // all other WalkerActor for intermediate iframe and top level document
+ // targets should stay silent.
+ isRemoteFrame(event.originalTarget || event.target)
+ );
+ },
+
+ _preventContentEvent(event) {
+ if (this._ignoreEventWhenPicking(event)) {
+ return;
+ }
+
+ event.stopPropagation();
+ event.preventDefault();
+
+ const target = event.originalTarget || event.target;
+ if (target !== this._currentTarget) {
+ this._resetStateAndReleaseTarget();
+ this._currentTarget = target;
+ // We use InspectorUtils to save the original hover content state of the target
+ // element (that includes its hover state). In order to not trigger any visual
+ // changes to the element that depend on its hover state we remove the state while
+ // the element is the most current target of the highlighter.
+ //
+ // TODO: This logic can be removed if/when we can use elementsAtPoint API for
+ // determining topmost DOMNode that corresponds to specific coordinates. We would
+ // then be able to use a highlighter overlay that would prevent all pointer events
+ // to content but still render highlighter for the node/element correctly.
+ this._currentTargetHoverState =
+ InspectorUtils.getContentState(target) & kStateHover;
+ InspectorUtils.removeContentState(target, kStateHover);
+ }
+ },
+
+ /**
+ * Click event handler for when picking is enabled.
+ *
+ * @param {Object} event
+ * Current click event.
+ */
+ onPick(event) {
+ if (this._ignoreEventWhenPicking(event)) {
+ return;
+ }
+
+ this._preventContentEvent(event);
+ if (!this._isEventAllowed(event)) {
+ return;
+ }
+
+ // If shift is pressed, this is only a preview click, send the event to
+ // the client, but don't stop picking.
+ if (event.shiftKey) {
+ if (!this._currentAccessible) {
+ this._currentAccessible = this._findAndAttachAccessible(event);
+ }
+ events.emit(this, "picker-accessible-previewed", this._currentAccessible);
+ return;
+ }
+
+ this._unsetPickerEnvironment();
+ this._isPicking = false;
+ if (!this._currentAccessible) {
+ this._currentAccessible = this._findAndAttachAccessible(event);
+ }
+ events.emit(this, "picker-accessible-picked", this._currentAccessible);
+ },
+
+ /**
+ * Hover event handler for when picking is enabled.
+ *
+ * @param {Object} event
+ * Current hover event.
+ */
+ async onHovered(event) {
+ if (this._ignoreEventWhenPicking(event)) {
+ return;
+ }
+
+ this._preventContentEvent(event);
+ if (!this._isEventAllowed(event)) {
+ return;
+ }
+
+ const accessible = this._findAndAttachAccessible(event);
+ if (!accessible || this._currentAccessible === accessible) {
+ return;
+ }
+
+ this._currentAccessible = accessible;
+ // Highlight current accessible and by the time we are done, if accessible that was
+ // highlighted is not current any more (user moved the mouse to a new node) highlight
+ // the most current accessible again.
+ const shown = await this.highlightAccessible(accessible);
+ if (this._isPicking && shown && accessible === this._currentAccessible) {
+ events.emit(this, "picker-accessible-hovered", accessible);
+ }
+ },
+
+ /**
+ * Keyboard event handler for when picking is enabled.
+ *
+ * @param {Object} event
+ * Current keyboard event.
+ */
+ onKey(event) {
+ if (!this._currentAccessible || this._ignoreEventWhenPicking(event)) {
+ return;
+ }
+
+ this._preventContentEvent(event);
+ if (!this._isEventAllowed(event)) {
+ return;
+ }
+
+ /**
+ * KEY: Action/scope
+ * ENTER/CARRIAGE_RETURN: Picks current accessible
+ * ESC/CTRL+SHIFT+C: Cancels picker
+ */
+ switch (event.keyCode) {
+ // Select the element.
+ case event.DOM_VK_RETURN:
+ this.onPick(event);
+ break;
+ // Cancel pick mode.
+ case event.DOM_VK_ESCAPE:
+ this.cancelPick();
+ events.emit(this, "picker-accessible-canceled");
+ break;
+ case event.DOM_VK_C:
+ if (
+ (IS_OSX && event.metaKey && event.altKey) ||
+ (!IS_OSX && event.ctrlKey && event.shiftKey)
+ ) {
+ this.cancelPick();
+ events.emit(this, "picker-accessible-canceled");
+ }
+ break;
+ default:
+ break;
+ }
+ },
+
+ /**
+ * Picker method that starts picker content listeners.
+ */
+ pick: function() {
+ if (!this._isPicking) {
+ this._isPicking = true;
+ this._setPickerEnvironment();
+ }
+ },
+
+ /**
+ * This pick method also focuses the highlighter's target window.
+ */
+ pickAndFocus: function() {
+ this.pick();
+ this.rootWin.focus();
+ },
+
+ attachAccessible(rawAccessible, accessibleDocument) {
+ // If raw accessible object is defunct or detached, no need to cache it and
+ // its ancestry.
+ if (
+ !rawAccessible ||
+ isDefunct(rawAccessible) ||
+ rawAccessible.indexInParent < 0
+ ) {
+ return null;
+ }
+
+ const accessible = this.addRef(rawAccessible);
+ // There is a chance that ancestry lookup can fail if the accessible is in
+ // the detached subtree. At that point the root accessible object would be
+ // defunct and accessing it via parent property will throw.
+ try {
+ let parent = accessible;
+ while (parent && parent.rawAccessible != accessibleDocument) {
+ parent = parent.parentAcc;
+ }
+ } catch (error) {
+ throw new Error(`Failed to get ancestor for ${accessible}: ${error}`);
+ }
+
+ return accessible;
+ },
+
+ /**
+ * When RDM is used, users can set custom DPR values that are different from the device
+ * they are using. Store true screenPixelsPerCSSPixel value to be able to use accessible
+ * highlighter features correctly.
+ */
+ get pixelRatio() {
+ const { contentViewer } = this.targetActor.docShell;
+ const { windowUtils } = this.rootWin;
+ const overrideDPPX = contentViewer.overrideDPPX;
+ let ratio;
+ if (overrideDPPX) {
+ contentViewer.overrideDPPX = 0;
+ ratio = windowUtils.screenPixelsPerCSSPixel;
+ contentViewer.overrideDPPX = overrideDPPX;
+ } else {
+ ratio = windowUtils.screenPixelsPerCSSPixel;
+ }
+
+ return ratio;
+ },
+
+ /**
+ * Find deepest accessible object that corresponds to the screen coordinates of the
+ * mouse pointer and attach it to the AccessibilityWalker tree.
+ *
+ * @param {Object} event
+ * Correspoinding content event.
+ * @return {null|Object}
+ * Accessible object, if available, that corresponds to a DOM node.
+ */
+ _findAndAttachAccessible(event) {
+ const target = event.originalTarget || event.target;
+ const docAcc = this.getRawAccessibleFor(this.rootDoc);
+ const win = target.ownerGlobal;
+ const zoom = this.isXUL ? 1 : getCurrentZoom(win);
+ const scale = this.pixelRatio / zoom;
+ const rawAccessible = docAcc.getDeepestChildAtPointInProcess(
+ event.screenX * scale,
+ event.screenY * scale
+ );
+ return this.attachAccessible(rawAccessible, docAcc);
+ },
+
+ /**
+ * Start picker content listeners.
+ */
+ _setPickerEnvironment: function() {
+ const target = this.targetActor.chromeEventHandler;
+ target.addEventListener("mousemove", this.onHovered, true);
+ target.addEventListener("click", this.onPick, true);
+ target.addEventListener("mousedown", this._preventContentEvent, true);
+ target.addEventListener("mouseup", this._preventContentEvent, true);
+ target.addEventListener("mouseover", this._preventContentEvent, true);
+ target.addEventListener("mouseout", this._preventContentEvent, true);
+ target.addEventListener("mouseleave", this._preventContentEvent, true);
+ target.addEventListener("mouseenter", this._preventContentEvent, true);
+ target.addEventListener("dblclick", this._preventContentEvent, true);
+ target.addEventListener("keydown", this.onKey, true);
+ target.addEventListener("keyup", this._preventContentEvent, true);
+ },
+
+ /**
+ * If content is still alive, stop picker content listeners, reset the hover state for
+ * last target element.
+ */
+ _unsetPickerEnvironment: function() {
+ const target = this.targetActor.chromeEventHandler;
+
+ if (!target) {
+ return;
+ }
+
+ target.removeEventListener("mousemove", this.onHovered, true);
+ target.removeEventListener("click", this.onPick, true);
+ target.removeEventListener("mousedown", this._preventContentEvent, true);
+ target.removeEventListener("mouseup", this._preventContentEvent, true);
+ target.removeEventListener("mouseover", this._preventContentEvent, true);
+ target.removeEventListener("mouseout", this._preventContentEvent, true);
+ target.removeEventListener("mouseleave", this._preventContentEvent, true);
+ target.removeEventListener("mouseenter", this._preventContentEvent, true);
+ target.removeEventListener("dblclick", this._preventContentEvent, true);
+ target.removeEventListener("keydown", this.onKey, true);
+ target.removeEventListener("keyup", this._preventContentEvent, true);
+
+ this._resetStateAndReleaseTarget();
+ },
+
+ /**
+ * When using accessibility highlighter, we keep track of the most current event pointer
+ * event target. In order to update or release the target, we need to make sure we set
+ * the content state (using InspectorUtils) to its original value.
+ *
+ * TODO: This logic can be removed if/when we can use elementsAtPoint API for
+ * determining topmost DOMNode that corresponds to specific coordinates. We would then
+ * be able to use a highlighter overlay that would prevent all pointer events to content
+ * but still render highlighter for the node/element correctly.
+ */
+ _resetStateAndReleaseTarget() {
+ if (!this._currentTarget) {
+ return;
+ }
+
+ try {
+ if (this._currentTargetHoverState) {
+ InspectorUtils.setContentState(this._currentTarget, kStateHover);
+ }
+ } catch (e) {
+ // DOMNode is already dead.
+ }
+
+ this._currentTarget = null;
+ this._currentTargetState = null;
+ },
+
+ /**
+ * Cacncel picker pick. Remvoe all content listeners and hide the highlighter.
+ */
+ cancelPick: function() {
+ this.unhighlight();
+
+ if (this._isPicking) {
+ this._unsetPickerEnvironment();
+ this._isPicking = false;
+ this._currentAccessible = null;
+ }
+ },
+
+ /**
+ * Indicates that the tabbing order current active element (focused) is being
+ * tracked.
+ */
+ _isTrackingTabbingOrderFocus: false,
+
+ /**
+ * Current focused element in the tabbing order.
+ */
+ _currentFocusedTabbingOrder: null,
+
+ /**
+ * Focusin event handler for when interacting with tabbing order overlay.
+ *
+ * @param {Object} event
+ * Most recent focusin event.
+ */
+ async onFocusIn(event) {
+ if (!this._isTrackingTabbingOrderFocus) {
+ return;
+ }
+
+ const target = event.originalTarget || event.target;
+ if (target === this._currentFocusedTabbingOrder) {
+ return;
+ }
+
+ this._currentFocusedTabbingOrder = target;
+ this.tabbingOrderHighlighter._highlighter.updateFocus({
+ node: target,
+ focused: true,
+ });
+ },
+
+ /**
+ * Focusout event handler for when interacting with tabbing order overlay.
+ *
+ * @param {Object} event
+ * Most recent focusout event.
+ */
+ async onFocusOut(event) {
+ if (
+ !this._isTrackingTabbingOrderFocus ||
+ !this._currentFocusedTabbingOrder
+ ) {
+ return;
+ }
+
+ const target = event.originalTarget || event.target;
+ // Sanity check.
+ if (target !== this._currentFocusedTabbingOrder) {
+ console.warn(
+ `focusout target: ${target} does not match current focused element in tabbing order: ${this._currentFocusedTabbingOrder}`
+ );
+ }
+
+ this.tabbingOrderHighlighter._highlighter.updateFocus({
+ node: this._currentFocusedTabbingOrder,
+ focused: false,
+ });
+ this._currentFocusedTabbingOrder = null;
+ },
+
+ /**
+ * Show tabbing order overlay for a given target.
+ *
+ * @param {Object} elm
+ * domnode actor to be used as the starting point for generating the
+ * tabbing order.
+ * @param {Number} index
+ * Starting index for the tabbing order.
+ *
+ * @return {JSON}
+ * Tabbing order information for the last element in the tabbing
+ * order. It includes a ContentDOMReference for the node and a tabbing
+ * index. If we are at the end of the tabbing order for the top level
+ * content document, the ContentDOMReference will be null. If focus
+ * manager discovered a remote IFRAME, then the ContentDOMReference
+ * references the IFRAME itself.
+ */
+ showTabbingOrder(elm, index) {
+ // Start track focus related events (only once). `showTabbingOrder` will be
+ // called multiple times for a given target if it contains other remote
+ // targets.
+ if (!this._isTrackingTabbingOrderFocus) {
+ this._isTrackingTabbingOrderFocus = true;
+ const target = this.targetActor.chromeEventHandler;
+ target.addEventListener("focusin", this.onFocusIn, true);
+ target.addEventListener("focusout", this.onFocusOut, true);
+ }
+
+ return this.tabbingOrderHighlighter.show(elm, { index });
+ },
+
+ /**
+ * Hide tabbing order overlay for a given target.
+ */
+ hideTabbingOrder() {
+ if (!this._tabbingOrderHighlighter) {
+ return;
+ }
+
+ this.tabbingOrderHighlighter.hide();
+ if (!this._isTrackingTabbingOrderFocus) {
+ return;
+ }
+
+ this._isTrackingTabbingOrderFocus = false;
+ this._currentFocusedTabbingOrder = null;
+ const target = this.targetActor.chromeEventHandler;
+ if (target) {
+ target.removeEventListener("focusin", this.onFocusIn, true);
+ target.removeEventListener("focusout", this.onFocusOut, true);
+ }
+ },
+});
+
+exports.AccessibleWalkerActor = AccessibleWalkerActor;
diff --git a/devtools/server/actors/accessibility/worker.js b/devtools/server/actors/accessibility/worker.js
new file mode 100644
index 0000000000..67fed4d22b
--- /dev/null
+++ b/devtools/server/actors/accessibility/worker.js
@@ -0,0 +1,105 @@
+/* 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";
+
+/* eslint-env worker */
+
+/**
+ * Import `createTask` to communicate with `devtools/shared/worker`.
+ */
+importScripts("resource://gre/modules/workers/require.js");
+const { createTask } = require("resource://devtools/shared/worker/helper.js");
+
+/**
+ * @see LineGraphWidget.prototype.setDataFromTimestamps in Graphs.js
+ * @param number id
+ * @param array timestamps
+ * @param number interval
+ * @param number duration
+ */
+createTask(self, "getBgRGBA", ({ dataTextBuf, dataBackgroundBuf }) =>
+ getBgRGBA(dataTextBuf, dataBackgroundBuf)
+);
+
+/**
+ * Calculates the luminance of a rgba tuple based on the formula given in
+ * https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
+ *
+ * @param {Array} rgba An array with [r,g,b,a] values.
+ * @return {Number} The calculated luminance.
+ */
+function calculateLuminance(rgba) {
+ for (let i = 0; i < 3; i++) {
+ rgba[i] /= 255;
+ rgba[i] =
+ rgba[i] < 0.03928
+ ? rgba[i] / 12.92
+ : Math.pow((rgba[i] + 0.055) / 1.055, 2.4);
+ }
+ return 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2];
+}
+
+/**
+ * Get RGBA or a range of RGBAs for the background pixels under the text. If luminance is
+ * uniform, only return one value of RGBA, otherwise return values that correspond to the
+ * min and max luminances.
+ * @param {ImageData} dataTextBuf
+ * pixel data for the accessible object with text visible.
+ * @param {ImageData} dataBackgroundBuf
+ * pixel data for the accessible object with transparent text.
+ * @return {Object}
+ * RGBA or a range of RGBAs with min and max values.
+ */
+function getBgRGBA(dataTextBuf, dataBackgroundBuf) {
+ let min = [0, 0, 0, 1];
+ let max = [255, 255, 255, 1];
+ let minLuminance = 1;
+ let maxLuminance = 0;
+ const luminances = {};
+ const dataText = new Uint8ClampedArray(dataTextBuf);
+ const dataBackground = new Uint8ClampedArray(dataBackgroundBuf);
+
+ let foundDistinctColor = false;
+ for (let i = 0; i < dataText.length; i = i + 4) {
+ const tR = dataText[i];
+ const bgR = dataBackground[i];
+ const tG = dataText[i + 1];
+ const bgG = dataBackground[i + 1];
+ const tB = dataText[i + 2];
+ const bgB = dataBackground[i + 2];
+
+ // Ignore pixels that are the same where pixels that are different between the two
+ // images are assumed to belong to the text within the node.
+ if (tR === bgR && tG === bgG && tB === bgB) {
+ continue;
+ }
+
+ foundDistinctColor = true;
+
+ const bgColor = `rgb(${bgR}, ${bgG}, ${bgB})`;
+ let luminance = luminances[bgColor];
+
+ if (!luminance) {
+ // Calculate luminance for the RGB value and store it to only measure once.
+ luminance = calculateLuminance([bgR, bgG, bgB]);
+ luminances[bgColor] = luminance;
+ }
+
+ if (minLuminance >= luminance) {
+ minLuminance = luminance;
+ min = [bgR, bgG, bgB, 1];
+ }
+
+ if (maxLuminance <= luminance) {
+ maxLuminance = luminance;
+ max = [bgR, bgG, bgB, 1];
+ }
+ }
+
+ if (!foundDistinctColor) {
+ return null;
+ }
+
+ return minLuminance === maxLuminance ? { value: max } : { min, max };
+}
diff --git a/devtools/server/actors/addon/addons.js b/devtools/server/actors/addon/addons.js
new file mode 100644
index 0000000000..5736867383
--- /dev/null
+++ b/devtools/server/actors/addon/addons.js
@@ -0,0 +1,43 @@
+/* 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";
+
+const { AddonManager } = require("resource://gre/modules/AddonManager.jsm");
+const protocol = require("devtools/shared/protocol");
+const { FileUtils } = require("resource://gre/modules/FileUtils.jsm");
+const { addonsSpec } = require("devtools/shared/specs/addon/addons");
+const { Services } = require("resource://gre/modules/Services.jsm");
+
+// This actor is not used by DevTools, but is relied on externally by
+// webext-run and the Firefox VS-Code plugin. see bug #1578108
+const AddonsActor = protocol.ActorClassWithSpec(addonsSpec, {
+ initialize: function(conn) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ },
+
+ async installTemporaryAddon(addonPath) {
+ let addonFile;
+ let addon;
+ try {
+ addonFile = new FileUtils.File(addonPath);
+ addon = await AddonManager.installTemporaryAddon(addonFile);
+ } catch (error) {
+ throw new Error(`Could not install add-on at '${addonPath}': ${error}`);
+ }
+
+ Services.obs.notifyObservers(null, "devtools-installed-addon", addon.id);
+
+ // TODO: once the add-on actor has been refactored to use
+ // protocol.js, we could return it directly.
+ // return new AddonTargetActor(this.conn, addon);
+
+ // Return a pseudo add-on object that a calling client can work
+ // with. Provide a flag that the client can use to detect when it
+ // gets upgraded to a real actor object.
+ return { id: addon.id, actor: false };
+ },
+});
+
+exports.AddonsActor = AddonsActor;
diff --git a/devtools/server/actors/addon/moz.build b/devtools/server/actors/addon/moz.build
new file mode 100644
index 0000000000..e382173641
--- /dev/null
+++ b/devtools/server/actors/addon/moz.build
@@ -0,0 +1,10 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "addons.js",
+ "webextension-inspected-window.js",
+)
diff --git a/devtools/server/actors/addon/webextension-inspected-window.js b/devtools/server/actors/addon/webextension-inspected-window.js
new file mode 100644
index 0000000000..e091ab7f22
--- /dev/null
+++ b/devtools/server/actors/addon/webextension-inspected-window.js
@@ -0,0 +1,697 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+
+const { Cc, Ci, Cu, Cr } = require("chrome");
+
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const Services = require("Services");
+const ChromeUtils = require("ChromeUtils");
+
+loader.lazyGetter(
+ this,
+ "NodeActor",
+ () => require("devtools/server/actors/inspector/node").NodeActor,
+ true
+);
+
+const {
+ webExtensionInspectedWindowSpec,
+} = require("devtools/shared/specs/addon/webextension-inspected-window");
+
+const { WebExtensionPolicy } = Cu.getGlobalForObject(
+ require("resource://gre/modules/XPCOMUtils.jsm")
+);
+
+// A weak set of the documents for which a warning message has been
+// already logged (so that we don't keep emitting the same warning if an
+// extension keeps calling the devtools.inspectedWindow.eval API method
+// when it fails to retrieve a result, but we do log the warning message
+// if the user reloads the window):
+//
+// WeakSet<Document>
+const deniedWarningDocuments = new WeakSet();
+
+function isSystemPrincipalWindow(window) {
+ return window.document.nodePrincipal.isSystemPrincipal;
+}
+
+// Create the exceptionInfo property in the format expected by a
+// WebExtension inspectedWindow.eval API calls.
+function createExceptionInfoResult(props) {
+ return {
+ exceptionInfo: {
+ isError: true,
+ code: "E_PROTOCOLERROR",
+ description: "Unknown Inspector protocol error",
+
+ // Apply the passed properties.
+ ...props,
+ },
+ };
+}
+
+// Show a warning message in the webconsole when an extension
+// eval request has been denied, so that the user knows about it
+// even if the extension doesn't report the error itself.
+function logAccessDeniedWarning(window, callerInfo, extensionPolicy) {
+ // Do not log the same warning multiple times for the same document.
+ if (deniedWarningDocuments.has(window.document)) {
+ return;
+ }
+
+ deniedWarningDocuments.add(window.document);
+
+ const { name } = extensionPolicy;
+
+ // System principals have a null nodePrincipal.URI and so we use
+ // the url from window.location.href.
+ const reportedURIorPrincipal = isSystemPrincipalWindow(window)
+ ? Services.io.newURI(window.location.href)
+ : window.document.nodePrincipal;
+
+ const error = Cc["@mozilla.org/scripterror;1"].createInstance(
+ Ci.nsIScriptError
+ );
+
+ const msg = `The extension "${name}" is not allowed to access ${reportedURIorPrincipal.spec}`;
+
+ const innerWindowId = window.windowGlobalChild.innerWindowId;
+
+ const errorFlag = 0;
+
+ let { url, lineNumber } = callerInfo;
+
+ const callerURI = callerInfo.url && Services.io.newURI(callerInfo.url);
+
+ // callerInfo.url is not the full path to the file that called the WebExtensions
+ // API yet (Bug 1448878), and so we associate the error to the url of the extension
+ // manifest.json file as a fallback.
+ if (callerURI.filePath === "/") {
+ url = extensionPolicy.getURL("/manifest.json");
+ lineNumber = null;
+ }
+
+ error.initWithWindowID(
+ msg,
+ url,
+ lineNumber,
+ 0,
+ 0,
+ errorFlag,
+ "webExtensions",
+ innerWindowId
+ );
+ Services.console.logMessage(error);
+}
+
+function CustomizedReload(params) {
+ this.docShell = params.targetActor.window.docShell;
+ this.docShell.QueryInterface(Ci.nsIWebProgress);
+
+ this.inspectedWindowEval = params.inspectedWindowEval;
+ this.callerInfo = params.callerInfo;
+
+ this.ignoreCache = params.ignoreCache;
+ this.injectedScript = params.injectedScript;
+ this.userAgent = params.userAgent;
+
+ this.customizedReloadWindows = new WeakSet();
+}
+
+CustomizedReload.prototype = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIWebProgressListener",
+ "nsISupportsWeakReference",
+ ]),
+ get window() {
+ return this.docShell.DOMWindow;
+ },
+
+ get webNavigation() {
+ return this.docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebNavigation);
+ },
+
+ get browsingContext() {
+ return this.docShell.browsingContext;
+ },
+
+ start() {
+ if (!this.waitForReloadCompleted) {
+ this.waitForReloadCompleted = new Promise((resolve, reject) => {
+ this.resolveReloadCompleted = resolve;
+ this.rejectReloadCompleted = reject;
+
+ if (this.userAgent) {
+ this.browsingContext.customUserAgent = this.userAgent;
+ }
+
+ let reloadFlags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
+
+ if (this.ignoreCache) {
+ reloadFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
+ }
+
+ try {
+ if (this.injectedScript) {
+ // Listen to the newly created document elements only if there is an
+ // injectedScript to evaluate.
+ Services.obs.addObserver(this, "initial-document-element-inserted");
+ }
+
+ // Watch the loading progress and clear the current CustomizedReload once the
+ // page has been reloaded (or if its reloading has been interrupted).
+ this.docShell.addProgressListener(
+ this,
+ Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT
+ );
+
+ this.webNavigation.reload(reloadFlags);
+ } catch (err) {
+ // Cancel the injected script listener if the reload fails
+ // (which will also report the error by rejecting the promise).
+ this.stop(err);
+ }
+ });
+ }
+
+ return this.waitForReloadCompleted;
+ },
+
+ observe(subject, topic, data) {
+ if (topic !== "initial-document-element-inserted") {
+ return;
+ }
+
+ const document = subject;
+ const window = document?.defaultView;
+
+ // Filter out non interesting documents.
+ if (!document || !document.location || !window) {
+ return;
+ }
+
+ const subjectDocShell = window.docShell;
+
+ // Keep track of the set of window objects where we are going to inject
+ // the injectedScript: the top level window and all its descendant
+ // that are still of type content (filtering out loaded XUL pages, if any).
+ if (window == this.window) {
+ this.customizedReloadWindows.add(window);
+ } else if (subjectDocShell.sameTypeParent) {
+ const parentWindow = subjectDocShell.sameTypeParent.domWindow;
+ if (parentWindow && this.customizedReloadWindows.has(parentWindow)) {
+ this.customizedReloadWindows.add(window);
+ }
+ }
+
+ if (this.customizedReloadWindows.has(window)) {
+ const { apiErrorResult } = this.inspectedWindowEval(
+ this.callerInfo,
+ this.injectedScript,
+ {},
+ window
+ );
+
+ // Log only apiErrorResult, because no one is waiting for the
+ // injectedScript result, and any exception is going to be logged
+ // in the inspectedWindow webconsole.
+ if (apiErrorResult) {
+ console.error(
+ "Unexpected Error in injectedScript during inspectedWindow.reload for",
+ `${this.callerInfo.url}:${this.callerInfo.lineNumber}`,
+ apiErrorResult
+ );
+ }
+ }
+ },
+
+ onStateChange(webProgress, request, state, status) {
+ if (webProgress.DOMWindow !== this.window) {
+ return;
+ }
+
+ if (state & Ci.nsIWebProgressListener.STATE_STOP) {
+ if (status == Cr.NS_BINDING_ABORTED) {
+ // The customized reload has been interrupted and we can clear
+ // the CustomizedReload and reject the promise.
+ const url = this.window.location.href;
+ this.stop(
+ new Error(
+ `devtools.inspectedWindow.reload on ${url} has been interrupted`
+ )
+ );
+ } else {
+ // Once the top level frame has been loaded, we can clear the customized reload
+ // and resolve the promise.
+ this.stop();
+ }
+ }
+ },
+
+ stop(error) {
+ if (this.stopped) {
+ return;
+ }
+
+ this.docShell.removeProgressListener(this);
+
+ if (this.injectedScript) {
+ Services.obs.removeObserver(this, "initial-document-element-inserted");
+ }
+
+ // Reset the customized user agent.
+ if (
+ this.userAgent &&
+ this.browsingContext.customUserAgent == this.userAgent
+ ) {
+ this.browsingContext.customUserAgent = null;
+ }
+
+ if (error) {
+ this.rejectReloadCompleted(error);
+ } else {
+ this.resolveReloadCompleted();
+ }
+
+ this.stopped = true;
+ },
+};
+
+var WebExtensionInspectedWindowActor = protocol.ActorClassWithSpec(
+ webExtensionInspectedWindowSpec,
+ {
+ /**
+ * Created the WebExtension InspectedWindow actor
+ */
+ initialize(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ },
+
+ destroy(conn) {
+ protocol.Actor.prototype.destroy.call(this, conn);
+
+ if (this.customizedReload) {
+ this.customizedReload.stop(
+ new Error("WebExtensionInspectedWindowActor destroyed")
+ );
+ delete this.customizedReload;
+ }
+
+ if (this._dbg) {
+ this._dbg.disable();
+ delete this._dbg;
+ }
+ },
+
+ get dbg() {
+ if (this._dbg) {
+ return this._dbg;
+ }
+
+ this._dbg = this.targetActor.makeDebugger();
+ return this._dbg;
+ },
+
+ get window() {
+ return this.targetActor.window;
+ },
+
+ get webNavigation() {
+ return this.targetActor.webNavigation;
+ },
+
+ createEvalBindings(dbgWindow, options) {
+ const bindings = Object.create(null);
+
+ let selectedDOMNode;
+
+ if (options.toolboxSelectedNodeActorID) {
+ const actor = DevToolsServer.searchAllConnectionsForActor(
+ options.toolboxSelectedNodeActorID
+ );
+ if (actor && actor instanceof NodeActor) {
+ selectedDOMNode = actor.rawNode;
+ }
+ }
+
+ Object.defineProperty(bindings, "$0", {
+ enumerable: true,
+ configurable: true,
+ get: () => {
+ if (selectedDOMNode && !Cu.isDeadWrapper(selectedDOMNode)) {
+ return dbgWindow.makeDebuggeeValue(selectedDOMNode);
+ }
+
+ return undefined;
+ },
+ });
+
+ // This function is used by 'eval' and 'reload' requests, but only 'eval'
+ // passes 'toolboxConsoleActor' from the client side in order to set
+ // the 'inspect' binding.
+ Object.defineProperty(bindings, "inspect", {
+ enumerable: true,
+ configurable: true,
+ value: dbgWindow.makeDebuggeeValue(object => {
+ const consoleActor = DevToolsServer.searchAllConnectionsForActor(
+ options.toolboxConsoleActorID
+ );
+ if (consoleActor) {
+ const dbgObj = consoleActor.makeDebuggeeValue(object);
+ consoleActor.inspectObject(
+ dbgObj,
+ "webextension-devtools-inspectedWindow-eval"
+ );
+ } else {
+ // TODO(rpl): evaluate if it would be better to raise an exception
+ // to the caller code instead.
+ console.error("Toolbox Console RDP Actor not found");
+ }
+ }),
+ });
+
+ return bindings;
+ },
+
+ /**
+ * Reload the target tab, optionally bypass cache, customize the userAgent and/or
+ * inject a script in targeted document or any of its sub-frame.
+ *
+ * @param {webExtensionCallerInfo} callerInfo
+ * the addonId and the url (the addon base url or the url of the actual caller
+ * filename and lineNumber) used to log useful debugging information in the
+ * produced error logs and eval stack trace.
+ *
+ * @param {webExtensionReloadOptions} options
+ * used to optionally enable the reload customizations.
+ * @param {boolean|undefined} options.ignoreCache
+ * enable/disable the cache bypass headers.
+ * @param {string|undefined} options.userAgent
+ * customize the userAgent during the page reload.
+ * @param {string|undefined} options.injectedScript
+ * evaluate the provided javascript code in the top level and every sub-frame
+ * created during the page reload, before any other script in the page has been
+ * executed.
+ */
+ reload(callerInfo, { ignoreCache, userAgent, injectedScript }) {
+ if (isSystemPrincipalWindow(this.window)) {
+ console.error(
+ "Ignored inspectedWindow.reload on system principal target for " +
+ `${callerInfo.url}:${callerInfo.lineNumber}`
+ );
+ return {};
+ }
+
+ const delayedReload = () => {
+ // This won't work while the browser is shutting down and we don't really
+ // care.
+ if (Services.startup.shuttingDown) {
+ return;
+ }
+
+ if (injectedScript || userAgent) {
+ if (this.customizedReload) {
+ // TODO(rpl): check what chrome does, and evaluate if queue the new reload
+ // after the current one has been completed.
+ console.error(
+ "Reload already in progress. Ignored inspectedWindow.reload for " +
+ `${callerInfo.url}:${callerInfo.lineNumber}`
+ );
+ return;
+ }
+
+ try {
+ this.customizedReload = new CustomizedReload({
+ targetActor: this.targetActor,
+ inspectedWindowEval: this.eval.bind(this),
+ callerInfo,
+ injectedScript,
+ userAgent,
+ ignoreCache,
+ });
+
+ this.customizedReload
+ .start()
+ .then(() => {
+ delete this.customizedReload;
+ })
+ .catch(err => {
+ delete this.customizedReload;
+ console.error(err);
+ });
+ } catch (err) {
+ // Cancel the customized reload (if any) on exception during the
+ // reload setup.
+ if (this.customizedReload) {
+ this.customizedReload.stop(err);
+ }
+
+ throw err;
+ }
+ } else {
+ // If there is no custom user agent and/or injected script, then
+ // we can reload the target without subscribing any observer/listener.
+ let reloadFlags = Ci.nsIWebNavigation.LOAD_FLAGS_NONE;
+ if (ignoreCache) {
+ reloadFlags |= Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE;
+ }
+ this.webNavigation.reload(reloadFlags);
+ }
+ };
+
+ // Execute the reload in a dispatched runnable, so that we can
+ // return the reply to the caller before the reload is actually
+ // started.
+ Services.tm.dispatchToMainThread(delayedReload);
+
+ return {};
+ },
+
+ /**
+ * Evaluate the provided javascript code in a target window (that is always the
+ * targetActor window when called through RDP protocol, or the passed
+ * customTargetWindow when called directly from the CustomizedReload instances).
+ *
+ * @param {webExtensionCallerInfo} callerInfo
+ * the addonId and the url (the addon base url or the url of the actual caller
+ * filename and lineNumber) used to log useful debugging information in the
+ * produced error logs and eval stack trace.
+ *
+ * @param {string} expression
+ * the javascript code to be evaluated in the target window
+ *
+ * @param {webExtensionEvalOptions} evalOptions
+ * used to optionally enable the eval customizations.
+ * NOTE: none of the eval options is currently implemented, they will be already
+ * reported as unsupported by the WebExtensions schema validation wrappers, but
+ * an additional level of error reporting is going to be applied here, so that
+ * if the server and the client have different ideas of which option is supported
+ * the eval call result will contain detailed informations (in the format usually
+ * expected for errors not raised in the evaluated javascript code).
+ *
+ * @param {DOMWindow|undefined} customTargetWindow
+ * Used in the CustomizedReload instances to evaluate the `injectedScript`
+ * javascript code in every sub-frame of the target window during the tab reload.
+ * NOTE: this parameter is not part of the RDP protocol exposed by this actor, when
+ * it is called over the remote debugging protocol the target window is always
+ * `targetActor.window`.
+ */
+ // eslint-disable-next-line complexity
+ eval(callerInfo, expression, options, customTargetWindow) {
+ const window = customTargetWindow || this.window;
+ options = options || {};
+
+ const extensionPolicy = WebExtensionPolicy.getByID(callerInfo.addonId);
+
+ if (!extensionPolicy) {
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s %s",
+ details: ["Caller extension not found for", callerInfo.url],
+ });
+ }
+
+ if (!window) {
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s",
+ details: [
+ "The target window is not defined. inspectedWindow.eval not executed.",
+ ],
+ });
+ }
+
+ // Log the error for the user to know that the extension request has been denied
+ // (the extension may not warn the user at all).
+ const logEvalDenied = () => {
+ logAccessDeniedWarning(window, callerInfo, extensionPolicy);
+ };
+
+ if (isSystemPrincipalWindow(window)) {
+ logEvalDenied();
+
+ // On denied JS evaluation, report it to the extension using the same data format
+ // used in the corresponding chrome API method to report issues that are
+ // not exceptions raised in the evaluated javascript code.
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s",
+ details: [
+ "This target has a system principal. inspectedWindow.eval denied.",
+ ],
+ });
+ }
+
+ const docPrincipalURI = window.document.nodePrincipal.URI;
+
+ // Deny on document principals listed as restricted or
+ // related to the about: pages (only about:blank and about:srcdoc are
+ // allowed and their are expected to not have their about URI associated
+ // to the principal).
+ if (
+ WebExtensionPolicy.isRestrictedURI(docPrincipalURI) ||
+ docPrincipalURI.schemeIs("about")
+ ) {
+ logEvalDenied();
+
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s %s",
+ details: [
+ "This extension is not allowed on the current inspected window origin",
+ docPrincipalURI.spec,
+ ],
+ });
+ }
+
+ const windowAddonId = window.document.nodePrincipal.addonId;
+
+ if (windowAddonId && extensionPolicy.id !== windowAddonId) {
+ logEvalDenied();
+
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s on %s",
+ details: [
+ "This extension is not allowed to access this extension page.",
+ window.document.location.origin,
+ ],
+ });
+ }
+
+ // Raise an error on the unsupported options.
+ if (
+ options.frameURL ||
+ options.contextSecurityOrigin ||
+ options.useContentScriptContext
+ ) {
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s",
+ details: [
+ "The inspectedWindow.eval options are currently not supported",
+ ],
+ });
+ }
+
+ const dbgWindow = this.dbg.makeGlobalObjectReference(window);
+
+ let evalCalledFrom = callerInfo.url;
+ if (callerInfo.lineNumber) {
+ evalCalledFrom += `:${callerInfo.lineNumber}`;
+ }
+
+ const bindings = this.createEvalBindings(dbgWindow, options);
+
+ const result = dbgWindow.executeInGlobalWithBindings(
+ expression,
+ bindings,
+ {
+ url: `debugger eval called from ${evalCalledFrom} - eval code`,
+ }
+ );
+
+ let evalResult;
+
+ if (result) {
+ if ("return" in result) {
+ evalResult = result.return;
+ } else if ("yield" in result) {
+ evalResult = result.yield;
+ } else if ("throw" in result) {
+ const throwErr = result.throw;
+
+ // XXXworkers: Calling unsafeDereference() returns an object with no
+ // toString method in workers. See Bug 1215120.
+ const unsafeDereference =
+ throwErr &&
+ typeof throwErr === "object" &&
+ throwErr.unsafeDereference();
+ const message = unsafeDereference?.toString
+ ? unsafeDereference.toString()
+ : String(throwErr);
+ const stack = unsafeDereference?.stack
+ ? unsafeDereference.stack
+ : null;
+
+ return {
+ exceptionInfo: {
+ isException: true,
+ value: `${message}\n\t${stack}`,
+ },
+ };
+ }
+ } else {
+ // TODO(rpl): can the result of executeInGlobalWithBinding be null or
+ // undefined? (which means that it is not a return, a yield or a throw).
+ console.error(
+ "Unexpected empty inspectedWindow.eval result for",
+ `${callerInfo.url}:${callerInfo.lineNumber}`
+ );
+ }
+
+ if (evalResult) {
+ try {
+ // Return the evalResult as a grip (used by the WebExtensions
+ // devtools inspector's sidebar.setExpression API method).
+ if (options.evalResultAsGrip) {
+ if (!options.toolboxConsoleActorID) {
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s - %s",
+ details: [
+ "Unexpected invalid sidebar panel expression request",
+ "missing toolboxConsoleActorID",
+ ],
+ });
+ }
+
+ const consoleActor = DevToolsServer.searchAllConnectionsForActor(
+ options.toolboxConsoleActorID
+ );
+
+ return { valueGrip: consoleActor.createValueGrip(evalResult) };
+ }
+
+ if (evalResult && typeof evalResult === "object") {
+ evalResult = evalResult.unsafeDereference();
+ }
+ evalResult = JSON.parse(JSON.stringify(evalResult));
+ } catch (err) {
+ // The evaluation result cannot be sent over the RDP Protocol,
+ // report it as with the same data format used in the corresponding
+ // chrome API method.
+ return createExceptionInfoResult({
+ description: "Inspector protocol error: %s",
+ details: [String(err)],
+ });
+ }
+ }
+
+ return { value: evalResult };
+ },
+ }
+);
+
+exports.WebExtensionInspectedWindowActor = WebExtensionInspectedWindowActor;
diff --git a/devtools/server/actors/animation-type-longhand.js b/devtools/server/actors/animation-type-longhand.js
new file mode 100644
index 0000000000..82270d35f4
--- /dev/null
+++ b/devtools/server/actors/animation-type-longhand.js
@@ -0,0 +1,402 @@
+/* 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";
+
+// Types of animation types of longhand properties.
+exports.ANIMATION_TYPE_FOR_LONGHANDS = [
+ [
+ "discrete",
+ new Set([
+ "align-content",
+ "align-items",
+ "align-self",
+ "align-tracks",
+ "aspect-ratio",
+ "appearance",
+ "backface-visibility",
+ "background-attachment",
+ "background-blend-mode",
+ "background-clip",
+ "background-image",
+ "background-origin",
+ "background-repeat",
+ "border-bottom-style",
+ "border-collapse",
+ "border-image-repeat",
+ "border-image-source",
+ "border-left-style",
+ "border-right-style",
+ "border-top-style",
+ "-moz-box-align",
+ "box-decoration-break",
+ "-moz-box-direction",
+ "-moz-box-ordinal-group",
+ "-moz-box-orient",
+ "-moz-box-pack",
+ "box-sizing",
+ "caption-side",
+ "clear",
+ "clip-rule",
+ "color-adjust",
+ "color-interpolation",
+ "color-interpolation-filters",
+ "column-fill",
+ "column-rule-style",
+ "column-span",
+ "contain",
+ "content",
+ "counter-increment",
+ "counter-reset",
+ "counter-set",
+ "cursor",
+ "direction",
+ "dominant-baseline",
+ "empty-cells",
+ "fill-rule",
+ "flex-direction",
+ "flex-wrap",
+ "float",
+ "-moz-float-edge",
+ "font-family",
+ "font-feature-settings",
+ "font-kerning",
+ "font-language-override",
+ "font-style",
+ "font-synthesis",
+ "font-variant-alternates",
+ "font-variant-caps",
+ "font-variant-east-asian",
+ "font-variant-ligatures",
+ "font-variant-numeric",
+ "font-variant-position",
+ "-moz-force-broken-image-icon",
+ "grid-auto-columns",
+ "grid-auto-flow",
+ "grid-auto-rows",
+ "grid-column-end",
+ "grid-column-start",
+ "grid-row-end",
+ "grid-row-start",
+ "grid-template-areas",
+ "grid-template-columns",
+ "grid-template-rows",
+ "hyphens",
+ "image-orientation",
+ "image-rendering",
+ "ime-mode",
+ "-moz-inert",
+ "initial-letter",
+ "isolation",
+ "justify-content",
+ "justify-items",
+ "justify-self",
+ "justify-tracks",
+ "line-break",
+ "list-style-image",
+ "list-style-position",
+ "list-style-type",
+ "-moz-list-reversed",
+ "marker-end",
+ "marker-mid",
+ "marker-start",
+ "mask-clip",
+ "mask-composite",
+ "mask-image",
+ "mask-mode",
+ "mask-origin",
+ "mask-repeat",
+ "mask-type",
+ "masonry-auto-flow",
+ "mix-blend-mode",
+ "object-fit",
+ "-moz-orient",
+ "-moz-osx-font-smoothing",
+ "outline-style",
+ "overflow-anchor",
+ "overflow-block",
+ "overflow-clip-box-block",
+ "overflow-clip-box-inline",
+ "overflow-inline",
+ "overflow-wrap",
+ "overflow-x",
+ "overflow-y",
+ "overscroll-behavior-inline",
+ "overscroll-behavior-block",
+ "overscroll-behavior-x",
+ "overscroll-behavior-y",
+ "break-after",
+ "break-before",
+ "break-inside",
+ "paint-order",
+ "pointer-events",
+ "position",
+ "quotes",
+ "resize",
+ "ruby-align",
+ "ruby-position",
+ "scroll-behavior",
+ "scroll-snap-align",
+ "scroll-snap-type",
+ "shape-rendering",
+ "scrollbar-width",
+ "stroke-linecap",
+ "stroke-linejoin",
+ "table-layout",
+ "text-align",
+ "text-align-last",
+ "text-anchor",
+ "text-combine-upright",
+ "text-decoration-line",
+ "text-decoration-skip-ink",
+ "text-decoration-style",
+ "text-emphasis-position",
+ "text-emphasis-style",
+ "text-justify",
+ "text-orientation",
+ "text-overflow",
+ "text-rendering",
+ "-moz-text-size-adjust",
+ "-webkit-text-stroke-width",
+ "text-transform",
+ "text-underline-position",
+ "touch-action",
+ "transform-box",
+ "transform-style",
+ "unicode-bidi",
+ "-moz-user-focus",
+ "-moz-user-input",
+ "-moz-user-modify",
+ "user-select",
+ "vector-effect",
+ "visibility",
+ "white-space",
+ "will-change",
+ "-moz-window-dragging",
+ "word-break",
+ "writing-mode",
+ ]),
+ ],
+ [
+ "none",
+ new Set([
+ "animation-delay",
+ "animation-direction",
+ "animation-duration",
+ "animation-fill-mode",
+ "animation-iteration-count",
+ "animation-name",
+ "animation-play-state",
+ "animation-timing-function",
+ "block-size",
+ "border-block-end-color",
+ "border-block-end-style",
+ "border-block-end-width",
+ "border-block-start-color",
+ "border-block-start-style",
+ "border-block-start-width",
+ "border-inline-end-color",
+ "border-inline-end-style",
+ "border-inline-end-width",
+ "border-inline-start-color",
+ "border-inline-start-style",
+ "border-inline-start-width",
+ "-moz-context-properties",
+ "-moz-control-character-visibility",
+ "-moz-default-appearance",
+ "display",
+ "font-optical-sizing",
+ "inline-size",
+ "inset-block-end",
+ "inset-block-start",
+ "inset-inline-end",
+ "inset-inline-start",
+ "margin-block-end",
+ "margin-block-start",
+ "margin-inline-end",
+ "margin-inline-start",
+ "math-style",
+ "max-block-size",
+ "max-inline-size",
+ "min-block-size",
+ "-moz-min-font-size-ratio",
+ "min-inline-size",
+ "padding-block-end",
+ "padding-block-start",
+ "padding-inline-end",
+ "padding-inline-start",
+ "math-depth",
+ "-moz-top-layer",
+ "transition-delay",
+ "transition-duration",
+ "transition-property",
+ "transition-timing-function",
+ "-moz-window-shadow",
+ ]),
+ ],
+ [
+ "color",
+ new Set([
+ "background-color",
+ "border-bottom-color",
+ "border-left-color",
+ "border-right-color",
+ "border-top-color",
+ "caret-color",
+ "color",
+ "column-rule-color",
+ "flood-color",
+ "-moz-font-smoothing-background-color",
+ "lighting-color",
+ "outline-color",
+ "scrollbar-color",
+ "stop-color",
+ "text-decoration-color",
+ "text-emphasis-color",
+ "-webkit-text-fill-color",
+ "-webkit-text-stroke-color",
+ ]),
+ ],
+ [
+ "custom",
+ new Set([
+ "backdrop-filter",
+ "background-position-x",
+ "background-position-y",
+ "background-size",
+ "border-bottom-width",
+ "border-image-slice",
+ "border-image-outset",
+ "border-image-width",
+ "border-left-width",
+ "border-right-width",
+ "border-spacing",
+ "border-top-width",
+ "clip",
+ "clip-path",
+ "column-count",
+ "column-rule-width",
+ "filter",
+ "font-stretch",
+ "font-variation-settings",
+ "font-weight",
+ "-moz-image-region",
+ "mask-position-x",
+ "mask-position-y",
+ "mask-size",
+ "object-position",
+ "offset-anchor",
+ "offset-path",
+ "offset-rotate",
+ "order",
+ "perspective-origin",
+ "rotate",
+ "scale",
+ "shape-outside",
+ "stroke-dasharray",
+ "transform",
+ "transform-origin",
+ "translate",
+ "-moz-window-transform",
+ "-moz-window-transform-origin",
+ "-webkit-line-clamp",
+ ]),
+ ],
+ [
+ "coord",
+ new Set([
+ "border-bottom-left-radius",
+ "border-bottom-right-radius",
+ "border-top-left-radius",
+ "border-top-right-radius",
+ "border-start-start-radius",
+ "border-start-end-radius",
+ "border-end-start-radius",
+ "border-end-end-radius",
+ "bottom",
+ "column-gap",
+ "column-width",
+ "cx",
+ "cy",
+ "flex-basis",
+ "height",
+ "left",
+ "letter-spacing",
+ "line-height",
+ "margin-bottom",
+ "margin-left",
+ "margin-right",
+ "margin-top",
+ "max-height",
+ "max-width",
+ "min-height",
+ "min-width",
+ "-moz-outline-radius-bottomleft",
+ "-moz-outline-radius-bottomright",
+ "-moz-outline-radius-topleft",
+ "-moz-outline-radius-topright",
+ "offset-distance",
+ "padding-bottom",
+ "padding-left",
+ "padding-right",
+ "padding-top",
+ "perspective",
+ "r",
+ "rx",
+ "ry",
+ "right",
+ "row-gap",
+ "scroll-padding-block-start",
+ "scroll-padding-block-end",
+ "scroll-padding-inline-start",
+ "scroll-padding-inline-end",
+ "scroll-padding-top",
+ "scroll-padding-right",
+ "scroll-padding-bottom",
+ "scroll-padding-left",
+ "scroll-margin-block-start",
+ "scroll-margin-block-end",
+ "scroll-margin-inline-start",
+ "scroll-margin-inline-end",
+ "scroll-margin-top",
+ "scroll-margin-right",
+ "scroll-margin-bottom",
+ "scroll-margin-left",
+ "shape-margin",
+ "stroke-dashoffset",
+ "stroke-width",
+ "-moz-tab-size",
+ "text-indent",
+ "text-decoration-thickness",
+ "text-underline-offset",
+ "top",
+ "vertical-align",
+ "width",
+ "word-spacing",
+ "x",
+ "y",
+ "z-index",
+ ]),
+ ],
+ [
+ "float",
+ new Set([
+ "-moz-box-flex",
+ "fill-opacity",
+ "flex-grow",
+ "flex-shrink",
+ "flood-opacity",
+ "font-size-adjust",
+ "opacity",
+ "shape-image-threshold",
+ "stop-opacity",
+ "stroke-miterlimit",
+ "stroke-opacity",
+ "-moz-window-opacity",
+ ]),
+ ],
+ ["shadow", new Set(["box-shadow", "text-shadow"])],
+ ["paintServer", new Set(["fill", "stroke"])],
+ ["length", new Set(["font-size", "outline-offset", "outline-width"])],
+];
diff --git a/devtools/server/actors/animation.js b/devtools/server/actors/animation.js
new file mode 100644
index 0000000000..b6455b1234
--- /dev/null
+++ b/devtools/server/actors/animation.js
@@ -0,0 +1,898 @@
+/* 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";
+
+/**
+ * Set of actors that expose the Web Animations API to devtools protocol
+ * clients.
+ *
+ * The |Animations| actor is the main entry point. It is used to discover
+ * animation players on given nodes.
+ * There should only be one instance per devtools server.
+ *
+ * The |AnimationPlayer| actor provides attributes and methods to inspect an
+ * animation as well as pause/resume/seek it.
+ *
+ * The Web Animation spec implementation is ongoing in Gecko, and so this set
+ * of actors should evolve when the implementation progresses.
+ *
+ * References:
+ * - WebAnimation spec:
+ * http://drafts.csswg.org/web-animations/
+ * - WebAnimation WebIDL files:
+ * /dom/webidl/Animation*.webidl
+ */
+
+const { Cu } = require("chrome");
+const protocol = require("devtools/shared/protocol");
+const { Actor } = protocol;
+const {
+ animationPlayerSpec,
+ animationsSpec,
+} = require("devtools/shared/specs/animation");
+const {
+ ANIMATION_TYPE_FOR_LONGHANDS,
+} = require("devtools/server/actors/animation-type-longhand");
+
+// Types of animations.
+const ANIMATION_TYPES = {
+ CSS_ANIMATION: "cssanimation",
+ CSS_TRANSITION: "csstransition",
+ SCRIPT_ANIMATION: "scriptanimation",
+ UNKNOWN: "unknown",
+};
+exports.ANIMATION_TYPES = ANIMATION_TYPES;
+
+function getAnimationTypeForLonghand(property) {
+ for (const [type, props] of ANIMATION_TYPE_FOR_LONGHANDS) {
+ if (props.has(property)) {
+ return type;
+ }
+ }
+ throw new Error("Unknown longhand property name");
+}
+exports.getAnimationTypeForLonghand = getAnimationTypeForLonghand;
+
+/**
+ * The AnimationPlayerActor provides information about a given animation: its
+ * startTime, currentTime, current state, etc.
+ *
+ * Since the state of a player changes as the animation progresses it is often
+ * useful to call getCurrentState at regular intervals to get the current state.
+ *
+ * This actor also allows playing, pausing and seeking the animation.
+ */
+var AnimationPlayerActor = protocol.ActorClassWithSpec(animationPlayerSpec, {
+ /**
+ * @param {AnimationsActor} The main AnimationsActor instance
+ * @param {AnimationPlayer} The player object returned by getAnimationPlayers
+ * @param {Number} Time which animation created
+ */
+ initialize: function(animationsActor, player, createdTime) {
+ Actor.prototype.initialize.call(this, animationsActor.conn);
+
+ this.onAnimationMutation = this.onAnimationMutation.bind(this);
+
+ this.walker = animationsActor.walker;
+ this.player = player;
+
+ // Listen to animation mutations on the node to alert the front when the
+ // current animation changes.
+ // If the node is a pseudo-element, then we listen on its parent with
+ // subtree:true (there's no risk of getting too many notifications in
+ // onAnimationMutation since we filter out events that aren't for the
+ // current animation).
+ this.observer = new this.window.MutationObserver(this.onAnimationMutation);
+ if (this.isPseudoElement) {
+ this.observer.observe(this.node.parentElement, {
+ animations: true,
+ subtree: true,
+ });
+ } else {
+ this.observer.observe(this.node, { animations: true });
+ }
+
+ this.createdTime = createdTime;
+ this.currentTimeAtCreated = player.currentTime;
+ },
+
+ destroy: function() {
+ // Only try to disconnect the observer if it's not already dead (i.e. if the
+ // container view hasn't navigated since).
+ if (this.observer && !Cu.isDeadWrapper(this.observer)) {
+ this.observer.disconnect();
+ }
+ this.player = this.observer = this.walker = null;
+
+ Actor.prototype.destroy.call(this);
+ },
+
+ get isPseudoElement() {
+ return !!this.player.effect.pseudoElement;
+ },
+
+ get pseudoElemenName() {
+ if (!this.isPseudoElement) {
+ return null;
+ }
+
+ return `_moz_generated_content_${this.player.effect.pseudoElement.replace(
+ /^::/,
+ ""
+ )}`;
+ },
+
+ get node() {
+ if (!this.isPseudoElement) {
+ return this.player.effect.target;
+ }
+
+ const pseudoElementName = this.pseudoElemenName;
+ const originatingElem = this.player.effect.target;
+ const treeWalker = this.walker.getDocumentWalker(originatingElem);
+
+ // When the animated node is a pseudo-element, we need to walk the children
+ // of the target node and look for it.
+ for (
+ let next = treeWalker.firstChild();
+ next;
+ next = treeWalker.nextSibling()
+ ) {
+ if (next.nodeName === pseudoElementName) {
+ return next;
+ }
+ }
+
+ console.warn(
+ `Pseudo element ${this.player.effect.pseudoElement} is not found`
+ );
+ return originatingElem;
+ },
+
+ get document() {
+ return this.node.ownerDocument;
+ },
+
+ get window() {
+ return this.document.defaultView;
+ },
+
+ /**
+ * Release the actor, when it isn't needed anymore.
+ * Protocol.js uses this release method to call the destroy method.
+ */
+ release: function() {},
+
+ form: function(detail) {
+ const data = this.getCurrentState();
+ data.actor = this.actorID;
+
+ // If we know the WalkerActor, and if the animated node is known by it, then
+ // return its corresponding NodeActor ID too.
+ if (this.walker && this.walker.hasNode(this.node)) {
+ data.animationTargetNodeActorID = this.walker.getNode(this.node).actorID;
+ }
+
+ return data;
+ },
+
+ isCssAnimation: function(player = this.player) {
+ return player instanceof this.window.CSSAnimation;
+ },
+
+ isCssTransition: function(player = this.player) {
+ return player instanceof this.window.CSSTransition;
+ },
+
+ isScriptAnimation: function(player = this.player) {
+ return (
+ player instanceof this.window.Animation &&
+ !(
+ player instanceof this.window.CSSAnimation ||
+ player instanceof this.window.CSSTransition
+ )
+ );
+ },
+
+ getType: function() {
+ if (this.isCssAnimation()) {
+ return ANIMATION_TYPES.CSS_ANIMATION;
+ } else if (this.isCssTransition()) {
+ return ANIMATION_TYPES.CSS_TRANSITION;
+ } else if (this.isScriptAnimation()) {
+ return ANIMATION_TYPES.SCRIPT_ANIMATION;
+ }
+
+ return ANIMATION_TYPES.UNKNOWN;
+ },
+
+ /**
+ * Get the name of this animation. This can be either the animation.id
+ * property if it was set, or the keyframe rule name or the transition
+ * property.
+ * @return {String}
+ */
+ getName: function() {
+ if (this.player.id) {
+ return this.player.id;
+ } else if (this.isCssAnimation()) {
+ return this.player.animationName;
+ } else if (this.isCssTransition()) {
+ return this.player.transitionProperty;
+ }
+
+ return "";
+ },
+
+ /**
+ * Get the animation duration from this player, in milliseconds.
+ * @return {Number}
+ */
+ getDuration: function() {
+ return this.player.effect.getComputedTiming().duration;
+ },
+
+ /**
+ * Get the animation delay from this player, in milliseconds.
+ * @return {Number}
+ */
+ getDelay: function() {
+ return this.player.effect.getComputedTiming().delay;
+ },
+
+ /**
+ * Get the animation endDelay from this player, in milliseconds.
+ * @return {Number}
+ */
+ getEndDelay: function() {
+ return this.player.effect.getComputedTiming().endDelay;
+ },
+
+ /**
+ * Get the animation iteration count for this player. That is, how many times
+ * is the animation scheduled to run.
+ * @return {Number} The number of iterations, or null if the animation repeats
+ * infinitely.
+ */
+ getIterationCount: function() {
+ const iterations = this.player.effect.getComputedTiming().iterations;
+ return iterations === Infinity ? null : iterations;
+ },
+
+ /**
+ * Get the animation iterationStart from this player, in ratio.
+ * That is offset of starting position of the animation.
+ * @return {Number}
+ */
+ getIterationStart: function() {
+ return this.player.effect.getComputedTiming().iterationStart;
+ },
+
+ /**
+ * Get the animation easing from this player.
+ * @return {String}
+ */
+ getEasing: function() {
+ return this.player.effect.getComputedTiming().easing;
+ },
+
+ /**
+ * Get the animation fill mode from this player.
+ * @return {String}
+ */
+ getFill: function() {
+ return this.player.effect.getComputedTiming().fill;
+ },
+
+ /**
+ * Get the animation direction from this player.
+ * @return {String}
+ */
+ getDirection: function() {
+ return this.player.effect.getComputedTiming().direction;
+ },
+
+ /**
+ * Get animation-timing-function from animated element if CSS Animations.
+ * @return {String}
+ */
+ getAnimationTimingFunction: function() {
+ if (!this.isCssAnimation()) {
+ return null;
+ }
+
+ let pseudo = null;
+ let target = this.player.effect.target;
+ if (target.type) {
+ // Animated element is a pseudo element.
+ pseudo = target.type;
+ target = target.element;
+ }
+ return this.window.getComputedStyle(target, pseudo).animationTimingFunction;
+ },
+
+ getPropertiesCompositorStatus: function() {
+ const properties = this.player.effect.getProperties();
+ return properties.map(prop => {
+ return {
+ property: prop.property,
+ runningOnCompositor: prop.runningOnCompositor,
+ warning: prop.warning,
+ };
+ });
+ },
+
+ /**
+ * Return the current start of the Animation.
+ * @return {Object}
+ */
+ getState: function() {
+ // Note that if you add a new property to the state object, make sure you
+ // add the corresponding property in the AnimationPlayerFront' initialState
+ // getter.
+ return {
+ type: this.getType(),
+ // startTime is null whenever the animation is paused or waiting to start.
+ startTime: this.player.startTime,
+ currentTime: this.player.currentTime,
+ playState: this.player.playState,
+ playbackRate: this.player.playbackRate,
+ name: this.getName(),
+ duration: this.getDuration(),
+ delay: this.getDelay(),
+ endDelay: this.getEndDelay(),
+ iterationCount: this.getIterationCount(),
+ iterationStart: this.getIterationStart(),
+ fill: this.getFill(),
+ easing: this.getEasing(),
+ direction: this.getDirection(),
+ animationTimingFunction: this.getAnimationTimingFunction(),
+ // animation is hitting the fast path or not. Returns false whenever the
+ // animation is paused as it is taken off the compositor then.
+ isRunningOnCompositor: this.getPropertiesCompositorStatus().some(
+ propState => propState.runningOnCompositor
+ ),
+ propertyState: this.getPropertiesCompositorStatus(),
+ // The document timeline's currentTime is being sent along too. This is
+ // not strictly related to the node's animationPlayer, but is useful to
+ // know the current time of the animation with respect to the document's.
+ documentCurrentTime: this.node.ownerDocument.timeline.currentTime,
+ // The time which this animation created.
+ createdTime: this.createdTime,
+ // The time which an animation's current time when this animation has created.
+ currentTimeAtCreated: this.currentTimeAtCreated,
+ };
+ },
+
+ /**
+ * Get the current state of the AnimationPlayer (currentTime, playState, ...).
+ * Note that the initial state is returned as the form of this actor when it
+ * is initialized.
+ * This protocol method only returns a trimed down version of this state in
+ * case some properties haven't changed since last time (since the front can
+ * reconstruct those). If you want the full state, use the getState method.
+ * @return {Object}
+ */
+ getCurrentState: function() {
+ const newState = this.getState();
+
+ // If we've saved a state before, compare and only send what has changed.
+ // It's expected of the front to also save old states to re-construct the
+ // full state when an incomplete one is received.
+ // This is to minimize protocol traffic.
+ let sentState = {};
+ if (this.currentState) {
+ for (const key in newState) {
+ if (
+ typeof this.currentState[key] === "undefined" ||
+ this.currentState[key] !== newState[key]
+ ) {
+ sentState[key] = newState[key];
+ }
+ }
+ } else {
+ sentState = newState;
+ }
+ this.currentState = newState;
+
+ return sentState;
+ },
+
+ /**
+ * Executed when the current animation changes, used to emit the new state
+ * the the front.
+ */
+ onAnimationMutation: function(mutations) {
+ const isCurrentAnimation = animation => animation === this.player;
+ const hasCurrentAnimation = animations =>
+ animations.some(isCurrentAnimation);
+ let hasChanged = false;
+
+ for (const { removedAnimations, changedAnimations } of mutations) {
+ if (hasCurrentAnimation(removedAnimations)) {
+ // Reset the local copy of the state on removal, since the animation can
+ // be kept on the client and re-added, its state needs to be sent in
+ // full.
+ this.currentState = null;
+ }
+
+ if (hasCurrentAnimation(changedAnimations)) {
+ // Only consider the state has having changed if any of effect timing properties,
+ // animationTimingFunction or playbackRate has changed.
+ const newState = this.getState();
+ const oldState = this.currentState;
+ hasChanged =
+ newState.delay !== oldState.delay ||
+ newState.iterationCount !== oldState.iterationCount ||
+ newState.iterationStart !== oldState.iterationStart ||
+ newState.duration !== oldState.duration ||
+ newState.endDelay !== oldState.endDelay ||
+ newState.direction !== oldState.direction ||
+ newState.easing !== oldState.easing ||
+ newState.fill !== oldState.fill ||
+ newState.animationTimingFunction !==
+ oldState.animationTimingFunction ||
+ newState.playbackRate !== oldState.playbackRate;
+ break;
+ }
+ }
+
+ if (hasChanged) {
+ this.emit("changed", this.getCurrentState());
+ }
+ },
+
+ /**
+ * Get data about the animated properties of this animation player.
+ * @return {Array} Returns a list of animated properties.
+ * Each property contains a list of values, their offsets and distances.
+ */
+ getProperties: function() {
+ const properties = this.player.effect.getProperties().map(property => {
+ return { name: property.property, values: property.values };
+ });
+
+ const DOMWindowUtils = this.window.windowUtils;
+
+ // Fill missing keyframe with computed value.
+ for (const property of properties) {
+ let underlyingValue = null;
+ // Check only 0% and 100% keyframes.
+ [0, property.values.length - 1].forEach(index => {
+ const values = property.values[index];
+ if (values.value !== undefined) {
+ return;
+ }
+ if (!underlyingValue) {
+ let pseudo = null;
+ let target = this.player.effect.target;
+ if (target.type) {
+ // This target is a pseudo element.
+ pseudo = target.type;
+ target = target.element;
+ }
+ const value = DOMWindowUtils.getUnanimatedComputedStyle(
+ target,
+ pseudo,
+ property.name,
+ DOMWindowUtils.FLUSH_NONE
+ );
+ const animationType = getAnimationTypeForLonghand(property.name);
+ underlyingValue =
+ animationType === "float" ? parseFloat(value, 10) : value;
+ }
+ values.value = underlyingValue;
+ });
+ }
+
+ // Calculate the distance.
+ for (const property of properties) {
+ const propertyName = property.name;
+ const maxObject = { distance: -1 };
+ for (let i = 0; i < property.values.length - 1; i++) {
+ const value1 = property.values[i].value;
+ for (let j = i + 1; j < property.values.length; j++) {
+ const value2 = property.values[j].value;
+ const distance = this.getDistance(
+ this.node,
+ propertyName,
+ value1,
+ value2,
+ DOMWindowUtils
+ );
+ if (maxObject.distance >= distance) {
+ continue;
+ }
+ maxObject.distance = distance;
+ maxObject.value1 = value1;
+ maxObject.value2 = value2;
+ }
+ }
+ if (maxObject.distance === 0) {
+ // Distance is zero means that no values change or can't calculate the distance.
+ // In this case, we use the keyframe offset as the distance.
+ property.values.reduce((previous, current) => {
+ // If the current value is same as previous value, use previous distance.
+ current.distance =
+ current.value === previous.value
+ ? previous.distance
+ : current.offset;
+ return current;
+ }, property.values[0]);
+ continue;
+ }
+ const baseValue =
+ maxObject.value1 < maxObject.value2
+ ? maxObject.value1
+ : maxObject.value2;
+ for (const values of property.values) {
+ const value = values.value;
+ const distance = this.getDistance(
+ this.node,
+ propertyName,
+ baseValue,
+ value,
+ DOMWindowUtils
+ );
+ values.distance = distance / maxObject.distance;
+ }
+ }
+ return properties;
+ },
+
+ /**
+ * Get the animation types for a given list of CSS property names.
+ * @param {Array} propertyNames - CSS property names (e.g. background-color)
+ * @return {Object} Returns animation types (e.g. {"background-color": "rgb(0, 0, 0)"}.
+ */
+ getAnimationTypes: function(propertyNames) {
+ const animationTypes = {};
+ for (const propertyName of propertyNames) {
+ animationTypes[propertyName] = getAnimationTypeForLonghand(propertyName);
+ }
+ return animationTypes;
+ },
+
+ /**
+ * Returns the distance of between value1, value2.
+ * @param {Object} target - dom element
+ * @param {String} propertyName - e.g. transform
+ * @param {String} value1 - e.g. translate(0px)
+ * @param {String} value2 - e.g. translate(10px)
+ * @param {Object} DOMWindowUtils
+ * @param {float} distance
+ */
+ getDistance: function(target, propertyName, value1, value2, DOMWindowUtils) {
+ if (value1 === value2) {
+ return 0;
+ }
+ try {
+ const distance = DOMWindowUtils.computeAnimationDistance(
+ target,
+ propertyName,
+ value1,
+ value2
+ );
+ return distance;
+ } catch (e) {
+ // We can't compute the distance such the 'discrete' animation,
+ // 'auto' keyword and so on.
+ return 0;
+ }
+ },
+});
+
+exports.AnimationPlayerActor = AnimationPlayerActor;
+
+/**
+ * The Animations actor lists animation players for a given node.
+ */
+exports.AnimationsActor = protocol.ActorClassWithSpec(animationsSpec, {
+ initialize: function(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+ this.onNavigate = this.onNavigate.bind(this);
+ this.onAnimationMutation = this.onAnimationMutation.bind(this);
+
+ this.allAnimationsPaused = false;
+ this.targetActor.on("will-navigate", this.onWillNavigate);
+ this.targetActor.on("navigate", this.onNavigate);
+ },
+
+ destroy: function() {
+ Actor.prototype.destroy.call(this);
+ this.targetActor.off("will-navigate", this.onWillNavigate);
+ this.targetActor.off("navigate", this.onNavigate);
+
+ this.stopAnimationPlayerUpdates();
+ this.targetActor = this.observer = this.actors = this.walker = null;
+ },
+
+ /**
+ * Clients can optionally call this with a reference to their WalkerActor.
+ * If they do, then AnimationPlayerActor's forms are going to also include
+ * NodeActor IDs when the corresponding NodeActors do exist.
+ * This, in turns, is helpful for clients to avoid having to go back once more
+ * to the server to get a NodeActor for a particular animation.
+ * @param {WalkerActor} walker
+ */
+ setWalkerActor: function(walker) {
+ this.walker = walker;
+ },
+
+ /**
+ * Retrieve the list of AnimationPlayerActor actors for currently running
+ * animations on a node and its descendants.
+ * Note that calling this method a second time will destroy all previously
+ * retrieved AnimationPlayerActors. Indeed, the lifecycle of these actors
+ * is managed here on the server and tied to getAnimationPlayersForNode
+ * being called.
+ * @param {NodeActor} nodeActor The NodeActor as defined in
+ * /devtools/server/actors/inspector
+ */
+ getAnimationPlayersForNode: function(nodeActor) {
+ const animations = nodeActor.rawNode.getAnimations({ subtree: true });
+
+ // Destroy previously stored actors
+ if (this.actors) {
+ for (const actor of this.actors) {
+ actor.destroy();
+ }
+ }
+
+ this.actors = [];
+
+ for (const animation of animations) {
+ const createdTime = this.getCreatedTime(animation);
+ const actor = AnimationPlayerActor(this, animation, createdTime);
+ this.actors.push(actor);
+ }
+
+ // When a front requests the list of players for a node, start listening
+ // for animation mutations on this node to send updates to the front, until
+ // either getAnimationPlayersForNode is called again or
+ // stopAnimationPlayerUpdates is called.
+ this.stopAnimationPlayerUpdates();
+ // ownerGlobal doesn't exist in content privileged windows.
+ // eslint-disable-next-line mozilla/use-ownerGlobal
+ const win = nodeActor.rawNode.ownerDocument.defaultView;
+ this.observer = new win.MutationObserver(this.onAnimationMutation);
+ this.observer.observe(nodeActor.rawNode, {
+ animations: true,
+ subtree: true,
+ });
+
+ return this.actors;
+ },
+
+ onAnimationMutation: function(mutations) {
+ const eventData = [];
+ const readyPromises = [];
+
+ for (const { addedAnimations, removedAnimations } of mutations) {
+ for (const player of removedAnimations) {
+ // Note that animations are reported as removed either when they are
+ // actually removed from the node (e.g. css class removed) or when they
+ // are finished and don't have forwards animation-fill-mode.
+ // In the latter case, we don't send an event, because the corresponding
+ // animation can still be seeked/resumed, so we want the client to keep
+ // its reference to the AnimationPlayerActor.
+ if (player.playState !== "idle") {
+ continue;
+ }
+
+ const index = this.actors.findIndex(a => a.player === player);
+ if (index !== -1) {
+ eventData.push({
+ type: "removed",
+ player: this.actors[index],
+ });
+ this.actors.splice(index, 1);
+ }
+ }
+
+ for (const player of addedAnimations) {
+ // If the added player already exists, it means we previously filtered
+ // it out when it was reported as removed. So filter it out here too.
+ if (this.actors.find(a => a.player === player)) {
+ continue;
+ }
+
+ // If the added player has the same name and target node as a player we
+ // already have, it means it's a transition that's re-starting. So send
+ // a "removed" event for the one we already have.
+ const index = this.actors.findIndex(a => {
+ const isSameType = a.player.constructor === player.constructor;
+ const isSameName =
+ (a.isCssAnimation() &&
+ a.player.animationName === player.animationName) ||
+ (a.isCssTransition() &&
+ a.player.transitionProperty === player.transitionProperty);
+ const isSameNode = a.player.effect.target === player.effect.target;
+
+ return isSameType && isSameNode && isSameName;
+ });
+ if (index !== -1) {
+ eventData.push({
+ type: "removed",
+ player: this.actors[index],
+ });
+ this.actors.splice(index, 1);
+ }
+
+ const createdTime = this.getCreatedTime(player);
+ const actor = AnimationPlayerActor(this, player, createdTime);
+ this.actors.push(actor);
+ eventData.push({
+ type: "added",
+ player: actor,
+ });
+ readyPromises.push(player.ready);
+ }
+ }
+
+ if (eventData.length) {
+ // Let's wait for all added animations to be ready before telling the
+ // front-end.
+ Promise.all(readyPromises).then(() => {
+ this.emit("mutations", eventData);
+ });
+ }
+ },
+
+ /**
+ * After the client has called getAnimationPlayersForNode for a given DOM
+ * node, the actor starts sending animation mutations for this node. If the
+ * client doesn't want this to happen anymore, it should call this method.
+ */
+ stopAnimationPlayerUpdates: function() {
+ if (this.observer && !Cu.isDeadWrapper(this.observer)) {
+ this.observer.disconnect();
+ }
+ },
+
+ onWillNavigate: function({ isTopLevel }) {
+ if (isTopLevel) {
+ this.stopAnimationPlayerUpdates();
+ }
+ },
+
+ onNavigate: function({ isTopLevel }) {
+ if (isTopLevel) {
+ this.allAnimationsPaused = false;
+ }
+ },
+
+ /**
+ * Pause given animations.
+ *
+ * @param {Array} actors A list of AnimationPlayerActor.
+ */
+ pauseSome: function(actors) {
+ for (const { player } of actors) {
+ this.pauseSync(player);
+ }
+
+ return this.waitForNextFrame(actors);
+ },
+
+ /**
+ * Play given animations.
+ *
+ * @param {Array} actors A list of AnimationPlayerActor.
+ */
+ playSome: function(actors) {
+ for (const { player } of actors) {
+ this.playSync(player);
+ }
+
+ return this.waitForNextFrame(actors);
+ },
+
+ /**
+ * Set the current time of several animations at the same time.
+ * @param {Array} players A list of AnimationPlayerActor.
+ * @param {Number} time The new currentTime.
+ * @param {Boolean} shouldPause Should the players be paused too.
+ */
+ setCurrentTimes: function(players, time, shouldPause) {
+ for (const actor of players) {
+ const player = actor.player;
+
+ if (shouldPause) {
+ player.startTime = null;
+ }
+
+ const currentTime =
+ player.playbackRate > 0
+ ? time - actor.createdTime
+ : actor.createdTime - time;
+ player.currentTime = currentTime * Math.abs(player.playbackRate);
+ }
+
+ return this.waitForNextFrame(players);
+ },
+
+ /**
+ * Set the playback rate of several animations at the same time.
+ * @param {Array} actors A list of AnimationPlayerActor.
+ * @param {Number} rate The new rate.
+ */
+ setPlaybackRates: function(players, rate) {
+ return Promise.all(
+ players.map(({ player }) => {
+ player.updatePlaybackRate(rate);
+ return player.ready;
+ })
+ );
+ },
+
+ /**
+ * Pause given player synchronously.
+ *
+ * @param {Object} player
+ */
+ pauseSync(player) {
+ player.startTime = null;
+ },
+
+ /**
+ * Play given player synchronously.
+ *
+ * @param {Object} player
+ */
+ playSync(player) {
+ if (!player.playbackRate) {
+ // We can not play with playbackRate zero.
+ return;
+ }
+
+ // Play animation in a synchronous fashion by setting the start time directly.
+ const currentTime = player.currentTime || 0;
+ player.startTime =
+ player.timeline.currentTime - currentTime / player.playbackRate;
+ },
+
+ /**
+ * Return created fime of given animaiton.
+ *
+ * @param {Object} animation
+ */
+ getCreatedTime(animation) {
+ return (
+ animation.startTime ||
+ animation.timeline.currentTime -
+ animation.currentTime / animation.playbackRate
+ );
+ },
+
+ /**
+ * Wait for next animation frame.
+ *
+ * @param {Array} actors
+ * @return {Promise} which waits for next frame
+ */
+ waitForNextFrame(actors) {
+ const promises = actors.map(actor => {
+ const doc = actor.document;
+ const win = actor.window;
+ const timeAtCurrent = doc.timeline.currentTime;
+
+ return new Promise(resolve => {
+ win.requestAnimationFrame(() => {
+ if (timeAtCurrent === doc.timeline.currentTime) {
+ win.requestAnimationFrame(resolve);
+ } else {
+ resolve();
+ }
+ });
+ });
+ });
+
+ return Promise.all(promises);
+ },
+});
diff --git a/devtools/server/actors/array-buffer.js b/devtools/server/actors/array-buffer.js
new file mode 100644
index 0000000000..005ed14617
--- /dev/null
+++ b/devtools/server/actors/array-buffer.js
@@ -0,0 +1,67 @@
+/* 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 protocol = require("devtools/shared/protocol");
+const { arrayBufferSpec } = require("devtools/shared/specs/array-buffer");
+
+/**
+ * Creates an actor for the specified ArrayBuffer.
+ *
+ * @param {DevToolsServerConnection} conn
+ * The server connection.
+ * @param buffer ArrayBuffer
+ * The buffer.
+ */
+const ArrayBufferActor = protocol.ActorClassWithSpec(arrayBufferSpec, {
+ initialize: function(conn, buffer) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.buffer = buffer;
+ this.bufferLength = buffer.byteLength;
+ },
+
+ rawValue: function() {
+ return this.buffer;
+ },
+
+ form: function() {
+ return {
+ actor: this.actorID,
+ length: this.bufferLength,
+ // The `typeName` is read in the source spec when reading "sourcedata"
+ // which can either be an ArrayBuffer actor or a LongString actor.
+ typeName: this.typeName,
+ };
+ },
+
+ slice(start, count) {
+ const slice = new Uint8Array(this.buffer, start, count);
+ const parts = [];
+ let offset = 0;
+ const PortionSize = 0x6000; // keep it divisible by 3 for btoa() and join()
+ while (offset + PortionSize < count) {
+ parts.push(
+ btoa(
+ String.fromCharCode.apply(
+ null,
+ slice.subarray(offset, offset + PortionSize)
+ )
+ )
+ );
+ offset += PortionSize;
+ }
+ parts.push(
+ btoa(String.fromCharCode.apply(null, slice.subarray(offset, count)))
+ );
+ return {
+ from: this.actorID,
+ encoded: parts.join(""),
+ };
+ },
+});
+
+module.exports = {
+ ArrayBufferActor,
+};
diff --git a/devtools/server/actors/breakpoint-list.js b/devtools/server/actors/breakpoint-list.js
new file mode 100644
index 0000000000..f728be36cf
--- /dev/null
+++ b/devtools/server/actors/breakpoint-list.js
@@ -0,0 +1,46 @@
+/* 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";
+
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { breakpointListSpec } = require("devtools/shared/specs/breakpoint-list");
+const {
+ WatchedDataHelpers,
+} = require("devtools/server/actors/watcher/WatchedDataHelpers.jsm");
+const { SUPPORTED_DATA } = WatchedDataHelpers;
+const { BREAKPOINTS } = SUPPORTED_DATA;
+
+/**
+ * This actor manages the breakpoints list.
+ *
+ * Breakpoints should be available as early as possible to new targets and
+ * will be forwarded to the WatcherActor to populate the shared watcher data available to
+ * all DevTools targets.
+ *
+ * @constructor
+ *
+ */
+const BreakpointListActor = ActorClassWithSpec(breakpointListSpec, {
+ initialize(watcherActor) {
+ this.watcherActor = watcherActor;
+ Actor.prototype.initialize.call(this, this.watcherActor.conn);
+ },
+
+ destroy(conn) {
+ Actor.prototype.destroy.call(this, conn);
+ },
+
+ setBreakpoint(location, options) {
+ return this.watcherActor.addDataEntry(BREAKPOINTS, [{ location, options }]);
+ },
+
+ removeBreakpoint(location, options) {
+ return this.watcherActor.removeDataEntry(BREAKPOINTS, [
+ { location, options },
+ ]);
+ },
+});
+
+exports.BreakpointListActor = BreakpointListActor;
diff --git a/devtools/server/actors/breakpoint.js b/devtools/server/actors/breakpoint.js
new file mode 100644
index 0000000000..64e9fe4466
--- /dev/null
+++ b/devtools/server/actors/breakpoint.js
@@ -0,0 +1,216 @@
+/* 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/. */
+
+/* global assert */
+
+"use strict";
+
+const {
+ logEvent,
+ getThrownMessage,
+} = require("devtools/server/actors/utils/logEvent");
+
+/**
+ * Set breakpoints on all the given entry points with the given
+ * BreakpointActor as the handler.
+ *
+ * @param BreakpointActor actor
+ * The actor handling the breakpoint hits.
+ * @param Array entryPoints
+ * An array of objects of the form `{ script, offsets }`.
+ */
+function setBreakpointAtEntryPoints(actor, entryPoints) {
+ for (const { script, offsets } of entryPoints) {
+ actor.addScript(script, offsets);
+ }
+}
+
+exports.setBreakpointAtEntryPoints = setBreakpointAtEntryPoints;
+
+/**
+ * BreakpointActors are instantiated for each breakpoint that has been installed
+ * by the client. They are not true actors and do not communicate with the
+ * client directly, but encapsulate the DebuggerScript locations where the
+ * breakpoint is installed.
+ */
+function BreakpointActor(threadActor, location) {
+ // A map from Debugger.Script instances to the offsets which the breakpoint
+ // has been set for in that script.
+ this.scripts = new Map();
+
+ this.threadActor = threadActor;
+ this.location = location;
+ this.options = null;
+}
+
+BreakpointActor.prototype = {
+ setOptions(options) {
+ const oldOptions = this.options;
+ this.options = options;
+
+ for (const [script, offsets] of this.scripts) {
+ this._newOffsetsOrOptions(script, offsets, oldOptions);
+ }
+ },
+
+ destroy: function() {
+ this.removeScripts();
+ this.options = null;
+ },
+
+ hasScript: function(script) {
+ return this.scripts.has(script);
+ },
+
+ /**
+ * Called when this same breakpoint is added to another Debugger.Script
+ * instance.
+ *
+ * @param script Debugger.Script
+ * The new source script on which the breakpoint has been set.
+ * @param offsets Array
+ * Any offsets in the script the breakpoint is associated with.
+ */
+ addScript: function(script, offsets) {
+ this.scripts.set(script, offsets.concat(this.scripts.get(offsets) || []));
+ this._newOffsetsOrOptions(script, offsets, null);
+ },
+
+ /**
+ * Remove the breakpoints from associated scripts and clear the script cache.
+ */
+ removeScripts: function() {
+ for (const [script] of this.scripts) {
+ script.clearBreakpoint(this);
+ }
+ this.scripts.clear();
+ },
+
+ /**
+ * Called on changes to this breakpoint's script offsets or options.
+ */
+ _newOffsetsOrOptions(script, offsets, oldOptions) {
+ // Clear any existing handler first in case this is called multiple times
+ // after options change.
+ for (const offset of offsets) {
+ script.clearBreakpoint(this, offset);
+ }
+
+ // In all other cases, this is used as a script breakpoint handler.
+ for (const offset of offsets) {
+ script.setBreakpoint(offset, this);
+ }
+ },
+
+ /**
+ * Check if this breakpoint has a condition that doesn't error and
+ * evaluates to true in frame.
+ *
+ * @param frame Debugger.Frame
+ * The frame to evaluate the condition in
+ * @returns Object
+ * - result: boolean|undefined
+ * True when the conditional breakpoint should trigger a pause,
+ * false otherwise. If the condition evaluation failed/killed,
+ * `result` will be `undefined`.
+ * - message: string
+ * If the condition throws, this is the thrown message.
+ */
+ checkCondition: function(frame, condition) {
+ const completion = frame.eval(condition);
+ if (completion) {
+ if (completion.throw) {
+ // The evaluation failed and threw
+ return {
+ result: true,
+ message: getThrownMessage(completion),
+ };
+ } else if (completion.yield) {
+ assert(false, "Shouldn't ever get yield completions from an eval");
+ } else {
+ return { result: !!completion.return };
+ }
+ }
+ // The evaluation was killed (possibly by the slow script dialog)
+ return { result: undefined };
+ },
+
+ /**
+ * A function that the engine calls when a breakpoint has been hit.
+ *
+ * @param frame Debugger.Frame
+ * The stack frame that contained the breakpoint.
+ */
+ // eslint-disable-next-line complexity
+ hit: function(frame) {
+ // Don't pause if we are currently stepping (in or over) or the frame is
+ // black-boxed.
+ const location = this.threadActor.sourcesManager.getFrameLocation(frame);
+
+ if (
+ this.threadActor.sourcesManager.isFrameBlackBoxed(frame) ||
+ this.threadActor.skipBreakpointsOption
+ ) {
+ return undefined;
+ }
+
+ // If we're trying to pop this frame, and we see a breakpoint at
+ // the spot at which popping started, ignore it. See bug 970469.
+ const locationAtFinish = frame.onPop?.location;
+ if (
+ locationAtFinish &&
+ locationAtFinish.line === location.line &&
+ locationAtFinish.column === location.column
+ ) {
+ return undefined;
+ }
+
+ if (!this.threadActor.hasMoved(frame, "breakpoint")) {
+ return undefined;
+ }
+
+ const reason = { type: "breakpoint", actors: [this.actorID] };
+ const { condition, logValue } = this.options || {};
+
+ if (condition) {
+ const { result, message } = this.checkCondition(frame, condition);
+
+ // Don't pause if the result is falsey
+ if (!result) {
+ return undefined;
+ }
+
+ if (message) {
+ // Don't pause if there is an exception message and POE is false
+ if (!this.threadActor._options.pauseOnExceptions) {
+ return undefined;
+ }
+
+ reason.type = "breakpointConditionThrown";
+ reason.message = message;
+ }
+ }
+
+ if (logValue) {
+ return logEvent({
+ threadActor: this.threadActor,
+ frame,
+ level: "logPoint",
+ expression: `[${logValue}]`,
+ });
+ }
+
+ return this.threadActor._pauseAndRespond(frame, reason);
+ },
+
+ delete: function() {
+ // Remove from the breakpoint store.
+ this.threadActor.breakpointActorMap.deleteActor(this.location);
+ // Remove the actual breakpoint from the associated scripts.
+ this.removeScripts();
+ this.destroy();
+ },
+};
+
+exports.BreakpointActor = BreakpointActor;
diff --git a/devtools/server/actors/changes.js b/devtools/server/actors/changes.js
new file mode 100644
index 0000000000..bcc145038f
--- /dev/null
+++ b/devtools/server/actors/changes.js
@@ -0,0 +1,122 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { changesSpec } = require("devtools/shared/specs/changes");
+const TrackChangeEmitter = require("devtools/server/actors/utils/track-change-emitter");
+
+/**
+ * The ChangesActor stores a stack of changes made by devtools on
+ * the document in the associated tab.
+ */
+const ChangesActor = protocol.ActorClassWithSpec(changesSpec, {
+ /**
+ * Create a ChangesActor.
+ *
+ * @param {DevToolsServerConnection} conn
+ * The server connection.
+ * @param {TargetActor} targetActor
+ * The top-level Actor for this tab.
+ */
+ initialize: function(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+
+ this.onTrackChange = this.pushChange.bind(this);
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ TrackChangeEmitter.on("track-change", this.onTrackChange);
+ this.targetActor.on("will-navigate", this.onWillNavigate);
+
+ this.changes = [];
+ },
+
+ destroy: function() {
+ this.clearChanges();
+ this.targetActor.off("will-navigate", this.onWillNavigate);
+ TrackChangeEmitter.off("track-change", this.onTrackChange);
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ start: function() {
+ /**
+ * This function currently does nothing and returns nothing. It exists only
+ * so that the client can trigger the creation of the ChangesActor through
+ * the front, without triggering side effects, and with a sensible semantic
+ * meaning.
+ */
+ },
+
+ changeCount: function() {
+ return this.changes.length;
+ },
+
+ change: function(index) {
+ if (index >= 0 && index < this.changes.length) {
+ // Return a copy of the change at index.
+ return Object.assign({}, this.changes[index]);
+ }
+ // No change at that index -- return undefined.
+ return undefined;
+ },
+
+ allChanges: function() {
+ /**
+ * This function is called by all change event consumers on the client
+ * to get their initial state synchronized with the ChangesActor. We
+ * set a flag when this function is called so we know that it's worthwhile
+ * to send events.
+ */
+ this._changesHaveBeenRequested = true;
+ return this.changes.slice();
+ },
+
+ /**
+ * Handler for "will-navigate" event from the browsing context. The event is fired for
+ * the host page and any nested resources, like iframes. The list of changes should be
+ * cleared only when the host page navigates, ignoring any of its iframes.
+ *
+ * TODO: Clear changes made within sources in iframes when they navigate. Bug 1513940
+ *
+ * @param {Object} eventData
+ * Event data with these properties:
+ * {
+ * window: Object // Window DOM object of the event source page
+ * isTopLevel: Boolean // true if the host page will navigate
+ * newURI: String // URI towards which the page will navigate
+ * request: Object // Request data.
+ * }
+ */
+ onWillNavigate: function(eventData) {
+ if (eventData.isTopLevel) {
+ this.clearChanges();
+ }
+ },
+
+ pushChange: function(change) {
+ this.changes.push(change);
+ if (this._changesHaveBeenRequested) {
+ this.emit("add-change", change);
+ }
+ },
+
+ popChange: function() {
+ const change = this.changes.pop();
+ if (this._changesHaveBeenRequested) {
+ this.emit("remove-change", change);
+ }
+ return change;
+ },
+
+ clearChanges: function() {
+ this.changes.length = 0;
+ if (this._changesHaveBeenRequested) {
+ this.emit("clear-changes");
+ }
+ },
+});
+
+exports.ChangesActor = ChangesActor;
diff --git a/devtools/server/actors/common.js b/devtools/server/actors/common.js
new file mode 100644
index 0000000000..ab97f7e17a
--- /dev/null
+++ b/devtools/server/actors/common.js
@@ -0,0 +1,116 @@
+/* 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";
+
+/**
+ * A SourceLocation represents a location in a source.
+ *
+ * @param SourceActor actor
+ * A SourceActor representing a source.
+ * @param Number line
+ * A line within the given source.
+ * @param Number column
+ * A column within the given line.
+ */
+function SourceLocation(actor, line, column, lastColumn) {
+ this._connection = actor ? actor.conn : null;
+ this._actorID = actor ? actor.actorID : undefined;
+ this._line = line;
+ this._column = column;
+ this._lastColumn = lastColumn !== undefined ? lastColumn : column + 1;
+}
+
+SourceLocation.prototype = {
+ get sourceActor() {
+ return this._connection ? this._connection.getActor(this._actorID) : null;
+ },
+
+ get url() {
+ return this.sourceActor.url;
+ },
+
+ get line() {
+ return this._line;
+ },
+
+ get column() {
+ return this._column;
+ },
+
+ get lastColumn() {
+ return this._lastColumn;
+ },
+
+ get sourceUrl() {
+ return this.sourceActor.url;
+ },
+
+ equals: function(other) {
+ return (
+ this.sourceActor.url == other.sourceActor.url &&
+ this.line === other.line &&
+ (this.column === undefined ||
+ other.column === undefined ||
+ this.column === other.column)
+ );
+ },
+
+ toJSON: function() {
+ return {
+ source: this.sourceActor.form(),
+ line: this.line,
+ column: this.column,
+ lastColumn: this.lastColumn,
+ };
+ },
+};
+
+exports.SourceLocation = SourceLocation;
+
+/**
+ * A method decorator that ensures the actor is in the expected state before
+ * proceeding. If the actor is not in the expected state, the decorated method
+ * returns a rejected promise.
+ *
+ * The actor's state must be at this.state property.
+ *
+ * @param String expectedState
+ * The expected state.
+ * @param String activity
+ * Additional info about what's going on.
+ * @param Function methodFunc
+ * The actor method to proceed with when the actor is in the expected
+ * state.
+ *
+ * @returns Function
+ * The decorated method.
+ */
+function expectState(expectedState, methodFunc, activity) {
+ return function(...args) {
+ if (this.state !== expectedState) {
+ const msg =
+ `Wrong state while ${activity}:` +
+ `Expected '${expectedState}', ` +
+ `but current state is '${this.state}'.`;
+ return Promise.reject(new Error(msg));
+ }
+
+ return methodFunc.apply(this, args);
+ };
+}
+
+exports.expectState = expectState;
+
+/**
+ * Autobind method from a `bridge` property set on some actors where the
+ * implementation is delegated to a separate class, and where `bridge` points
+ * to an instance of this class.
+ */
+function actorBridgeWithSpec(methodName) {
+ return function() {
+ return this.bridge[methodName].apply(this.bridge, arguments);
+ };
+}
+exports.actorBridgeWithSpec = actorBridgeWithSpec;
diff --git a/devtools/server/actors/compatibility/compatibility.js b/devtools/server/actors/compatibility/compatibility.js
new file mode 100644
index 0000000000..4ace06431d
--- /dev/null
+++ b/devtools/server/actors/compatibility/compatibility.js
@@ -0,0 +1,169 @@
+/* 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 protocol = require("devtools/shared/protocol");
+const { compatibilitySpec } = require("devtools/shared/specs/compatibility");
+
+loader.lazyGetter(this, "mdnCompatibility", () => {
+ const MDNCompatibility = require("devtools/server/actors/compatibility/lib/MDNCompatibility");
+ const cssPropertiesCompatData = require("devtools/shared/compatibility/dataset/css-properties.json");
+ return new MDNCompatibility(cssPropertiesCompatData);
+});
+
+const CompatibilityActor = protocol.ActorClassWithSpec(compatibilitySpec, {
+ /**
+ * Create a CompatibilityActor.
+ * CompatibilityActor is responsible for providing the compatibility information
+ * for the web page using the data from the Inspector and the `MDNCompatibility`
+ * and conveys them to the compatibility panel in the DevTool Inspector. Currently,
+ * the `CompatibilityActor` only detects compatibility issues in the CSS declarations
+ * but plans are in motion to extend it to evaluate compatibility information for
+ * HTML and JavaScript.
+ * The design below has the InspectorActor own the CompatibilityActor, but it's
+ * possible we will want to move it into it's own panel in the future.
+ *
+ * @param inspector
+ * The InspectorActor that owns this CompatibilityActor.
+ *
+ * @constructor
+ */
+ initialize: function(inspector) {
+ protocol.Actor.prototype.initialize.call(this, inspector.conn);
+ this.inspector = inspector;
+ },
+
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+ this.inspector = null;
+ },
+
+ form() {
+ return {
+ actor: this.actorID,
+ };
+ },
+
+ getTraits() {
+ return {
+ traits: {},
+ };
+ },
+
+ /**
+ * Responsible for computing the compatibility issues for a given CSS declaration block
+ * @param Array
+ * Array of CSS declaration object of the form:
+ * {
+ * // Declaration name
+ * name: <string>,
+ * // Declaration value
+ * value: <string>,
+ * }
+ * @param array targetBrowsers
+ * Array of target browsers to be used to check CSS compatibility against.
+ * It is an Array of the following form
+ * {
+ * // Browser id as specified in `devtools/shared/compatibility/datasets/browser.json`
+ * id: <string>,
+ * name: <string>,
+ * version: <string>,
+ * // Browser status - esr, current, beta, nightly
+ * status: <string>,
+ * }
+ * @returns An Array of JSON objects with compatibility information in following form:
+ * {
+ * // Type of compatibility issue
+ * type: <string>,
+ * // The CSS declaration that has compatibility issues
+ * property: <string>,
+ * // Alias to the given CSS property
+ * alias: <Array>,
+ * // Link to MDN documentation for the particular CSS rule
+ * url: <string>,
+ * deprecated: <boolean>,
+ * experimental: <boolean>,
+ * // An array of all the browsers that don't support the given CSS rule
+ * unsupportedBrowsers: <Array>,
+ * }
+ */
+ getCSSDeclarationBlockIssues: function(declarationBlock, targetBrowsers) {
+ return mdnCompatibility.getCSSDeclarationBlockIssues(
+ declarationBlock,
+ targetBrowsers
+ );
+ },
+
+ /**
+ * Responsible for computing the compatibility issues in the
+ * CSS declaration of the given node.
+ * @param NodeActor node
+ * @param targetBrowsers Array
+ * An Array of JSON object of target browser to check compatibility against in following form:
+ * {
+ * // Browser id as specified in `devtools/server/actors/compatibility/lib/datasets/browser.json`
+ * id: <string>,
+ * name: <string>,
+ * version: <string>,
+ * // Browser status - esr, current, beta, nightly
+ * status: <string>,
+ * }
+ * @returns An Array of JSON objects with compatibility information in following form:
+ * {
+ * // Type of compatibility issue
+ * type: <string>,
+ * // The CSS declaration that has compatibility issues
+ * property: <string>,
+ * // Alias to the given CSS property
+ * alias: <Array>,
+ * // Link to MDN documentation for the particular CSS rule
+ * url: <string>,
+ * deprecated: <boolean>,
+ * experimental: <boolean>,
+ * // An array of all the browsers that don't support the given CSS rule
+ * unsupportedBrowsers: <Array>,
+ * }
+ */
+ async getNodeCssIssues(node, targetBrowsers) {
+ const pageStyle = await this.inspector.getPageStyle();
+ const styles = await pageStyle.getApplied(node, {
+ skipPseudo: false,
+ });
+
+ const declarationBlocks = styles.entries
+ .map(({ rule }) => {
+ // Replace form() with a function to get minimal subset
+ // of declarations from StyleRuleActor when such a
+ // function lands in the StyleRuleActor
+ const declarations = rule.form().declarations;
+ if (!declarations) {
+ return null;
+ }
+ return declarations.filter(d => !d.commentOffsets);
+ })
+ .filter(declarations => declarations && declarations.length);
+
+ return declarationBlocks
+ .map(declarationBlock =>
+ mdnCompatibility.getCSSDeclarationBlockIssues(
+ declarationBlock,
+ targetBrowsers
+ )
+ )
+ .flat()
+ .reduce((issues, issue) => {
+ // Get rid of duplicate issue
+ return issues.find(
+ i => i.type === issue.type && i.property === issue.property
+ )
+ ? issues
+ : [...issues, issue];
+ }, []);
+ },
+});
+
+module.exports = {
+ CompatibilityActor,
+};
diff --git a/devtools/server/actors/compatibility/lib/MDNCompatibility.js b/devtools/server/actors/compatibility/lib/MDNCompatibility.js
new file mode 100644
index 0000000000..24df66099e
--- /dev/null
+++ b/devtools/server/actors/compatibility/lib/MDNCompatibility.js
@@ -0,0 +1,496 @@
+/* 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";
+
+const _SUPPORT_STATE = {
+ BROWSER_NOT_FOUND: "BROWSER_NOT_FOUND",
+ DATA_NOT_FOUND: "DATA_NOT_FOUND",
+ SUPPORTED: "SUPPORTED",
+ UNSUPPORTED: "UNSUPPORTED",
+ UNSUPPORTED_PREFIX_NEEDED: "UNSUPPORTED_PREFIX_NEEDED",
+};
+
+const { COMPATIBILITY_ISSUE_TYPE } = require("devtools/shared/constants");
+
+/**
+ * A class with methods used to query the MDN compatibility data for CSS properties and
+ * HTML nodes and attributes for specific browsers and versions.
+ */
+class MDNCompatibility {
+ /**
+ * Constructor.
+ *
+ * @param {JSON} cssPropertiesCompatData
+ * JSON of the compat data for CSS properties.
+ * https://github.com/mdn/browser-compat-data/tree/master/css/properties
+ */
+ constructor(cssPropertiesCompatData) {
+ this._cssPropertiesCompatData = cssPropertiesCompatData;
+
+ // Flatten all CSS properties aliases.
+ this._flattenAliases(this._cssPropertiesCompatData);
+ }
+
+ /**
+ * Return the CSS related compatibility issues from given CSS declaration blocks.
+ *
+ * @param {Array} declarations
+ * CSS declarations to check.
+ * e.g. [{ name: "background-color", value: "lime" }, ...]
+ * @param {Array} browsers
+ * Restrict compatibility checks to these browsers and versions.
+ * e.g. [{ id: "firefox", name: "Firefox", version: "68" }, ...]
+ * @return {Array} issues
+ */
+ getCSSDeclarationBlockIssues(declarations, browsers) {
+ const summaries = [];
+ for (const { name: property } of declarations) {
+ // Ignore CSS custom properties as any name is valid.
+ if (property.startsWith("--")) {
+ continue;
+ }
+
+ summaries.push(this._getCSSPropertyCompatSummary(browsers, property));
+ }
+
+ // Classify to aliases summaries and normal summaries.
+ const {
+ aliasSummaries,
+ normalSummaries,
+ } = this._classifyCSSCompatSummaries(summaries, browsers);
+
+ // Finally, convert to CSS issues.
+ return this._toCSSIssues(normalSummaries.concat(aliasSummaries));
+ }
+
+ _asFloatVersion(version = false) {
+ if (version === true) {
+ return 0;
+ }
+
+ if (version === false) {
+ return Number.MAX_VALUE;
+ }
+
+ if (version.startsWith("\u2264")) {
+ // MDN compatibility data started to use an expression like "≤66" for version.
+ // We just ignore the character here.
+ version = version.substring(1);
+ }
+
+ return parseFloat(version);
+ }
+
+ /**
+ * Classify the compatibility summaries that are able to get from
+ * `getCSSPropertyCompatSummary`.
+ * There are CSS properties that can specify the style with plural aliases such as
+ * `user-select`, aggregates those as the aliases summaries.
+ *
+ * @param {Array} summaries
+ * Assume the result of _getCSSPropertyCompatSummary().
+ * @param {Array} browsers
+ * All browsers that to check
+ * e.g. [{ id: "firefox", name: "Firefox", version: "68" }, ...]
+ * @return Object
+ * {
+ * aliasSummaries: Array of alias summary,
+ * normalSummaries: Array of normal summary
+ * }
+ */
+ _classifyCSSCompatSummaries(summaries, browsers) {
+ const aliasSummariesMap = new Map();
+ const normalSummaries = summaries.filter(s => {
+ const {
+ database,
+ invalid,
+ terms,
+ unsupportedBrowsers,
+ prefixNeededBrowsers,
+ } = s;
+
+ if (invalid) {
+ return true;
+ }
+
+ const alias = this._getAlias(database, ...terms);
+ if (!alias) {
+ return true;
+ }
+
+ if (!aliasSummariesMap.has(alias)) {
+ aliasSummariesMap.set(
+ alias,
+ Object.assign(s, {
+ property: alias,
+ aliases: [],
+ unsupportedBrowsers: browsers,
+ prefixNeededBrowsers: browsers,
+ })
+ );
+ }
+
+ // Update alias summary.
+ const terminal = terms.pop();
+ const aliasSummary = aliasSummariesMap.get(alias);
+ if (!aliasSummary.aliases.includes(terminal)) {
+ aliasSummary.aliases.push(terminal);
+ }
+ aliasSummary.unsupportedBrowsers = aliasSummary.unsupportedBrowsers.filter(
+ b => unsupportedBrowsers.includes(b)
+ );
+ aliasSummary.prefixNeededBrowsers = aliasSummary.prefixNeededBrowsers.filter(
+ b => prefixNeededBrowsers.includes(b)
+ );
+ return false;
+ });
+
+ const aliasSummaries = [...aliasSummariesMap.values()].map(s => {
+ s.prefixNeeded = s.prefixNeededBrowsers.length !== 0;
+ return s;
+ });
+
+ return { aliasSummaries, normalSummaries };
+ }
+
+ _findAliasesFrom(compatTable) {
+ const aliases = [];
+
+ for (const browser in compatTable.support) {
+ let supportStates = compatTable.support[browser] || [];
+ supportStates = Array.isArray(supportStates)
+ ? supportStates
+ : [supportStates];
+
+ for (const { alternative_name: name, prefix } of supportStates) {
+ if (!prefix && !name) {
+ continue;
+ }
+
+ aliases.push({ alternative_name: name, prefix });
+ }
+ }
+
+ return aliases;
+ }
+
+ /**
+ * Builds a list of aliases between CSS properties, like flex and -webkit-flex,
+ * and mutates individual entries in the web compat data store for CSS properties to
+ * add their corresponding aliases.
+ */
+ _flattenAliases(compatNode) {
+ for (const term in compatNode) {
+ if (term.startsWith("_")) {
+ // Ignore exploring if the term is _aliasOf or __compat.
+ continue;
+ }
+
+ const compatTable = this._getCompatTable(compatNode, [term]);
+ if (compatTable) {
+ const aliases = this._findAliasesFrom(compatTable);
+
+ for (const { alternative_name: name, prefix } of aliases) {
+ const alias = name || prefix + term;
+ compatNode[alias] = { _aliasOf: term };
+ }
+
+ if (aliases.length) {
+ // Make the term accessible as the alias.
+ compatNode[term]._aliasOf = term;
+ }
+ }
+
+ // Flatten deeper node as well.
+ this._flattenAliases(compatNode[term]);
+ }
+ }
+
+ _getAlias(compatNode, ...terms) {
+ const targetNode = this._getCompatNode(compatNode, terms);
+ return targetNode ? targetNode._aliasOf : null;
+ }
+
+ _getChildCompatNode(compatNode, term) {
+ term = term.toLowerCase();
+
+ let child = null;
+ for (const field in compatNode) {
+ if (field.toLowerCase() === term) {
+ child = compatNode[field];
+ break;
+ }
+ }
+
+ if (!child) {
+ return null;
+ }
+
+ if (child._aliasOf) {
+ // If the node is an alias, returns the node the alias points.
+ child = compatNode[child._aliasOf];
+ }
+
+ return child;
+ }
+
+ /**
+ * Return a compatibility node which is target for `terms` parameter from `compatNode`
+ * parameter. For example, when check `background-clip: content-box;`, the `terms` will
+ * be ["background-clip", "content-box"]. Then, follow the name of terms from the
+ * compatNode node, return the target node. Although this function actually do more
+ * complex a bit, if it says simply, returns a node of
+ * compatNode["background-clip"]["content-box""] .
+ */
+ _getCompatNode(compatNode, terms) {
+ for (const term of terms) {
+ compatNode = this._getChildCompatNode(compatNode, term);
+ if (!compatNode) {
+ return null;
+ }
+ }
+
+ return compatNode;
+ }
+
+ /**
+ * Return the compatibility table from given compatNode and specified terms.
+ * For example, if the terms is ["background-color"],
+ * this function returns compatNode["background-color"].__compat.
+ *
+ * @return {Object} compatibility table
+ * {
+ * description: {String} Description of this compatibility table.
+ * mdn_url: {String} Document in the MDN.
+ * support: {
+ * $browserName: {String} $browserName is such as firefox, firefox_android and so on.
+ * [
+ * {
+ * version_added: {String}
+ * The version this feature was added.
+ * version_removed: {String} Optional.
+ * The version this feature was removed. Optional.
+ * prefix: {String} Optional.
+ * The prefix this feature is needed such as "-moz-".
+ * alternative_name: {String} Optional.
+ * The alternative name of this feature such as "-moz-osx-font-smoothing" of "font-smooth".
+ * notes: {String} Optional.
+ * A simple note for this support.
+ * },
+ * ...
+ * ],
+ * },
+ * status: {
+ * experimental: {Boolean} If true, this feature is experimental.
+ * standard_track: {Boolean}, If true, this feature is on the standard track.
+ * deprecated: {Boolean} If true, this feature is deprecated.
+ * }
+ * }
+ */
+ _getCompatTable(compatNode, terms) {
+ let targetNode = this._getCompatNode(compatNode, terms);
+
+ if (!targetNode) {
+ return null;
+ }
+
+ if (!targetNode.__compat) {
+ for (const field in targetNode) {
+ // TODO: We don't have a way to know the context for now.
+ // Thus, use first context node as the compat table.
+ // e.g. flex_context of align-item
+ // https://github.com/mdn/browser-compat-data/blob/master/css/properties/align-items.json#L5
+ if (field.endsWith("_context")) {
+ targetNode = targetNode[field];
+ break;
+ }
+ }
+ }
+
+ return targetNode.__compat;
+ }
+
+ /**
+ * Return the compatibility summary of the terms.
+ *
+ * @param {Array} browsers
+ * All browsers that to check
+ * e.g. [{ id: "firefox", name: "Firefox", version: "68" }, ...]
+ * @param {Array} database
+ * MDN compatibility dataset where finds from
+ * @param {Array} terms
+ * The terms which is checked the compatibility summary from the
+ * database. The paremeters are passed as `rest parameters`.
+ * e.g. _getCompatSummary(browsers, database, "user-select", ...)
+ * @return {Object}
+ * {
+ * database: The passed database as a parameter,
+ * terms: The passed terms as a parameter,
+ * url: The link which indicates the spec in MDN,
+ * deprecated: true if the spec of terms is deprecated,
+ * experimental: true if the spec of terms is experimental,
+ * unsupportedBrowsers: Array of unsupported browsers,
+ * }
+ */
+ _getCompatSummary(browsers, database, ...terms) {
+ if (!this._hasTerm(database, ...terms)) {
+ return { invalid: true, unsupportedBrowsers: [] };
+ }
+
+ const { unsupportedBrowsers, prefixNeededBrowsers } = browsers.reduce(
+ (value, browser) => {
+ const state = this._getSupportState(browser, database, ...terms);
+
+ switch (state) {
+ case _SUPPORT_STATE.UNSUPPORTED_PREFIX_NEEDED: {
+ value.prefixNeededBrowsers.push(browser);
+ value.unsupportedBrowsers.push(browser);
+ break;
+ }
+ case _SUPPORT_STATE.UNSUPPORTED: {
+ value.unsupportedBrowsers.push(browser);
+ break;
+ }
+ }
+
+ return value;
+ },
+ { unsupportedBrowsers: [], prefixNeededBrowsers: [] }
+ );
+
+ const { deprecated, experimental } = this._getStatus(database, ...terms);
+ const url = this._getMDNLink(database, ...terms);
+
+ return {
+ database,
+ terms,
+ url,
+ deprecated,
+ experimental,
+ unsupportedBrowsers,
+ prefixNeededBrowsers,
+ };
+ }
+
+ /**
+ * Return the compatibility summary of the CSS property.
+ * This function just adds `property` filed to the result of `_getCompatSummary`.
+ *
+ * @param {Array} browsers
+ * All browsers that to check
+ * e.g. [{ id: "firefox", name: "Firefox", version: "68" }, ...]
+ * @return {Object} compatibility summary
+ */
+ _getCSSPropertyCompatSummary(browsers, property) {
+ const summary = this._getCompatSummary(
+ browsers,
+ this._cssPropertiesCompatData,
+ property
+ );
+ return Object.assign(summary, { property });
+ }
+
+ _getMDNLink(compatNode, ...terms) {
+ for (; terms.length > 0; terms.pop()) {
+ const compatTable = this._getCompatTable(compatNode, terms);
+ const url = compatTable ? compatTable.mdn_url : null;
+
+ if (url) {
+ return url;
+ }
+ }
+
+ return null;
+ }
+
+ _getSupportState(browser, compatNode, ...terms) {
+ const compatTable = this._getCompatTable(compatNode, terms);
+ if (!compatTable) {
+ return _SUPPORT_STATE.DATA_NOT_FOUND;
+ }
+
+ let supportList = compatTable.support[browser.id];
+ if (!supportList) {
+ return _SUPPORT_STATE.BROWSER_NOT_FOUND;
+ }
+
+ supportList = Array.isArray(supportList) ? supportList : [supportList];
+ const version = parseFloat(browser.version);
+ const terminal = terms[terms.length - 1];
+ const match = terminal.match(/^-\w+-/);
+ const prefix = match ? match[0] : undefined;
+ // There are compat data that are defined with prefix like "-moz-binding".
+ // In this case, we don't have to check the prefix.
+ const isPrefixedData = prefix && !this._getAlias(compatNode, ...terms);
+
+ let prefixNeeded = false;
+ for (const support of supportList) {
+ const { version_added: added, version_removed: removed } = support;
+ const addedVersion = this._asFloatVersion(added === null ? true : added);
+ const removedVersion = this._asFloatVersion(
+ removed === null ? false : removed
+ );
+
+ if (addedVersion <= version && version < removedVersion) {
+ if (support.alternative_name) {
+ if (support.alternative_name === terminal) {
+ return _SUPPORT_STATE.SUPPORTED;
+ }
+ } else if (isPrefixedData || support.prefix === prefix) {
+ return _SUPPORT_STATE.SUPPORTED;
+ }
+
+ prefixNeeded = true;
+ }
+ }
+
+ return prefixNeeded
+ ? _SUPPORT_STATE.UNSUPPORTED_PREFIX_NEEDED
+ : _SUPPORT_STATE.UNSUPPORTED;
+ }
+
+ _getStatus(compatNode, ...terms) {
+ const compatTable = this._getCompatTable(compatNode, terms);
+ return compatTable ? compatTable.status : {};
+ }
+
+ _hasIssue({ unsupportedBrowsers, deprecated, experimental, invalid }) {
+ // Don't apply as issue the invalid term which was not in the database.
+ return (
+ !invalid && (unsupportedBrowsers.length || deprecated || experimental)
+ );
+ }
+
+ _hasTerm(compatNode, ...terms) {
+ return !!this._getCompatTable(compatNode, terms);
+ }
+
+ _toIssue(summary, type) {
+ const issue = Object.assign({}, summary, { type });
+ delete issue.database;
+ delete issue.terms;
+ delete issue.prefixNeededBrowsers;
+ return issue;
+ }
+
+ _toCSSIssues(summaries) {
+ const issues = [];
+
+ for (const summary of summaries) {
+ if (!this._hasIssue(summary)) {
+ continue;
+ }
+
+ const type = summary.aliases
+ ? COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY_ALIASES
+ : COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY;
+ issues.push(this._toIssue(summary, type));
+ }
+
+ return issues;
+ }
+}
+
+module.exports = MDNCompatibility;
diff --git a/devtools/server/actors/compatibility/lib/moz.build b/devtools/server/actors/compatibility/lib/moz.build
new file mode 100644
index 0000000000..f28d8fe482
--- /dev/null
+++ b/devtools/server/actors/compatibility/lib/moz.build
@@ -0,0 +1,11 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+XPCSHELL_TESTS_MANIFESTS += ["test/xpcshell/xpcshell.ini"]
+
+DevToolsModules(
+ "MDNCompatibility.js",
+)
diff --git a/devtools/server/actors/compatibility/lib/test/xpcshell/.eslintrc.js b/devtools/server/actors/compatibility/lib/test/xpcshell/.eslintrc.js
new file mode 100644
index 0000000000..65efbdee13
--- /dev/null
+++ b/devtools/server/actors/compatibility/lib/test/xpcshell/.eslintrc.js
@@ -0,0 +1,6 @@
+"use strict";
+
+module.exports = {
+ // Extend from the common devtools xpcshell eslintrc config.
+ extends: "../../../../../../.eslintrc.xpcshell.js",
+};
diff --git a/devtools/server/actors/compatibility/lib/test/xpcshell/head.js b/devtools/server/actors/compatibility/lib/test/xpcshell/head.js
new file mode 100644
index 0000000000..93a0b0881f
--- /dev/null
+++ b/devtools/server/actors/compatibility/lib/test/xpcshell/head.js
@@ -0,0 +1,8 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+/* eslint no-unused-vars: [2, {"vars": "local"}] */
+
+const { require } = ChromeUtils.import("resource://devtools/shared/Loader.jsm");
diff --git a/devtools/server/actors/compatibility/lib/test/xpcshell/test_mdn-compatibility.js b/devtools/server/actors/compatibility/lib/test/xpcshell/test_mdn-compatibility.js
new file mode 100644
index 0000000000..046307921a
--- /dev/null
+++ b/devtools/server/actors/compatibility/lib/test/xpcshell/test_mdn-compatibility.js
@@ -0,0 +1,186 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+"use strict";
+
+// Test for the MDN compatibility diagnosis module.
+
+const { COMPATIBILITY_ISSUE_TYPE } = require("devtools/shared/constants");
+const MDNCompatibility = require("devtools/server/actors/compatibility/lib/MDNCompatibility");
+const cssPropertiesCompatData = require("devtools/shared/compatibility/dataset/css-properties.json");
+
+const mdnCompatibility = new MDNCompatibility(cssPropertiesCompatData);
+
+const FIREFOX_1 = {
+ id: "firefox",
+ version: "1",
+};
+
+const FIREFOX_60 = {
+ id: "firefox",
+ version: "60",
+};
+
+const FIREFOX_69 = {
+ id: "firefox",
+ version: "69",
+};
+
+const FIREFOX_ANDROID_1 = {
+ id: "firefox_android",
+ version: "1",
+};
+
+const SAFARI_13 = {
+ id: "safari",
+ version: "13",
+};
+
+const TEST_DATA = [
+ {
+ description: "Test for a supported property",
+ declarations: [{ name: "background-color" }],
+ browsers: [FIREFOX_69],
+ expectedIssues: [],
+ },
+ {
+ description: "Test for some supported properties",
+ declarations: [{ name: "background-color" }, { name: "color" }],
+ browsers: [FIREFOX_69],
+ expectedIssues: [],
+ },
+ {
+ description: "Test for an unsupported property",
+ declarations: [{ name: "grid-column" }],
+ browsers: [FIREFOX_1],
+ expectedIssues: [
+ {
+ type: COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY,
+ property: "grid-column",
+ url: "https://developer.mozilla.org/docs/Web/CSS/grid-column",
+ deprecated: false,
+ experimental: false,
+ unsupportedBrowsers: [FIREFOX_1],
+ },
+ ],
+ },
+ {
+ description: "Test for an unknown property",
+ declarations: [{ name: "unknown-property" }],
+ browsers: [FIREFOX_69],
+ expectedIssues: [],
+ },
+ {
+ description: "Test for a deprecated property",
+ declarations: [{ name: "clip" }],
+ browsers: [FIREFOX_69],
+ expectedIssues: [
+ {
+ type: COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY,
+ property: "clip",
+ url: "https://developer.mozilla.org/docs/Web/CSS/clip",
+ deprecated: true,
+ experimental: false,
+ unsupportedBrowsers: [],
+ },
+ ],
+ },
+ {
+ description: "Test for a property having some issues",
+ declarations: [{ name: "font-variant-alternates" }],
+ browsers: [FIREFOX_1],
+ expectedIssues: [
+ {
+ type: COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY,
+ property: "font-variant-alternates",
+ url:
+ "https://developer.mozilla.org/docs/Web/CSS/font-variant-alternates",
+ deprecated: true,
+ experimental: false,
+ unsupportedBrowsers: [FIREFOX_1],
+ },
+ ],
+ },
+ {
+ description:
+ "Test for an aliased property not supported in all browsers with prefix needed",
+ declarations: [{ name: "-moz-user-select" }],
+ browsers: [FIREFOX_69, SAFARI_13],
+ expectedIssues: [
+ {
+ type: COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY_ALIASES,
+ property: "user-select",
+ aliases: ["-moz-user-select"],
+ url: "https://developer.mozilla.org/docs/Web/CSS/user-select",
+ deprecated: false,
+ experimental: false,
+ prefixNeeded: true,
+ unsupportedBrowsers: [SAFARI_13],
+ },
+ ],
+ },
+ {
+ description:
+ "Test for an aliased property not supported in all browsers without prefix needed",
+ declarations: [
+ { name: "-moz-user-select" },
+ { name: "-webkit-user-select" },
+ ],
+ browsers: [FIREFOX_ANDROID_1, FIREFOX_69, SAFARI_13],
+ expectedIssues: [
+ {
+ type: COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY_ALIASES,
+ property: "user-select",
+ aliases: ["-moz-user-select", "-webkit-user-select"],
+ url: "https://developer.mozilla.org/docs/Web/CSS/user-select",
+ deprecated: false,
+ experimental: false,
+ prefixNeeded: false,
+ unsupportedBrowsers: [FIREFOX_ANDROID_1],
+ },
+ ],
+ },
+ {
+ description: "Test for aliased properties supported in all browsers",
+ declarations: [
+ { name: "-moz-user-select" },
+ { name: "-webkit-user-select" },
+ ],
+ browsers: [FIREFOX_69, SAFARI_13],
+ expectedIssues: [],
+ },
+ {
+ description: "Test for a property defined with prefix",
+ declarations: [{ name: "-moz-binding" }],
+ browsers: [FIREFOX_1, FIREFOX_60, FIREFOX_69],
+ expectedIssues: [
+ {
+ type: COMPATIBILITY_ISSUE_TYPE.CSS_PROPERTY,
+ property: "-moz-binding",
+ url: "https://developer.mozilla.org/docs/Web/CSS/-moz-binding",
+ deprecated: true,
+ experimental: false,
+ unsupportedBrowsers: [FIREFOX_69],
+ },
+ ],
+ },
+];
+
+add_task(() => {
+ for (const {
+ description,
+ declarations,
+ browsers,
+ expectedIssues,
+ } of TEST_DATA) {
+ info(description);
+ const issues = mdnCompatibility.getCSSDeclarationBlockIssues(
+ declarations,
+ browsers
+ );
+ deepEqual(
+ issues,
+ expectedIssues,
+ "CSS declaration compatibility data matches expectations"
+ );
+ }
+});
diff --git a/devtools/server/actors/compatibility/lib/test/xpcshell/xpcshell.ini b/devtools/server/actors/compatibility/lib/test/xpcshell/xpcshell.ini
new file mode 100644
index 0000000000..490afa9504
--- /dev/null
+++ b/devtools/server/actors/compatibility/lib/test/xpcshell/xpcshell.ini
@@ -0,0 +1,7 @@
+[DEFAULT]
+tags = devtools
+head = head.js
+firefox-appdir = browser
+skip-if = toolkit == 'android'
+
+[test_mdn-compatibility.js]
diff --git a/devtools/server/actors/compatibility/moz.build b/devtools/server/actors/compatibility/moz.build
new file mode 100644
index 0000000000..010b027d37
--- /dev/null
+++ b/devtools/server/actors/compatibility/moz.build
@@ -0,0 +1,16 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "lib",
+]
+
+DevToolsModules(
+ "compatibility.js",
+)
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Inspector: Compatibility")
diff --git a/devtools/server/actors/css-properties.js b/devtools/server/actors/css-properties.js
new file mode 100644
index 0000000000..6bc57bb2c9
--- /dev/null
+++ b/devtools/server/actors/css-properties.js
@@ -0,0 +1,121 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { ActorClassWithSpec, Actor } = protocol;
+const { cssPropertiesSpec } = require("devtools/shared/specs/css-properties");
+const { cssColors } = require("devtools/shared/css/color-db");
+const InspectorUtils = require("InspectorUtils");
+
+loader.lazyRequireGetter(
+ this,
+ "CSS_TYPES",
+ "devtools/shared/css/constants",
+ true
+);
+
+exports.CssPropertiesActor = ActorClassWithSpec(cssPropertiesSpec, {
+ initialize(conn) {
+ Actor.prototype.initialize.call(this, conn);
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+ },
+
+ getCSSDatabase() {
+ const properties = generateCssProperties();
+ const pseudoElements = InspectorUtils.getCSSPseudoElementNames();
+ const supportedFeature = {
+ // checking for css-color-4 color function support.
+ "css-color-4-color-function": InspectorUtils.isValidCSSColor(
+ "rgb(1 1 1 / 100%)"
+ ),
+ };
+
+ return { properties, pseudoElements, supportedFeature };
+ },
+});
+
+/**
+ * Generate the CSS properties object. Every key is the property name, while
+ * the values are objects that contain information about that property.
+ *
+ * @return {Object}
+ */
+function generateCssProperties() {
+ const properties = {};
+ const propertyNames = InspectorUtils.getCSSPropertyNames({
+ includeAliases: true,
+ });
+ const colors = Object.keys(cssColors);
+
+ propertyNames.forEach(name => {
+ // Get the list of CSS types this property supports.
+ const supports = [];
+ for (const type in CSS_TYPES) {
+ if (safeCssPropertySupportsType(name, type)) {
+ supports.push(type);
+ }
+ }
+
+ // Don't send colors over RDP, these will be re-attached by the front.
+ let values = InspectorUtils.getCSSValuesForProperty(name);
+ if (values.includes("aliceblue")) {
+ values = values.filter(x => !colors.includes(x));
+ values.unshift("COLOR");
+ }
+
+ const subproperties = InspectorUtils.getSubpropertiesForCSSProperty(name);
+
+ properties[name] = {
+ isInherited: InspectorUtils.isInheritedProperty(name),
+ values,
+ supports,
+ subproperties,
+ };
+ });
+
+ return properties;
+}
+exports.generateCssProperties = generateCssProperties;
+
+/**
+ * Test if a CSS is property is known using server-code.
+ *
+ * @param {string} name
+ * @return {Boolean}
+ */
+function isCssPropertyKnown(name) {
+ try {
+ // If the property name is unknown, the cssPropertyIsShorthand
+ // will throw an exception. But if it is known, no exception will
+ // be thrown; so we just ignore the return value.
+ InspectorUtils.cssPropertyIsShorthand(name);
+ return true;
+ } catch (e) {
+ return false;
+ }
+}
+
+exports.isCssPropertyKnown = isCssPropertyKnown;
+
+/**
+ * A wrapper for InspectorUtils.cssPropertySupportsType that ignores invalid
+ * properties.
+ *
+ * @param {String} name The property name.
+ * @param {number} type The type tested for support.
+ * @return {Boolean} Whether the property supports the type.
+ * If the property is unknown, false is returned.
+ */
+function safeCssPropertySupportsType(name, type) {
+ try {
+ return InspectorUtils.cssPropertySupportsType(name, type);
+ } catch (e) {
+ return false;
+ }
+}
diff --git a/devtools/server/actors/descriptors/moz.build b/devtools/server/actors/descriptors/moz.build
new file mode 100644
index 0000000000..bf297b3dcb
--- /dev/null
+++ b/devtools/server/actors/descriptors/moz.build
@@ -0,0 +1,12 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "process.js",
+ "tab.js",
+ "webextension.js",
+ "worker.js",
+)
diff --git a/devtools/server/actors/descriptors/process.js b/devtools/server/actors/descriptors/process.js
new file mode 100644
index 0000000000..b15e6b0b19
--- /dev/null
+++ b/devtools/server/actors/descriptors/process.js
@@ -0,0 +1,169 @@
+/* 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";
+
+const Services = require("Services");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const { Cc, Ci } = require("chrome");
+
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const {
+ processDescriptorSpec,
+} = require("devtools/shared/specs/descriptors/process");
+
+loader.lazyRequireGetter(
+ this,
+ "ContentProcessTargetActor",
+ "devtools/server/actors/targets/content-process",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "ParentProcessTargetActor",
+ "devtools/server/actors/targets/parent-process",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "connectToContentProcess",
+ "devtools/server/connectors/content-process-connector",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WatcherActor",
+ "devtools/server/actors/watcher",
+ true
+);
+
+const ProcessDescriptorActor = ActorClassWithSpec(processDescriptorSpec, {
+ initialize(connection, options = {}) {
+ if ("id" in options && typeof options.id != "number") {
+ throw Error("process connect requires a valid `id` attribute.");
+ }
+ Actor.prototype.initialize.call(this, connection);
+ this.id = options.id;
+ this._browsingContextTargetActor = null;
+ this.isParent = options.parent;
+ this.destroy = this.destroy.bind(this);
+ },
+
+ get browsingContextID() {
+ if (this._browsingContextTargetActor) {
+ return this._browsingContextTargetActor.docShell.browsingContext.id;
+ }
+ return null;
+ },
+
+ _parentProcessConnect() {
+ const env = Cc["@mozilla.org/process/environment;1"].getService(
+ Ci.nsIEnvironment
+ );
+ const isXpcshell = env.exists("XPCSHELL_TEST_PROFILE_DIR");
+ let targetActor;
+ if (isXpcshell) {
+ // Check if we are running on xpcshell.
+ // When running on xpcshell, there is no valid browsing context to attach to
+ // and so ParentProcessTargetActor doesn't make sense as it inherits from
+ // BrowsingContextTargetActor. So instead use ContentProcessTargetActor, which
+ // matches xpcshell needs.
+ targetActor = new ContentProcessTargetActor(this.conn);
+ } else {
+ // Create the target actor for the parent process, which is in the same process
+ // as this target. Because we are in the same process, we have a true actor that
+ // should be managed by the ProcessDescriptorActor.
+ targetActor = new ParentProcessTargetActor(this.conn);
+ // this is a special field that only parent process with a browsing context
+ // have, as they are the only processes at the moment that have child
+ // browsing contexts
+ this._browsingContextTargetActor = targetActor;
+ }
+ this.manage(targetActor);
+ // to be consistent with the return value of the _childProcessConnect, we are returning
+ // the form here. This might be memoized in the future
+ return targetActor.form();
+ },
+
+ /**
+ * Connect to a remote process actor, always a ContentProcess target.
+ */
+ async _childProcessConnect() {
+ const { id } = this;
+ const mm = this._lookupMessageManager(id);
+ if (!mm) {
+ return {
+ error: "noProcess",
+ message: "There is no process with id '" + id + "'.",
+ };
+ }
+ const childTargetForm = await connectToContentProcess(
+ this.conn,
+ mm,
+ this.destroy
+ );
+ return childTargetForm;
+ },
+
+ _lookupMessageManager(id) {
+ for (let i = 0; i < Services.ppmm.childCount; i++) {
+ const mm = Services.ppmm.getChildAt(i);
+
+ // A zero id is used for the parent process, instead of its actual pid.
+ if (id ? mm.osPid == id : mm.isInProcess) {
+ return mm;
+ }
+ }
+ return null;
+ },
+
+ /**
+ * Connect the a process actor.
+ */
+ async getTarget() {
+ if (!DevToolsServer.allowChromeProcess) {
+ return {
+ error: "forbidden",
+ message: "You are not allowed to debug processes.",
+ };
+ }
+ if (this.isParent) {
+ return this._parentProcessConnect();
+ }
+ // This is a remote process we are connecting to
+ return this._childProcessConnect();
+ },
+
+ /**
+ * Return a Watcher actor, allowing to keep track of targets which
+ * already exists or will be created. It also helps knowing when they
+ * are destroyed.
+ */
+ getWatcher() {
+ if (!this.watcher) {
+ this.watcher = new WatcherActor(this.conn);
+ this.manage(this.watcher);
+ }
+ return this.watcher;
+ },
+
+ form() {
+ return {
+ actor: this.actorID,
+ id: this.id,
+ isParent: this.isParent,
+ traits: {
+ // Supports the Watcher actor. Can be removed as part of Bug 1680280.
+ watcher: true,
+ },
+ };
+ },
+
+ destroy() {
+ this._browsingContextTargetActor = null;
+ Actor.prototype.destroy.call(this);
+ },
+});
+
+exports.ProcessDescriptorActor = ProcessDescriptorActor;
diff --git a/devtools/server/actors/descriptors/tab.js b/devtools/server/actors/descriptors/tab.js
new file mode 100644
index 0000000000..b08cad801f
--- /dev/null
+++ b/devtools/server/actors/descriptors/tab.js
@@ -0,0 +1,216 @@
+/* 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";
+
+/*
+ * Descriptor Actor that represents a Tab in the parent process. It
+ * launches a FrameTargetActor in the content process to do the real work and tunnels the
+ * data.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const Services = require("Services");
+const {
+ connectToFrame,
+} = require("devtools/server/connectors/frame-connector");
+loader.lazyImporter(
+ this,
+ "PlacesUtils",
+ "resource://gre/modules/PlacesUtils.jsm"
+);
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { tabDescriptorSpec } = require("devtools/shared/specs/descriptors/tab");
+const { AppConstants } = require("resource://gre/modules/AppConstants.jsm");
+
+loader.lazyRequireGetter(
+ this,
+ "WatcherActor",
+ "devtools/server/actors/watcher",
+ true
+);
+
+/**
+ * Creates a target actor proxy for handling requests to a single browser frame.
+ * Both <xul:browser> and <iframe mozbrowser> are supported.
+ * This actor is a shim that connects to a FrameTargetActor in a remote browser process.
+ * All RDP packets get forwarded using the message manager.
+ *
+ * @param connection The main RDP connection.
+ * @param browser <xul:browser> or <iframe mozbrowser> element to connect to.
+ */
+const TabDescriptorActor = ActorClassWithSpec(tabDescriptorSpec, {
+ initialize(connection, browser) {
+ Actor.prototype.initialize.call(this, connection);
+ this._conn = connection;
+ this._browser = browser;
+ },
+
+ form() {
+ const form = {
+ actor: this.actorID,
+ browsingContextID:
+ this._browser && this._browser.browsingContext
+ ? this._browser.browsingContext.id
+ : null,
+ isZombieTab: this._isZombieTab(),
+ outerWindowID: this._getOuterWindowId(),
+ selected: this.selected,
+ title: this._getTitle(),
+ traits: {
+ // Supports the Watcher actor. Can be removed as part of Bug 1680280.
+ watcher: true,
+ },
+ url: this._getUrl(),
+ };
+
+ return form;
+ },
+
+ _getTitle() {
+ // If the content already provides a title, use it.
+ if (this._browser.contentTitle) {
+ return this._browser.contentTitle;
+ }
+
+ // For zombie or lazy tabs (tab created, but content has not been loaded),
+ // try to retrieve the title from the XUL Tab itself.
+ // Note: this only works on Firefox desktop.
+ if (this._tabbrowser) {
+ const tab = this._tabbrowser.getTabForBrowser(this._browser);
+ if (tab) {
+ return tab.label;
+ }
+ }
+
+ // No title available.
+ return null;
+ },
+
+ _getUrl() {
+ if (!this._browser || !this._browser.browsingContext) {
+ return "";
+ }
+
+ const { browsingContext } = this._browser;
+ return browsingContext.currentWindowGlobal.documentURI.spec;
+ },
+
+ _getOuterWindowId() {
+ if (!this._browser || !this._browser.browsingContext) {
+ return "";
+ }
+
+ const { browsingContext } = this._browser;
+ return browsingContext.currentWindowGlobal.outerWindowId;
+ },
+
+ get selected() {
+ // getMostRecentBrowserWindow will find the appropriate window on Firefox
+ // Desktop and on GeckoView.
+ const topAppWindow = Services.wm.getMostRecentBrowserWindow();
+
+ const selectedBrowser = topAppWindow?.gBrowser?.selectedBrowser;
+ if (!selectedBrowser) {
+ // Note: gBrowser is not available on GeckoView.
+ // We should find another way to know if this browser is the selected
+ // browser. See Bug 1631020.
+ return false;
+ }
+
+ return this._browser === selectedBrowser;
+ },
+
+ async getTarget() {
+ if (!this._conn) {
+ return {
+ error: "tabDestroyed",
+ message: "Tab destroyed while performing a TabDescriptorActor update",
+ };
+ }
+
+ /* eslint-disable-next-line no-async-promise-executor */
+ return new Promise(async (resolve, reject) => {
+ const onDestroy = () => {
+ // Reject the update promise if the tab was destroyed while requesting an update
+ reject({
+ error: "tabDestroyed",
+ message: "Tab destroyed while performing a TabDescriptorActor update",
+ });
+ };
+
+ try {
+ // Check if the browser is still connected before calling connectToFrame
+ if (!this._browser.isConnected) {
+ onDestroy();
+ return;
+ }
+
+ const connectForm = await connectToFrame(
+ this._conn,
+ this._browser,
+ onDestroy
+ );
+
+ resolve(connectForm);
+ } catch (e) {
+ reject({
+ error: "tabDestroyed",
+ message: "Tab destroyed while connecting to the frame",
+ });
+ }
+ });
+ },
+
+ /**
+ * Return a Watcher actor, allowing to keep track of targets which
+ * already exists or will be created. It also helps knowing when they
+ * are destroyed.
+ */
+ getWatcher() {
+ if (!this.watcher) {
+ this.watcher = new WatcherActor(this.conn, { browser: this._browser });
+ this.manage(this.watcher);
+ }
+ return this.watcher;
+ },
+
+ get _tabbrowser() {
+ if (this._browser && typeof this._browser.getTabBrowser == "function") {
+ return this._browser.getTabBrowser();
+ }
+ return null;
+ },
+
+ async getFavicon() {
+ if (!AppConstants.MOZ_PLACES) {
+ // PlacesUtils is not supported
+ return null;
+ }
+
+ try {
+ const { data } = await PlacesUtils.promiseFaviconData(this._getUrl());
+ return data;
+ } catch (e) {
+ // Favicon unavailable for this url.
+ return null;
+ }
+ },
+
+ _isZombieTab() {
+ // Note: GeckoView doesn't support zombie tabs
+ const tabbrowser = this._tabbrowser;
+ const tab = tabbrowser ? tabbrowser.getTabForBrowser(this._browser) : null;
+ return tab?.hasAttribute && tab.hasAttribute("pending");
+ },
+
+ destroy() {
+ this._browser = null;
+
+ Actor.prototype.destroy.call(this);
+ },
+});
+
+exports.TabDescriptorActor = TabDescriptorActor;
diff --git a/devtools/server/actors/descriptors/webextension.js b/devtools/server/actors/descriptors/webextension.js
new file mode 100644
index 0000000000..bd4079c676
--- /dev/null
+++ b/devtools/server/actors/descriptors/webextension.js
@@ -0,0 +1,252 @@
+/* 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";
+
+/*
+ * Represents a WebExtension add-on in the parent process. This gives some metadata about
+ * the add-on and watches for uninstall events. This uses a proxy to access the
+ * WebExtension in the WebExtension process via the message manager.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const protocol = require("devtools/shared/protocol");
+const {
+ webExtensionDescriptorSpec,
+} = require("devtools/shared/specs/descriptors/webextension");
+const {
+ connectToFrame,
+} = require("devtools/server/connectors/frame-connector");
+
+loader.lazyImporter(
+ this,
+ "AddonManager",
+ "resource://gre/modules/AddonManager.jsm"
+);
+loader.lazyImporter(
+ this,
+ "ExtensionParent",
+ "resource://gre/modules/ExtensionParent.jsm"
+);
+
+/**
+ * Creates the actor that represents the addon in the parent process, which connects
+ * itself to a WebExtensionTargetActor counterpart which is created in the extension
+ * process (or in the main process if the WebExtensions OOP mode is disabled).
+ *
+ * The WebExtensionDescriptorActor subscribes itself as an AddonListener on the AddonManager
+ * and forwards this events to child actor (e.g. on addon reload or when the addon is
+ * uninstalled completely) and connects to the child extension process using a `browser`
+ * element provided by the extension internals (it is not related to any single extension,
+ * but it will be created automatically to the currently selected "WebExtensions OOP mode"
+ * and it persist across the extension reloads (it is destroyed once the actor exits).
+ * WebExtensionDescriptorActor is a child of RootActor, it can be retrieved via
+ * RootActor.listAddons request.
+ *
+ * @param {DevToolsServerConnection} conn
+ * The connection to the client.
+ * @param {AddonWrapper} addon
+ * The target addon.
+ */
+const WebExtensionDescriptorActor = protocol.ActorClassWithSpec(
+ webExtensionDescriptorSpec,
+ {
+ initialize(conn, addon) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.addon = addon;
+ this.addonId = addon.id;
+ this._childFormPromise = null;
+
+ // Called when the debug browser element has been destroyed
+ this._extensionFrameDisconnect = this._extensionFrameDisconnect.bind(
+ this
+ );
+ this._onChildExit = this._onChildExit.bind(this);
+ AddonManager.addAddonListener(this);
+ },
+
+ form() {
+ const policy = ExtensionParent.WebExtensionPolicy.getByID(this.addonId);
+ return {
+ actor: this.actorID,
+ debuggable: this.addon.isDebuggable,
+ hidden: this.addon.hidden,
+ // iconDataURL is available after calling loadIconDataURL
+ iconDataURL: this._iconDataURL,
+ iconURL: this.addon.iconURL,
+ id: this.addonId,
+ isSystem: this.addon.isSystem,
+ isWebExtension: this.addon.isWebExtension,
+ manifestURL: policy && policy.getURL("manifest.json"),
+ name: this.addon.name,
+ temporarilyInstalled: this.addon.temporarilyInstalled,
+ traits: {},
+ url: this.addon.sourceURI ? this.addon.sourceURI.spec : undefined,
+ warnings: ExtensionParent.DebugUtils.getExtensionManifestWarnings(
+ this.addonId
+ ),
+ };
+ },
+
+ async getTarget() {
+ const form = await this._extensionFrameConnect();
+ // Merge into the child actor form, some addon metadata
+ // (e.g. the addon name shown in the addon debugger window title).
+ return Object.assign(form, {
+ iconURL: this.addon.iconURL,
+ id: this.addon.id,
+ // Set the isOOP attribute on the connected child actor form.
+ isOOP: this.isOOP,
+ name: this.addon.name,
+ });
+ },
+
+ getChildren() {
+ return [];
+ },
+
+ async _extensionFrameConnect() {
+ if (this._browser) {
+ throw new Error(
+ "This actor is already connected to the extension process"
+ );
+ }
+
+ this._browser = await ExtensionParent.DebugUtils.getExtensionProcessBrowser(
+ this
+ );
+
+ this._form = await connectToFrame(
+ this.conn,
+ this._browser,
+ this._extensionFrameDisconnect,
+ { addonId: this.addonId }
+ );
+
+ this._childActorID = this._form.actor;
+
+ // Exit the proxy child actor if the child actor has been destroyed.
+ this._mm.addMessageListener("debug:webext_child_exit", this._onChildExit);
+
+ return this._form;
+ },
+
+ /** WebExtension Actor Methods **/
+ async reload() {
+ await this.addon.reload();
+ return {};
+ },
+
+ // This function will be called from RootActor in case that the devtools client
+ // retrieves list of addons with `iconDataURL` option.
+ async loadIconDataURL() {
+ this._iconDataURL = await this.getIconDataURL();
+ },
+
+ async getIconDataURL() {
+ if (!this.addon.iconURL) {
+ return null;
+ }
+
+ const xhr = new XMLHttpRequest();
+ xhr.responseType = "blob";
+ xhr.open("GET", this.addon.iconURL, true);
+
+ if (this.addon.iconURL.toLowerCase().endsWith(".svg")) {
+ // Maybe SVG, thus force to change mime type.
+ xhr.overrideMimeType("image/svg+xml");
+ }
+
+ try {
+ const blob = await new Promise((resolve, reject) => {
+ xhr.onload = () => resolve(xhr.response);
+ xhr.onerror = reject;
+ xhr.send();
+ });
+
+ const reader = new FileReader();
+ return await new Promise((resolve, reject) => {
+ reader.onloadend = () => resolve(reader.result);
+ reader.onerror = reject;
+ reader.readAsDataURL(blob);
+ });
+ } catch (_) {
+ console.warn(`Failed to create data url from [${this.addon.iconURL}]`);
+ return null;
+ }
+ },
+
+ // TODO: check if we need this, as it is only used in a test
+ get isOOP() {
+ return this._browser ? this._browser.isRemoteBrowser : undefined;
+ },
+
+ // Private Methods
+ get _mm() {
+ return (
+ this._browser &&
+ (this._browser.messageManager ||
+ this._browser.frameLoader.messageManager)
+ );
+ },
+
+ _extensionFrameDisconnect() {
+ AddonManager.removeAddonListener(this);
+
+ this.addon = null;
+ if (this._mm) {
+ this._mm.removeMessageListener(
+ "debug:webext_child_exit",
+ this._onChildExit
+ );
+
+ this._mm.sendAsyncMessage("debug:webext_parent_exit", {
+ actor: this._childActorID,
+ });
+
+ ExtensionParent.DebugUtils.releaseExtensionProcessBrowser(this);
+ }
+
+ this._browser = null;
+ this._childActorID = null;
+ },
+
+ /**
+ * Handle the child actor exit.
+ */
+ _onChildExit(msg) {
+ if (msg.json.actor !== this._childActorID) {
+ return;
+ }
+
+ this._extensionFrameDisconnect();
+ },
+
+ // AddonManagerListener callbacks.
+ onInstalled(addon) {
+ if (addon.id != this.addonId) {
+ return;
+ }
+
+ // Update the AddonManager's addon object on reload/update.
+ this.addon = addon;
+ },
+
+ onUninstalled(addon) {
+ if (addon != this.addon) {
+ return;
+ }
+
+ this._extensionFrameDisconnect();
+ },
+
+ destroy() {
+ this._extensionFrameDisconnect();
+ protocol.Actor.prototype.destroy.call(this);
+ },
+ }
+);
+
+exports.WebExtensionDescriptorActor = WebExtensionDescriptorActor;
diff --git a/devtools/server/actors/descriptors/worker.js b/devtools/server/actors/descriptors/worker.js
new file mode 100644
index 0000000000..e1f3275b53
--- /dev/null
+++ b/devtools/server/actors/descriptors/worker.js
@@ -0,0 +1,253 @@
+/* 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";
+
+/*
+ * Target actor for any of the various kinds of workers.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const { Ci } = require("chrome");
+const ChromeUtils = require("ChromeUtils");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
+const protocol = require("devtools/shared/protocol");
+const {
+ workerDescriptorSpec,
+} = require("devtools/shared/specs/descriptors/worker");
+
+loader.lazyRequireGetter(this, "ChromeUtils");
+
+loader.lazyRequireGetter(
+ this,
+ "connectToWorker",
+ "devtools/server/connectors/worker-connector",
+ true
+);
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "swm",
+ "@mozilla.org/serviceworkers/manager;1",
+ "nsIServiceWorkerManager"
+);
+
+const WorkerDescriptorActor = protocol.ActorClassWithSpec(
+ workerDescriptorSpec,
+ {
+ initialize(conn, dbg) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this._dbg = dbg;
+ this._attached = false;
+ this._threadActor = null;
+ this._transport = null;
+
+ this._dbgListener = {
+ onClose: this._onWorkerClose.bind(this),
+ onError: this._onWorkerError.bind(this),
+ };
+ },
+
+ form() {
+ const form = {
+ actor: this.actorID,
+ consoleActor: this._consoleActor,
+ threadActor: this._threadActor,
+ id: this._dbg.id,
+ url: this._dbg.url,
+ traits: {},
+ type: this._dbg.type,
+ };
+ if (this._dbg.type === Ci.nsIWorkerDebugger.TYPE_SERVICE) {
+ /**
+ * With parent-intercept mode, the ServiceWorkerManager in content
+ * processes don't maintain ServiceWorkerRegistrations; record the
+ * ServiceWorker's ID, and this data will be merged with the
+ * corresponding registration in the parent process.
+ */
+ if (
+ !swm.isParentInterceptEnabled() ||
+ !DevToolsServer.isInChildProcess
+ ) {
+ const registration = this._getServiceWorkerRegistrationInfo();
+ form.scope = registration.scope;
+ const newestWorker =
+ registration.activeWorker ||
+ registration.waitingWorker ||
+ registration.installingWorker;
+ form.fetch = newestWorker?.handlesFetchEvents;
+ }
+ }
+ return form;
+ },
+
+ attach() {
+ if (this._dbg.isClosed) {
+ return { error: "closed" };
+ }
+
+ if (!this._attached) {
+ const isServiceWorker =
+ this._dbg.type == Ci.nsIWorkerDebugger.TYPE_SERVICE;
+ if (isServiceWorker) {
+ this._preventServiceWorkerShutdown();
+ }
+ this._dbg.addListener(this._dbgListener);
+ this._attached = true;
+ }
+
+ return {
+ type: "attached",
+ url: this._dbg.url,
+ };
+ },
+
+ detach() {
+ if (!this._attached) {
+ return { error: "wrongState" };
+ }
+
+ this._detach();
+
+ return { type: "detached" };
+ },
+
+ destroy() {
+ if (this._attached) {
+ this._detach();
+ }
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ async getTarget() {
+ if (!this._attached) {
+ return { error: "wrongState" };
+ }
+
+ if (this._threadActor !== null) {
+ return {
+ type: "connected",
+ threadActor: this._threadActor,
+ };
+ }
+
+ try {
+ const { transport, workerTargetForm } = await connectToWorker(
+ this.conn,
+ this._dbg,
+ this.actorID,
+ {}
+ );
+
+ this._threadActor = workerTargetForm.threadActor;
+ this._consoleActor = workerTargetForm.consoleActor;
+ this._transport = transport;
+
+ return {
+ type: "connected",
+ threadActor: this._threadActor,
+ consoleActor: this._consoleActor,
+ url: this._dbg.url,
+ };
+ } catch (error) {
+ return { error: error.toString() };
+ }
+ },
+
+ push() {
+ if (this._dbg.type !== Ci.nsIWorkerDebugger.TYPE_SERVICE) {
+ return { error: "wrongType" };
+ }
+ const registration = this._getServiceWorkerRegistrationInfo();
+ const originAttributes = ChromeUtils.originAttributesToSuffix(
+ this._dbg.principal.originAttributes
+ );
+ swm.sendPushEvent(originAttributes, registration.scope);
+ return { type: "pushed" };
+ },
+
+ _onWorkerClose() {
+ if (this._attached) {
+ this._detach();
+ }
+
+ this.conn.sendActorEvent(this.actorID, "close");
+ },
+
+ _onWorkerError(filename, lineno, message) {
+ reportError("ERROR:" + filename + ":" + lineno + ":" + message + "\n");
+ },
+
+ _getServiceWorkerRegistrationInfo() {
+ return swm.getRegistrationByPrincipal(this._dbg.principal, this._dbg.url);
+ },
+
+ _getServiceWorkerInfo() {
+ const registration = this._getServiceWorkerRegistrationInfo();
+ return registration.getWorkerByID(this._dbg.serviceWorkerID);
+ },
+
+ _detach() {
+ if (this._threadActor !== null) {
+ this._transport.close();
+ this._transport = null;
+ this._threadActor = null;
+ }
+
+ // If the worker is already destroyed, nsIWorkerDebugger.type throws
+ // (_dbg.closed appears to be false when it throws)
+ let type;
+ try {
+ type = this._dbg.type;
+ } catch (e) {
+ // nothing
+ }
+
+ const isServiceWorker = type == Ci.nsIWorkerDebugger.TYPE_SERVICE;
+ if (isServiceWorker) {
+ this._allowServiceWorkerShutdown();
+ }
+
+ this._dbg.removeListener(this._dbgListener);
+ this._attached = false;
+ },
+
+ /**
+ * Automatically disable the internal sw timeout that shut them down by calling
+ * nsIWorkerInfo.attachDebugger().
+ * This can be removed when Bug 1496997 lands.
+ */
+ _preventServiceWorkerShutdown() {
+ if (swm.isParentInterceptEnabled()) {
+ // In parentIntercept mode, the worker target actor cannot call attachDebugger
+ // because this API can only be called from the parent process. This will be
+ // done by the worker target front.
+ return;
+ }
+
+ const worker = this._getServiceWorkerInfo();
+ if (worker) {
+ worker.attachDebugger();
+ }
+ },
+
+ /**
+ * Allow the service worker to time out. See _preventServiceWorkerShutdown.
+ */
+ _allowServiceWorkerShutdown() {
+ if (swm.isParentInterceptEnabled()) {
+ return;
+ }
+
+ const worker = this._getServiceWorkerInfo();
+ if (worker) {
+ worker.detachDebugger();
+ }
+ },
+ }
+);
+
+exports.WorkerDescriptorActor = WorkerDescriptorActor;
diff --git a/devtools/server/actors/device.js b/devtools/server/actors/device.js
new file mode 100644
index 0000000000..50d30350aa
--- /dev/null
+++ b/devtools/server/actors/device.js
@@ -0,0 +1,83 @@
+/* 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";
+
+const { Ci, Cc } = require("chrome");
+const Services = require("Services");
+const protocol = require("devtools/shared/protocol");
+
+const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "swm",
+ "@mozilla.org/serviceworkers/manager;1",
+ "nsIServiceWorkerManager"
+);
+
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const { getSystemInfo } = require("devtools/shared/system");
+const { deviceSpec } = require("devtools/shared/specs/device");
+const { AppConstants } = require("resource://gre/modules/AppConstants.jsm");
+
+exports.DeviceActor = protocol.ActorClassWithSpec(deviceSpec, {
+ initialize: function(conn) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ // pageshow and pagehide event release wake lock, so we have to acquire
+ // wake lock again by pageshow event
+ this._onPageShow = this._onPageShow.bind(this);
+ if (this._window) {
+ this._window.addEventListener("pageshow", this._onPageShow, true);
+ }
+ this._acquireWakeLock();
+ },
+
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+ this._releaseWakeLock();
+ if (this._window) {
+ this._window.removeEventListener("pageshow", this._onPageShow, true);
+ }
+ },
+
+ getDescription: function() {
+ return Object.assign({}, getSystemInfo(), {
+ // ServiceWorker debugging is only supported when parent-intercept is
+ // enabled. This cannot change at runtime, so it can be treated as a
+ // constant for the device.
+ canDebugServiceWorkers: swm.isParentInterceptEnabled(),
+ });
+ },
+
+ _acquireWakeLock: function() {
+ if (AppConstants.platform !== "android") {
+ return;
+ }
+
+ const pm = Cc["@mozilla.org/power/powermanagerservice;1"].getService(
+ Ci.nsIPowerManagerService
+ );
+ this._wakelock = pm.newWakeLock("screen", this._window);
+ },
+
+ _releaseWakeLock: function() {
+ if (this._wakelock) {
+ try {
+ this._wakelock.unlock();
+ } catch (e) {
+ // Ignore error since wake lock is already unlocked
+ }
+ this._wakelock = null;
+ }
+ },
+
+ _onPageShow: function() {
+ this._releaseWakeLock();
+ this._acquireWakeLock();
+ },
+
+ get _window() {
+ return Services.wm.getMostRecentWindow(DevToolsServer.chromeWindowType);
+ },
+});
diff --git a/devtools/server/actors/emulation/content-viewer.js b/devtools/server/actors/emulation/content-viewer.js
new file mode 100644
index 0000000000..3bbc6eeead
--- /dev/null
+++ b/devtools/server/actors/emulation/content-viewer.js
@@ -0,0 +1,128 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const protocol = require("devtools/shared/protocol");
+const { contentViewerSpec } = require("devtools/shared/specs/content-viewer");
+
+/**
+ * This actor emulates various browser content environments by using methods available
+ * on the ContentViewer exposed by the platform.
+ */
+const ContentViewerActor = protocol.ActorClassWithSpec(contentViewerSpec, {
+ initialize(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ this.docShell = targetActor.docShell;
+
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+ this.onWindowReady = this.onWindowReady.bind(this);
+
+ this.targetActor.on("will-navigate", this.onWillNavigate);
+ this.targetActor.on("window-ready", this.onWindowReady);
+ },
+
+ destroy() {
+ this.stopPrintMediaSimulation();
+ this.setEmulatedColorScheme();
+
+ this.targetActor.off("will-navigate", this.onWillNavigate);
+ this.targetActor.off("window-ready", this.onWindowReady);
+
+ this.targetActor = null;
+ this.docShell = null;
+
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ onWillNavigate({ isTopLevel }) {
+ // Make sure that print simulation is stopped before navigating to another page. We
+ // need to do this since the browser will cache the last state of the page in its
+ // session history.
+ if (this._printSimulationEnabled && isTopLevel) {
+ this.stopPrintMediaSimulation(true);
+ }
+ },
+
+ onWindowReady({ isTopLevel }) {
+ // Since `emulateMedium` only works for the current page, we need to ensure persistent
+ // print simulation for when the user navigates to a new page while its enabled.
+ // To do this, we need to tell the page to begin print simulation before the DOM
+ // content is available to the user:
+ if (this._printSimulationEnabled && isTopLevel) {
+ this.startPrintMediaSimulation();
+ }
+ },
+
+ /* Color scheme simulation */
+
+ /**
+ * Returns the currently emulated color scheme.
+ */
+ getEmulatedColorScheme() {
+ return this._emulatedColorScheme;
+ },
+
+ /**
+ * Sets the currently emulated color scheme or if an invalid value is given,
+ * the override is cleared.
+ */
+ setEmulatedColorScheme(scheme = null) {
+ if (this._emulatedColorScheme === scheme) {
+ return;
+ }
+
+ let internalColorScheme;
+ switch (scheme) {
+ case "light":
+ internalColorScheme = Ci.nsIContentViewer.PREFERS_COLOR_SCHEME_LIGHT;
+ break;
+ case "dark":
+ internalColorScheme = Ci.nsIContentViewer.PREFERS_COLOR_SCHEME_DARK;
+ break;
+ default:
+ internalColorScheme = Ci.nsIContentViewer.PREFERS_COLOR_SCHEME_NONE;
+ }
+
+ this._emulatedColorScheme = scheme;
+ this.docShell.contentViewer.emulatePrefersColorScheme(internalColorScheme);
+ },
+
+ // The current emulated color scheme value. It's possible values are listed in the
+ // COLOR_SCHEMES constant in devtools/client/inspector/rules/constants.
+ _emulatedColorScheme: null,
+
+ /* Simulating print media for the page */
+
+ _printSimulationEnabled: false,
+
+ getIsPrintSimulationEnabled() {
+ return this._printSimulationEnabled;
+ },
+
+ async startPrintMediaSimulation() {
+ this._printSimulationEnabled = true;
+ this.targetActor.docShell.contentViewer.emulateMedium("print");
+ },
+
+ /**
+ * Stop simulating print media for the current page.
+ *
+ * @param {Boolean} state
+ * Whether or not to set _printSimulationEnabled to false. If true, we want to
+ * stop simulation print media for the current page but NOT set
+ * _printSimulationEnabled to false. We do this specifically for the
+ * "will-navigate" event where we still want to continue simulating print when
+ * navigating to the next page. Defaults to false, meaning we want to completely
+ * stop print simulation.
+ */
+ async stopPrintMediaSimulation(state = false) {
+ this._printSimulationEnabled = state;
+ this.targetActor.docShell.contentViewer.stopEmulatingMedium();
+ },
+});
+
+exports.ContentViewerActor = ContentViewerActor;
diff --git a/devtools/server/actors/emulation/moz.build b/devtools/server/actors/emulation/moz.build
new file mode 100644
index 0000000000..2ab4b0f676
--- /dev/null
+++ b/devtools/server/actors/emulation/moz.build
@@ -0,0 +1,11 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "content-viewer.js",
+ "responsive.js",
+ "touch-simulator.js",
+)
diff --git a/devtools/server/actors/emulation/responsive.js b/devtools/server/actors/emulation/responsive.js
new file mode 100644
index 0000000000..8e688ec760
--- /dev/null
+++ b/devtools/server/actors/emulation/responsive.js
@@ -0,0 +1,424 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const Services = require("Services");
+const protocol = require("devtools/shared/protocol");
+const { responsiveSpec } = require("devtools/shared/specs/responsive");
+
+loader.lazyRequireGetter(
+ this,
+ "ScreenshotActor",
+ "devtools/server/actors/screenshot",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "TouchSimulator",
+ "devtools/server/actors/emulation/touch-simulator",
+ true
+);
+
+const FLOATING_SCROLLBARS_SHEET = Services.io.newURI(
+ "chrome://devtools/skin/floating-scrollbars-responsive-design.css"
+);
+
+/**
+ * This actor overrides various browser features to simulate different environments to
+ * test how pages perform under various conditions.
+ *
+ * The design below, which saves the previous value of each property before setting, is
+ * needed because it's possible to have multiple copies of this actor for a single page.
+ * When some instance of this actor changes a property, we want it to be able to restore
+ * that property to the way it was found before the change.
+ *
+ * A subtle aspect of the code below is that all get* methods must return non-undefined
+ * values, so that the absence of a previous value can be distinguished from the value for
+ * "no override" for each of the properties.
+ */
+const ResponsiveActor = protocol.ActorClassWithSpec(responsiveSpec, {
+ initialize(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ this.docShell = targetActor.docShell;
+
+ this.onWindowReady = this.onWindowReady.bind(this);
+
+ this.targetActor.on("window-ready", this.onWindowReady);
+ },
+
+ destroy() {
+ this.clearDPPXOverride();
+ this.clearNetworkThrottling();
+ this.clearTouchEventsOverride();
+ this.clearMetaViewportOverride();
+ this.clearUserAgentOverride();
+
+ this.targetActor.off("window-ready", this.onWindowReady);
+
+ this.targetActor = null;
+ this.docShell = null;
+ this._screenshotActor = null;
+ this._touchSimulator = null;
+
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ async onWindowReady() {
+ await this.setFloatingScrollbars(true);
+ },
+
+ /**
+ * Retrieve the console actor for this tab. This allows us to expose network throttling
+ * as part of emulation settings, even though it's internally connected to the network
+ * monitor, which for historical reasons is part of the console actor.
+ */
+ get _consoleActor() {
+ if (this.targetActor.exited || this.targetActor.isDestroyed()) {
+ return null;
+ }
+ const form = this.targetActor.form();
+ return this.conn._getOrCreateActor(form.consoleActor);
+ },
+
+ get screenshotActor() {
+ if (!this._screenshotActor) {
+ this._screenshotActor = new ScreenshotActor(this.conn, this.targetActor);
+ this.manage(this._screenshotActor);
+ }
+
+ return this._screenshotActor;
+ },
+
+ get touchSimulator() {
+ if (!this._touchSimulator) {
+ this._touchSimulator = new TouchSimulator(
+ this.targetActor.chromeEventHandler
+ );
+ }
+
+ return this._touchSimulator;
+ },
+
+ get win() {
+ return this.docShell.chromeEventHandler.ownerGlobal;
+ },
+
+ /* DPPX override */
+
+ _previousDPPXOverride: undefined,
+
+ setDPPXOverride(dppx) {
+ if (this.getDPPXOverride() === dppx) {
+ return false;
+ }
+
+ if (this._previousDPPXOverride === undefined) {
+ this._previousDPPXOverride = this.getDPPXOverride();
+ }
+
+ this.docShell.contentViewer.overrideDPPX = dppx;
+
+ return true;
+ },
+
+ getDPPXOverride() {
+ return this.docShell.contentViewer.overrideDPPX;
+ },
+
+ clearDPPXOverride() {
+ if (this._previousDPPXOverride !== undefined) {
+ return this.setDPPXOverride(this._previousDPPXOverride);
+ }
+
+ return false;
+ },
+
+ /* Network Throttling */
+
+ _previousNetworkThrottling: undefined,
+
+ /**
+ * Transform the RDP format into the internal format and then set network throttling.
+ */
+ setNetworkThrottling({ downloadThroughput, uploadThroughput, latency }) {
+ const throttleData = {
+ latencyMean: latency,
+ latencyMax: latency,
+ downloadBPSMean: downloadThroughput,
+ downloadBPSMax: downloadThroughput,
+ uploadBPSMean: uploadThroughput,
+ uploadBPSMax: uploadThroughput,
+ };
+ return this._setNetworkThrottling(throttleData);
+ },
+
+ _setNetworkThrottling(throttleData) {
+ const current = this._getNetworkThrottling();
+ // Check if they are both objects or both null
+ let match = throttleData == current;
+ // If both objects, check all entries
+ if (match && current && throttleData) {
+ match = Object.entries(current).every(([k, v]) => {
+ return throttleData[k] === v;
+ });
+ }
+ if (match) {
+ return false;
+ }
+
+ if (this._previousNetworkThrottling === undefined) {
+ this._previousNetworkThrottling = current;
+ }
+
+ const consoleActor = this._consoleActor;
+ if (!consoleActor) {
+ return false;
+ }
+ consoleActor.startListeners(["NetworkActivity"]);
+ consoleActor.setPreferences({
+ "NetworkMonitor.throttleData": throttleData,
+ });
+ return true;
+ },
+
+ /**
+ * Get network throttling and then transform the internal format into the RDP format.
+ */
+ getNetworkThrottling() {
+ const throttleData = this._getNetworkThrottling();
+ if (!throttleData) {
+ return null;
+ }
+ const { downloadBPSMax, uploadBPSMax, latencyMax } = throttleData;
+ return {
+ downloadThroughput: downloadBPSMax,
+ uploadThroughput: uploadBPSMax,
+ latency: latencyMax,
+ };
+ },
+
+ _getNetworkThrottling() {
+ const consoleActor = this._consoleActor;
+ if (!consoleActor) {
+ return null;
+ }
+ const prefs = consoleActor.getPreferences(["NetworkMonitor.throttleData"]);
+ return prefs.preferences["NetworkMonitor.throttleData"] || null;
+ },
+
+ clearNetworkThrottling() {
+ if (this._previousNetworkThrottling !== undefined) {
+ return this._setNetworkThrottling(this._previousNetworkThrottling);
+ }
+
+ return false;
+ },
+
+ /* Touch events override */
+
+ _previousTouchEventsOverride: undefined,
+
+ /**
+ * Set the current element picker state.
+ *
+ * True means the element picker is currently active and we should not be emulating
+ * touch events.
+ * False means the element picker is not active and it is ok to emulate touch events.
+ *
+ * This actor method is meant to be called by the DevTools front-end. The reason for
+ * this is the following:
+ * RDM is the only current consumer of the touch simulator. RDM instantiates this actor
+ * on its own, whether or not the Toolbox is opened. That means it does so in its own
+ * DevTools Server instance.
+ * When the Toolbox is running, it uses a different DevToolsServer. Therefore, it is not
+ * possible for the touch simulator to know whether the picker is active or not. This
+ * state has to be sent by the client code of the Toolbox to this actor.
+ * If a future use case arises where we want to use the touch simulator from the Toolbox
+ * too, then we could add code in here to detect the picker mode as described in
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=1409085#c3
+
+ * @param {Boolean} state
+ * @param {String} pickerType
+ */
+ setElementPickerState(state, pickerType) {
+ this.touchSimulator.setElementPickerState(state, pickerType);
+ },
+
+ setTouchEventsOverride(flag) {
+ if (this.getTouchEventsOverride() == flag) {
+ return false;
+ }
+ if (this._previousTouchEventsOverride === undefined) {
+ this._previousTouchEventsOverride = this.getTouchEventsOverride();
+ }
+
+ // Start or stop the touch simulator depending on the override flag
+ // See BrowsingContext.webidl `TouchEventsOverride` enum for values.
+ if (flag == "enabled") {
+ this.touchSimulator.start();
+ } else {
+ this.touchSimulator.stop();
+ }
+
+ this.docShell.browsingContext.touchEventsOverride = flag;
+ return true;
+ },
+
+ getTouchEventsOverride() {
+ return this.docShell.browsingContext.touchEventsOverride;
+ },
+
+ clearTouchEventsOverride() {
+ if (this._previousTouchEventsOverride !== undefined) {
+ return this.setTouchEventsOverride(this._previousTouchEventsOverride);
+ }
+ return false;
+ },
+
+ /* Meta viewport override */
+
+ _previousMetaViewportOverride: undefined,
+
+ setMetaViewportOverride(flag) {
+ if (this.getMetaViewportOverride() == flag) {
+ return false;
+ }
+ if (this._previousMetaViewportOverride === undefined) {
+ this._previousMetaViewportOverride = this.getMetaViewportOverride();
+ }
+
+ this.docShell.metaViewportOverride = flag;
+ return true;
+ },
+
+ getMetaViewportOverride() {
+ return this.docShell.metaViewportOverride;
+ },
+
+ clearMetaViewportOverride() {
+ if (this._previousMetaViewportOverride !== undefined) {
+ return this.setMetaViewportOverride(this._previousMetaViewportOverride);
+ }
+ return false;
+ },
+
+ /* User agent override */
+
+ _previousUserAgentOverride: undefined,
+
+ setUserAgentOverride(userAgent) {
+ if (this.getUserAgentOverride() == userAgent) {
+ return false;
+ }
+ if (this._previousUserAgentOverride === undefined) {
+ this._previousUserAgentOverride = this.getUserAgentOverride();
+ }
+ // Bug 1637494: TODO - customUserAgent should only be set from parent
+ // process.
+ this.docShell.customUserAgent = userAgent;
+ return true;
+ },
+
+ getUserAgentOverride() {
+ return this.docShell.browsingContext.customUserAgent;
+ },
+
+ clearUserAgentOverride() {
+ if (this._previousUserAgentOverride !== undefined) {
+ return this.setUserAgentOverride(this._previousUserAgentOverride);
+ }
+ return false;
+ },
+
+ setScreenOrientation(type, angle) {
+ if (
+ this.win.screen.orientation.angle !== angle ||
+ this.win.screen.orientation.type !== type
+ ) {
+ this.docShell.browsingContext.setRDMPaneOrientation(type, angle);
+ }
+ },
+
+ /**
+ * Simulates the "orientationchange" event when device screen is rotated.
+ *
+ * @param {String} type
+ * The orientation type of the rotated device.
+ * @param {Number} angle
+ * The rotated angle of the device.
+ * @param {Boolean} isViewportRotated
+ * Whether or not screen orientation change is a result of rotating the viewport.
+ * If true, then dispatch the "orientationchange" event on the content window.
+ */
+ async simulateScreenOrientationChange(
+ type,
+ angle,
+ isViewportRotated = false
+ ) {
+ // Don't dispatch the "orientationchange" event if orientation change is a result
+ // of switching to a new device, location change, or opening RDM.
+ if (!isViewportRotated) {
+ this.setScreenOrientation(type, angle);
+ return;
+ }
+
+ const { CustomEvent } = this.win;
+ const orientationChangeEvent = new CustomEvent("orientationchange");
+
+ this.setScreenOrientation(type, angle);
+ this.win.dispatchEvent(orientationChangeEvent);
+ },
+
+ async captureScreenshot() {
+ return this.screenshotActor.capture({});
+ },
+
+ /**
+ * Applies a mobile scrollbar overlay to the content document.
+ *
+ * @param {Boolean} applyFloatingScrollbars
+ */
+ async setFloatingScrollbars(applyFloatingScrollbars) {
+ const docShell = this.docShell;
+ const allDocShells = [docShell];
+
+ for (let i = 0; i < docShell.childCount; i++) {
+ const child = docShell.getChildAt(i).QueryInterface(Ci.nsIDocShell);
+ allDocShells.push(child);
+ }
+
+ for (const d of allDocShells) {
+ const win = d.contentViewer.DOMDocument.defaultView;
+ const winUtils = win.windowUtils;
+ try {
+ if (applyFloatingScrollbars) {
+ winUtils.loadSheet(FLOATING_SCROLLBARS_SHEET, this.win.AGENT_SHEET);
+ } else {
+ winUtils.removeSheet(FLOATING_SCROLLBARS_SHEET, this.win.AGENT_SHEET);
+ }
+ } catch (e) {}
+ }
+
+ this.flushStyle();
+ },
+
+ async setMaxTouchPoints(touchSimulationEnabled) {
+ const maxTouchPoints = touchSimulationEnabled ? 1 : 0;
+ this.docShell.browsingContext.setRDMPaneMaxTouchPoints(maxTouchPoints);
+ },
+
+ flushStyle() {
+ // Force presContext destruction
+ const isSticky = this.docShell.contentViewer.sticky;
+ this.docShell.contentViewer.sticky = false;
+ this.docShell.contentViewer.hide();
+ this.docShell.contentViewer.show();
+ this.docShell.contentViewer.sticky = isSticky;
+ },
+});
+
+exports.ResponsiveActor = ResponsiveActor;
diff --git a/devtools/server/actors/emulation/touch-simulator.js b/devtools/server/actors/emulation/touch-simulator.js
new file mode 100644
index 0000000000..dbbc5adb17
--- /dev/null
+++ b/devtools/server/actors/emulation/touch-simulator.js
@@ -0,0 +1,426 @@
+/* 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";
+
+const { Services } = require("resource://gre/modules/Services.jsm");
+
+loader.lazyRequireGetter(this, "InspectorUtils", "InspectorUtils");
+loader.lazyRequireGetter(
+ this,
+ "PICKER_TYPES",
+ "devtools/shared/picker-constants"
+);
+
+var systemAppOrigin = (function() {
+ let systemOrigin = "_";
+ try {
+ systemOrigin = Services.io.newURI(
+ Services.prefs.getCharPref("b2g.system_manifest_url")
+ ).prePath;
+ } catch (e) {
+ // Fall back to default value
+ }
+ return systemOrigin;
+})();
+
+var isClickHoldEnabled = Services.prefs.getBoolPref(
+ "ui.click_hold_context_menus"
+);
+var clickHoldDelay = Services.prefs.getIntPref(
+ "ui.click_hold_context_menus.delay",
+ 500
+);
+
+// Touch state constants are derived from values defined in: nsIDOMWindowUtils.idl
+const TOUCH_CONTACT = 0x02;
+const TOUCH_REMOVE = 0x04;
+
+const TOUCH_STATES = {
+ touchstart: TOUCH_CONTACT,
+ touchmove: TOUCH_CONTACT,
+ touchend: TOUCH_REMOVE,
+};
+
+const kStateHover = 0x00000004; // NS_EVENT_STATE_HOVER
+
+function TouchSimulator(simulatorTarget) {
+ this.simulatorTarget = simulatorTarget;
+ this._currentPickerMap = new Map();
+}
+
+/**
+ * Simulate touch events for platforms where they aren't generally available.
+ */
+TouchSimulator.prototype = {
+ events: [
+ "mousedown",
+ "mousemove",
+ "mouseup",
+ "touchstart",
+ "touchend",
+ "mouseenter",
+ "mouseover",
+ "mouseout",
+ "mouseleave",
+ ],
+
+ contextMenuTimeout: null,
+
+ simulatorTarget: null,
+
+ enabled: false,
+
+ start() {
+ if (this.enabled) {
+ // Simulator is already started
+ return;
+ }
+
+ this.events.forEach(evt => {
+ // Only listen trusted events to prevent messing with
+ // event dispatched manually within content documents
+ this.simulatorTarget.addEventListener(evt, this, true, false);
+ });
+
+ this.enabled = true;
+ },
+
+ stop() {
+ if (!this.enabled) {
+ // Simulator isn't running
+ return;
+ }
+ this.events.forEach(evt => {
+ this.simulatorTarget.removeEventListener(evt, this, true);
+ });
+ this.enabled = false;
+ },
+
+ _isPicking() {
+ const types = Object.values(PICKER_TYPES);
+ return types.some(type => this._currentPickerMap.get(type));
+ },
+
+ /**
+ * Set the state value for one of DevTools pickers (either eyedropper or
+ * element picker).
+ * If any content picker is currently active, we should not be emulating
+ * touch events. Otherwise it is ok to emulate touch events.
+ * In theory only one picker can ever be active at a time, but tracking the
+ * different pickers independantly avoids race issues in the client code.
+ *
+ * @param {Boolean} state
+ * True if the picker is currently active, false otherwise.
+ * @param {String} pickerType
+ * One of PICKER_TYPES.
+ */
+ setElementPickerState(state, pickerType) {
+ if (!Object.values(PICKER_TYPES).includes(pickerType)) {
+ throw new Error(
+ "Unsupported type in setElementPickerState: " + pickerType
+ );
+ }
+ this._currentPickerMap.set(pickerType, state);
+ },
+
+ // eslint-disable-next-line complexity
+ handleEvent(evt) {
+ // Bail out if devtools is in pick mode in the same tab.
+ if (this._isPicking()) {
+ return;
+ }
+
+ // The gaia system window use an hybrid system even on the device which is
+ // a mix of mouse/touch events. So let's not cancel *all* mouse events
+ // if it is the current target.
+ const content = this.getContent(evt.target);
+ if (!content) {
+ return;
+ }
+ const isSystemWindow = content.location
+ .toString()
+ .startsWith(systemAppOrigin);
+
+ // App touchstart & touchend should also be dispatched on the system app
+ // to match on-device behavior.
+ if (evt.type.startsWith("touch") && !isSystemWindow) {
+ const sysFrame = content.realFrameElement;
+ if (!sysFrame) {
+ return;
+ }
+ const sysDocument = sysFrame.ownerDocument;
+ const sysWindow = sysDocument.defaultView;
+
+ const touchEvent = sysDocument.createEvent("touchevent");
+ const touch = evt.touches[0] || evt.changedTouches[0];
+ const point = sysDocument.createTouch(
+ sysWindow,
+ sysFrame,
+ 0,
+ touch.pageX,
+ touch.pageY,
+ touch.screenX,
+ touch.screenY,
+ touch.clientX,
+ touch.clientY,
+ 1,
+ 1,
+ 0,
+ 0
+ );
+
+ const touches = sysDocument.createTouchList(point);
+ const targetTouches = touches;
+ const changedTouches = touches;
+ touchEvent.initTouchEvent(
+ evt.type,
+ true,
+ true,
+ sysWindow,
+ 0,
+ false,
+ false,
+ false,
+ false,
+ touches,
+ targetTouches,
+ changedTouches
+ );
+ sysFrame.dispatchEvent(touchEvent);
+ return;
+ }
+
+ // Ignore all but real mouse event coming from physical mouse
+ // (especially ignore mouse event being dispatched from a touch event)
+ if (
+ evt.button ||
+ evt.mozInputSource != evt.MOZ_SOURCE_MOUSE ||
+ evt.isSynthesized
+ ) {
+ return;
+ }
+
+ const eventTarget = this.target;
+ let type = "";
+ switch (evt.type) {
+ case "mouseenter":
+ case "mouseover":
+ case "mouseout":
+ case "mouseleave":
+ // Don't propagate events which are not related to touch events
+ evt.stopPropagation();
+ evt.preventDefault();
+
+ // We don't want to trigger any visual changes to elements whose content can
+ // be modified via hover states. We can avoid this by removing the element's
+ // content state.
+ InspectorUtils.removeContentState(evt.target, kStateHover);
+ break;
+
+ case "mousedown":
+ this.target = evt.target;
+
+ // If the click-hold feature is enabled, start a timeout to convert long clicks
+ // into contextmenu events.
+ // Just don't do it if the event occurred on a scrollbar.
+ if (isClickHoldEnabled && !evt.originalTarget.closest("scrollbar")) {
+ this.contextMenuTimeout = this.sendContextMenu(evt);
+ }
+
+ this.startX = evt.pageX;
+ this.startY = evt.pageY;
+
+ // Capture events so if a different window show up the events
+ // won't be dispatched to something else.
+ evt.target.setCapture(false);
+
+ type = "touchstart";
+ break;
+
+ case "mousemove":
+ if (!eventTarget) {
+ // Don't propagate mousemove event when touchstart event isn't fired
+ evt.stopPropagation();
+ return;
+ }
+
+ type = "touchmove";
+ break;
+
+ case "mouseup":
+ if (!eventTarget) {
+ return;
+ }
+ this.target = null;
+
+ content.clearTimeout(this.contextMenuTimeout);
+ type = "touchend";
+
+ // Only register click listener after mouseup to ensure
+ // catching only real user click. (Especially ignore click
+ // being dispatched on form submit)
+ if (evt.detail == 1) {
+ this.simulatorTarget.addEventListener("click", this, {
+ capture: true,
+ once: true,
+ });
+ }
+ break;
+ }
+
+ const target = eventTarget || this.target;
+ if (target && type) {
+ this.synthesizeNativeTouch(
+ this.getContent(evt.target),
+ evt.clientX,
+ evt.clientY,
+ evt.screenX,
+ evt.screenY,
+ type
+ );
+ }
+
+ if (!isSystemWindow) {
+ evt.preventDefault();
+ evt.stopImmediatePropagation();
+ }
+ },
+
+ sendContextMenu({ target, clientX, clientY, screenX, screenY }) {
+ const view = target.ownerGlobal;
+ const { MouseEvent } = view;
+ const evt = new MouseEvent("contextmenu", {
+ bubbles: true,
+ cancelable: true,
+ view,
+ screenX,
+ screenY,
+ clientX,
+ clientY,
+ });
+ const content = this.getContent(target);
+ const timeout = content.setTimeout(() => {
+ target.dispatchEvent(evt);
+ }, clickHoldDelay);
+
+ return timeout;
+ },
+
+ /**
+ * Synthesizes a native touch action on a given target element. The `x` and `y` values
+ * passed to this function should be relative to the layout viewport (what is returned
+ * by `MouseEvent.clientX/clientY`) and are reported in CSS pixels.
+ *
+ * @param {Window} win
+ * The target window.
+ * @param {Number} x
+ * The `x` CSS coordinate relative to the layout viewport.
+ * @param {Number} y
+ * The `y` CSS coordinate relative to the layout viewport.
+ * @param {Number} screenX
+ * The `x` screen coordinate relative to the screen origin.
+ * @param {Number} screenY
+ * The `y` screen coordinate relative to the screen origin.
+ * @param {String} type
+ * A key appearing in the TOUCH_STATES associative array.
+ */
+ synthesizeNativeTouch(win, x, y, screenX, screenY, type) {
+ // Native events work in device pixels, so calculate device coordinates from
+ // the screen coordinates.
+ const utils = win.windowUtils;
+ const deviceScale = utils.screenPixelsPerCSSPixelNoOverride;
+ const pt = { x: screenX * deviceScale, y: screenY * deviceScale };
+
+ utils.sendNativeTouchPoint(0, TOUCH_STATES[type], pt.x, pt.y, 1, 90, null);
+ return true;
+ },
+
+ sendTouchEvent(evt, target, name) {
+ const win = target.ownerGlobal;
+ const content = this.getContent(target);
+ if (!content) {
+ return;
+ }
+
+ // To avoid duplicating logic for creating and dispatching touch events on the JS
+ // side, we should use what's already implemented for WindowUtils.sendTouchEvent.
+ const utils = win.windowUtils;
+ utils.sendTouchEvent(
+ name,
+ [0],
+ [evt.clientX],
+ [evt.clientY],
+ [1],
+ [1],
+ [0],
+ [1],
+ 0,
+ false
+ );
+ },
+
+ getContent(target) {
+ const win = target?.ownerDocument ? target.ownerGlobal : null;
+ return win;
+ },
+
+ getDelayBeforeMouseEvent(evt) {
+ // On mobile platforms, Firefox inserts a 300ms delay between
+ // touch events and accompanying mouse events, except if the
+ // content window is not zoomable and the content window is
+ // auto-zoomed to device-width.
+
+ // If the preference dom.meta-viewport.enabled is set to false,
+ // we couldn't read viewport's information from getViewportInfo().
+ // So we always simulate 300ms delay when the
+ // dom.meta-viewport.enabled is false.
+ const savedMetaViewportEnabled = Services.prefs.getBoolPref(
+ "dom.meta-viewport.enabled"
+ );
+ if (!savedMetaViewportEnabled) {
+ return 300;
+ }
+
+ const content = this.getContent(evt.target);
+ if (!content) {
+ return 0;
+ }
+
+ const utils = content.windowUtils;
+
+ const allowZoom = {};
+ const minZoom = {};
+ const maxZoom = {};
+ const autoSize = {};
+
+ utils.getViewportInfo(
+ content.innerWidth,
+ content.innerHeight,
+ {},
+ allowZoom,
+ minZoom,
+ maxZoom,
+ {},
+ {},
+ autoSize
+ );
+
+ // FIXME: On Safari and Chrome mobile platform, if the css property
+ // touch-action set to none or manipulation would also suppress 300ms
+ // delay. But Firefox didn't support this property now, we can't get
+ // this value from utils.getVisitedDependentComputedStyle() to check
+ // if we should suppress 300ms delay.
+ if (
+ !allowZoom.value || // user-scalable = no
+ minZoom.value === maxZoom.value || // minimum-scale = maximum-scale
+ autoSize.value // width = device-width
+ ) {
+ return 0;
+ }
+ return 300;
+ },
+};
+
+exports.TouchSimulator = TouchSimulator;
diff --git a/devtools/server/actors/environment.js b/devtools/server/actors/environment.js
new file mode 100644
index 0000000000..aa5ad1f2bc
--- /dev/null
+++ b/devtools/server/actors/environment.js
@@ -0,0 +1,201 @@
+/* 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";
+
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { createValueGrip } = require("devtools/server/actors/object/utils");
+const { environmentSpec } = require("devtools/shared/specs/environment");
+
+/**
+ * Creates an EnvironmentActor. EnvironmentActors are responsible for listing
+ * the bindings introduced by a lexical environment and assigning new values to
+ * those identifier bindings.
+ *
+ * @param Debugger.Environment aEnvironment
+ * The lexical environment that will be used to create the actor.
+ * @param ThreadActor aThreadActor
+ * The parent thread actor that contains this environment.
+ */
+const EnvironmentActor = ActorClassWithSpec(environmentSpec, {
+ initialize: function(environment, threadActor) {
+ Actor.prototype.initialize.call(this, threadActor.conn);
+
+ this.obj = environment;
+ this.threadActor = threadActor;
+ },
+
+ /**
+ * When the Environment Actor is destroyed it removes the
+ * Debugger.Environment.actor field so that environment does not
+ * reference a destroyed actor.
+ */
+ destroy: function() {
+ this.obj.actor = null;
+ Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Return an environment form for use in a protocol message.
+ */
+ form: function() {
+ const form = { actor: this.actorID };
+
+ // What is this environment's type?
+ if (this.obj.type == "declarative") {
+ form.type = this.obj.calleeScript ? "function" : "block";
+ } else {
+ form.type = this.obj.type;
+ }
+
+ form.scopeKind = this.obj.scopeKind;
+
+ // Does this environment have a parent?
+ if (this.obj.parent) {
+ form.parent = this.threadActor
+ .createEnvironmentActor(this.obj.parent, this.getParent())
+ .form();
+ }
+
+ // Does this environment reflect the properties of an object as variables?
+ if (this.obj.type == "object" || this.obj.type == "with") {
+ form.object = createValueGrip(
+ this.obj.object,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ }
+
+ // Is this the environment created for a function call?
+ if (this.obj.calleeScript) {
+ // Client only uses "displayName" for "function".
+ // Create a fake object actor containing only "displayName" as replacement
+ // for the no longer available obj.callee (see bug 1663847).
+ // See bug 1664218 for cleanup.
+ form.function = { displayName: this.obj.calleeScript.displayName };
+ }
+
+ // Shall we list this environment's bindings?
+ if (this.obj.type == "declarative") {
+ form.bindings = this.bindings();
+ }
+
+ return form;
+ },
+
+ /**
+ * Handle a protocol request to fully enumerate the bindings introduced by the
+ * lexical environment.
+ */
+ bindings: function() {
+ const bindings = { arguments: [], variables: {} };
+
+ // TODO: this part should be removed in favor of the commented-out part
+ // below when getVariableDescriptor lands (bug 725815).
+ if (typeof this.obj.getVariable != "function") {
+ // if (typeof this.obj.getVariableDescriptor != "function") {
+ return bindings;
+ }
+
+ let parameterNames;
+ if (this.obj.calleeScript) {
+ parameterNames = this.obj.calleeScript.parameterNames;
+ } else {
+ parameterNames = [];
+ }
+ for (const name of parameterNames) {
+ const arg = {};
+ const value = this.obj.getVariable(name);
+
+ // TODO: this part should be removed in favor of the commented-out part
+ // below when getVariableDescriptor lands (bug 725815).
+ const desc = {
+ value: value,
+ configurable: false,
+ writable: !value?.optimizedOut,
+ enumerable: true,
+ };
+
+ // let desc = this.obj.getVariableDescriptor(name);
+ const descForm = {
+ enumerable: true,
+ configurable: desc.configurable,
+ };
+ if ("value" in desc) {
+ descForm.value = createValueGrip(
+ desc.value,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ descForm.writable = desc.writable;
+ } else {
+ descForm.get = createValueGrip(
+ desc.get,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ descForm.set = createValueGrip(
+ desc.set,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ }
+ arg[name] = descForm;
+ bindings.arguments.push(arg);
+ }
+
+ for (const name of this.obj.names()) {
+ if (
+ bindings.arguments.some(function exists(element) {
+ return !!element[name];
+ })
+ ) {
+ continue;
+ }
+
+ const value = this.obj.getVariable(name);
+
+ // TODO: this part should be removed in favor of the commented-out part
+ // below when getVariableDescriptor lands.
+ const desc = {
+ value: value,
+ configurable: false,
+ writable: !(
+ value &&
+ (value.optimizedOut || value.uninitialized || value.missingArguments)
+ ),
+ enumerable: true,
+ };
+
+ // let desc = this.obj.getVariableDescriptor(name);
+ const descForm = {
+ enumerable: true,
+ configurable: desc.configurable,
+ };
+ if ("value" in desc) {
+ descForm.value = createValueGrip(
+ desc.value,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ descForm.writable = desc.writable;
+ } else {
+ descForm.get = createValueGrip(
+ desc.get || undefined,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ descForm.set = createValueGrip(
+ desc.set || undefined,
+ this.getParent(),
+ this.threadActor.objectGrip
+ );
+ }
+ bindings.variables[name] = descForm;
+ }
+
+ return bindings;
+ },
+});
+
+exports.EnvironmentActor = EnvironmentActor;
diff --git a/devtools/server/actors/errordocs.js b/devtools/server/actors/errordocs.js
new file mode 100644
index 0000000000..17823b1f93
--- /dev/null
+++ b/devtools/server/actors/errordocs.js
@@ -0,0 +1,205 @@
+/* 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/. */
+
+/**
+ * A mapping of error message names to external documentation. Any error message
+ * included here will be displayed alongside its link in the web console.
+ */
+
+"use strict";
+
+// Worker contexts do not support Services; in that case we have to rely
+// on the support URL redirection.
+const Services = require("Services");
+const supportBaseURL = !isWorker
+ ? Services.urlFormatter.formatURLPref("app.support.baseURL")
+ : "https://support.mozilla.org/kb/";
+
+const baseErrorURL =
+ "https://developer.mozilla.org/docs/Web/JavaScript/Reference/Errors/";
+const params =
+ "?utm_source=mozilla&utm_medium=firefox-console-errors&utm_campaign=default";
+
+const ErrorDocs = {
+ JSMSG_READ_ONLY: "Read-only",
+ JSMSG_BAD_ARRAY_LENGTH: "Invalid_array_length",
+ JSMSG_NEGATIVE_REPETITION_COUNT: "Negative_repetition_count",
+ JSMSG_RESULTING_STRING_TOO_LARGE: "Resulting_string_too_large",
+ JSMSG_BAD_RADIX: "Bad_radix",
+ JSMSG_PRECISION_RANGE: "Precision_range",
+ JSMSG_STMT_AFTER_RETURN: "Stmt_after_return",
+ JSMSG_NOT_A_CODEPOINT: "Not_a_codepoint",
+ JSMSG_BAD_SORT_ARG: "Array_sort_argument",
+ JSMSG_UNEXPECTED_TYPE: "Unexpected_type",
+ JSMSG_NOT_DEFINED: "Not_defined",
+ JSMSG_NOT_FUNCTION: "Not_a_function",
+ JSMSG_EQUAL_AS_ASSIGN: "Equal_as_assign",
+ JSMSG_UNDEFINED_PROP: "Undefined_prop",
+ JSMSG_DEPRECATED_PRAGMA: "Deprecated_source_map_pragma",
+ JSMSG_DEPRECATED_USAGE: "Deprecated_caller_or_arguments_usage",
+ JSMSG_CANT_DELETE: "Cant_delete",
+ JSMSG_VAR_HIDES_ARG: "Var_hides_argument",
+ JSMSG_JSON_BAD_PARSE: "JSON_bad_parse",
+ JSMSG_UNDECLARED_VAR: "Undeclared_var",
+ JSMSG_UNEXPECTED_TOKEN: "Unexpected_token",
+ JSMSG_BAD_OCTAL: "Bad_octal",
+ JSMSG_PROPERTY_ACCESS_DENIED: "Property_access_denied",
+ JSMSG_NO_PROPERTIES: "No_properties",
+ JSMSG_ALREADY_HAS_PRAGMA: "Already_has_pragma",
+ JSMSG_BAD_RETURN_OR_YIELD: "Bad_return_or_yield",
+ JSMSG_UNEXPECTED_TOKEN_NO_EXPECT: "Missing_semicolon_before_statement",
+ JSMSG_OVER_RECURSED: "Too_much_recursion",
+ JSMSG_BRACKET_AFTER_LIST: "Missing_bracket_after_list",
+ JSMSG_PAREN_AFTER_ARGS: "Missing_parenthesis_after_argument_list",
+ JSMSG_MORE_ARGS_NEEDED: "More_arguments_needed",
+ JSMSG_BAD_LEFTSIDE_OF_ASS: "Invalid_assignment_left-hand_side",
+ JSMSG_UNTERMINATED_STRING: "Unterminated_string_literal",
+ JSMSG_NOT_CONSTRUCTOR: "Not_a_constructor",
+ JSMSG_CURLY_AFTER_LIST: "Missing_curly_after_property_list",
+ JSMSG_DEPRECATED_FOR_EACH: "For-each-in_loops_are_deprecated",
+ JSMSG_STRICT_NON_SIMPLE_PARAMS: "Strict_Non_Simple_Params",
+ JSMSG_DEAD_OBJECT: "Dead_object",
+ JSMSG_OBJECT_REQUIRED: "No_non-null_object",
+ JSMSG_IDSTART_AFTER_NUMBER: "Identifier_after_number",
+ JSMSG_DEPRECATED_EXPR_CLOSURE: "Deprecated_expression_closures",
+ JSMSG_ILLEGAL_CHARACTER: "Illegal_character",
+ JSMSG_BAD_REGEXP_FLAG: "Bad_regexp_flag",
+ JSMSG_INVALID_FOR_IN_DECL_WITH_INIT: "Invalid_for-in_initializer",
+ JSMSG_CANT_REDEFINE_PROP: "Cant_redefine_property",
+ JSMSG_COLON_AFTER_ID: "Missing_colon_after_property_id",
+ JSMSG_IN_NOT_OBJECT: "in_operator_no_object",
+ JSMSG_CURLY_AFTER_BODY: "Missing_curly_after_function_body",
+ JSMSG_NAME_AFTER_DOT: "Missing_name_after_dot_operator",
+ JSMSG_DEPRECATED_OCTAL: "Deprecated_octal",
+ JSMSG_PAREN_AFTER_COND: "Missing_parenthesis_after_condition",
+ JSMSG_JSON_CYCLIC_VALUE: "Cyclic_object_value",
+ JSMSG_NO_VARIABLE_NAME: "No_variable_name",
+ JSMSG_UNNAMED_FUNCTION_STMT: "Unnamed_function_statement",
+ JSMSG_CANT_DEFINE_PROP_OBJECT_NOT_EXTENSIBLE:
+ "Cant_define_property_object_not_extensible",
+ JSMSG_TYPED_ARRAY_BAD_ARGS: "Typed_array_invalid_arguments",
+ JSMSG_GETTER_ONLY: "Getter_only",
+ JSMSG_INVALID_DATE: "Invalid_date",
+ JSMSG_DEPRECATED_STRING_METHOD: "Deprecated_String_generics",
+ JSMSG_RESERVED_ID: "Reserved_identifier",
+ JSMSG_BAD_CONST_ASSIGN: "Invalid_const_assignment",
+ JSMSG_BAD_CONST_DECL: "Missing_initializer_in_const",
+ JSMSG_OF_AFTER_FOR_LOOP_DECL: "Invalid_for-of_initializer",
+ JSMSG_BAD_URI: "Malformed_URI",
+ JSMSG_DEPRECATED_DELETE_OPERAND: "Delete_in_strict_mode",
+ JSMSG_MISSING_FORMAL: "Missing_formal_parameter",
+ JSMSG_CANT_TRUNCATE_ARRAY: "Non_configurable_array_element",
+ JSMSG_INCOMPATIBLE_PROTO: "Called_on_incompatible_type",
+ JSMSG_INCOMPATIBLE_METHOD: "Called_on_incompatible_type",
+ JSMSG_BAD_INSTANCEOF_RHS: "invalid_right_hand_side_instanceof_operand",
+ JSMSG_EMPTY_ARRAY_REDUCE: "Reduce_of_empty_array_with_no_initial_value",
+ JSMSG_NOT_ITERABLE: "is_not_iterable",
+ JSMSG_PROPERTY_FAIL: "cant_access_property",
+ JSMSG_PROPERTY_FAIL_EXPR: "cant_access_property",
+ JSMSG_REDECLARED_VAR: "Redeclared_parameter",
+ JSMSG_SET_NON_OBJECT_RECEIVER: "Cant_assign_to_property",
+};
+
+const MIXED_CONTENT_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/Security/Mixed_content";
+const TRACKING_PROTECTION_LEARN_MORE =
+ "https://developer.mozilla.org/Firefox/Privacy/Tracking_Protection";
+const INSECURE_PASSWORDS_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/Security/Insecure_passwords";
+const PUBLIC_KEY_PINS_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/HTTP/Public_Key_Pinning";
+const STRICT_TRANSPORT_SECURITY_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/HTTP/Headers/Strict-Transport-Security";
+const WEAK_SIGNATURE_ALGORITHM_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/Security/Weak_Signature_Algorithm";
+const MIME_TYPE_MISMATCH_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/HTTP/Headers/X-Content-Type-Options";
+const SOURCE_MAP_LEARN_MORE =
+ "https://developer.mozilla.org/en-US/docs/Tools/Debugger/Source_map_errors";
+const TLS_LEARN_MORE =
+ "https://blog.mozilla.org/security/2018/10/15/removing-old-versions-of-tls/";
+const X_FRAME_OPTIONS_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/HTTP/Headers/X-Frame-Options";
+const REQUEST_STORAGE_ACCESS_LEARN_MORE =
+ "https://developer.mozilla.org/docs/Web/API/Document/requestStorageAccess";
+const ErrorCategories = {
+ "X-Frame-Options": X_FRAME_OPTIONS_LEARN_MORE,
+ "Insecure Password Field": INSECURE_PASSWORDS_LEARN_MORE,
+ "Mixed Content Message": MIXED_CONTENT_LEARN_MORE,
+ "Mixed Content Blocker": MIXED_CONTENT_LEARN_MORE,
+ "Invalid HPKP Headers": PUBLIC_KEY_PINS_LEARN_MORE,
+ "Invalid HSTS Headers": STRICT_TRANSPORT_SECURITY_LEARN_MORE,
+ "SHA-1 Signature": WEAK_SIGNATURE_ALGORITHM_LEARN_MORE,
+ "Tracking Protection": TRACKING_PROTECTION_LEARN_MORE,
+ MIMEMISMATCH: MIME_TYPE_MISMATCH_LEARN_MORE,
+ "source map": SOURCE_MAP_LEARN_MORE,
+ TLS: TLS_LEARN_MORE,
+ requestStorageAccess: REQUEST_STORAGE_ACCESS_LEARN_MORE,
+ HTTPSOnly: supportBaseURL + "https-only-prefs",
+};
+
+const baseCorsErrorUrl =
+ "https://developer.mozilla.org/docs/Web/HTTP/CORS/Errors/";
+const corsParams =
+ "?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default";
+const CorsErrorDocs = {
+ CORSDisabled: "CORSDisabled",
+ CORSDidNotSucceed: "CORSDidNotSucceed",
+ CORSOriginHeaderNotAdded: "CORSOriginHeaderNotAdded",
+ CORSExternalRedirectNotAllowed: "CORSExternalRedirectNotAllowed",
+ CORSRequestNotHttp: "CORSRequestNotHttp",
+ CORSMissingAllowOrigin: "CORSMissingAllowOrigin",
+ CORSMultipleAllowOriginNotAllowed: "CORSMultipleAllowOriginNotAllowed",
+ CORSAllowOriginNotMatchingOrigin: "CORSAllowOriginNotMatchingOrigin",
+ CORSNotSupportingCredentials: "CORSNotSupportingCredentials",
+ CORSMethodNotFound: "CORSMethodNotFound",
+ CORSMissingAllowCredentials: "CORSMissingAllowCredentials",
+ CORSPreflightDidNotSucceed2: "CORSPreflightDidNotSucceed",
+ CORSInvalidAllowMethod: "CORSInvalidAllowMethod",
+ CORSInvalidAllowHeader: "CORSInvalidAllowHeader",
+ CORSMissingAllowHeaderFromPreflight2: "CORSMissingAllowHeaderFromPreflight",
+};
+
+const baseStorageAccessPolicyErrorUrl =
+ "https://developer.mozilla.org/docs/Mozilla/Firefox/Privacy/Storage_access_policy/Errors/";
+const storageAccessPolicyParams =
+ "?utm_source=devtools&utm_medium=firefox-cookie-errors&utm_campaign=default";
+const StorageAccessPolicyErrorDocs = {
+ cookieBlockedPermission: "CookieBlockedByPermission",
+ cookieBlockedTracker: "CookieBlockedTracker",
+ cookieBlockedAll: "CookieBlockedAll",
+ cookieBlockedForeign: "CookieBlockedForeign",
+ cookiePartitionedForeign: "CookiePartitionedForeign",
+};
+
+exports.GetURL = error => {
+ if (!error) {
+ return undefined;
+ }
+
+ const doc = ErrorDocs[error.errorMessageName];
+ if (doc) {
+ return baseErrorURL + doc + params;
+ }
+
+ const corsDoc = CorsErrorDocs[error.category];
+ if (corsDoc) {
+ return baseCorsErrorUrl + corsDoc + corsParams;
+ }
+
+ const storageAccessPolicyDoc = StorageAccessPolicyErrorDocs[error.category];
+ if (storageAccessPolicyDoc) {
+ return (
+ baseStorageAccessPolicyErrorUrl +
+ storageAccessPolicyDoc +
+ storageAccessPolicyParams
+ );
+ }
+
+ const categoryURL = ErrorCategories[error.category];
+ if (categoryURL) {
+ return categoryURL + params;
+ }
+ return undefined;
+};
diff --git a/devtools/server/actors/frame.js b/devtools/server/actors/frame.js
new file mode 100644
index 0000000000..232ea40793
--- /dev/null
+++ b/devtools/server/actors/frame.js
@@ -0,0 +1,223 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const Debugger = require("Debugger");
+const { assert } = require("devtools/shared/DevToolsUtils");
+const { Pool } = require("devtools/shared/protocol/Pool");
+const { createValueGrip } = require("devtools/server/actors/object/utils");
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { frameSpec } = require("devtools/shared/specs/frame");
+
+function formatDisplayName(frame) {
+ if (frame.type === "call") {
+ const callee = frame.callee;
+ return callee.name || callee.userDisplayName || callee.displayName;
+ }
+
+ return `(${frame.type})`;
+}
+
+function isDeadSavedFrame(savedFrame) {
+ return Cu && Cu.isDeadWrapper(savedFrame);
+}
+function isValidSavedFrame(threadActor, savedFrame) {
+ return (
+ !isDeadSavedFrame(savedFrame) &&
+ // If the frame's source is unknown to the debugger, then we ignore it
+ // since the frame likely does not belong to a realm that is marked
+ // as a debuggee.
+ // This check will also fail if the frame would have been known but was
+ // GCed before the debugger was opened on the page.
+ // TODO: Use SavedFrame's security principal to limit non-debuggee frames
+ // and pass all unknown frames to the debugger as a URL with no sourceID.
+ getSavedFrameSource(threadActor, savedFrame)
+ );
+}
+function getSavedFrameSource(threadActor, savedFrame) {
+ return threadActor.sourcesManager.getSourceActorByInternalSourceId(
+ savedFrame.sourceId
+ );
+}
+function getSavedFrameParent(threadActor, savedFrame) {
+ if (isDeadSavedFrame(savedFrame)) {
+ return null;
+ }
+
+ while (true) {
+ savedFrame = savedFrame.parent || savedFrame.asyncParent;
+
+ // If the saved frame is a dead wrapper, we don't have any way to keep
+ // stepping through parent frames.
+ if (!savedFrame || isDeadSavedFrame(savedFrame)) {
+ savedFrame = null;
+ break;
+ }
+
+ if (isValidSavedFrame(threadActor, savedFrame)) {
+ break;
+ }
+ }
+ return savedFrame;
+}
+
+/**
+ * An actor for a specified stack frame.
+ */
+const FrameActor = ActorClassWithSpec(frameSpec, {
+ /**
+ * Creates the Frame actor.
+ *
+ * @param frame Debugger.Frame|SavedFrame
+ * The debuggee frame.
+ * @param threadActor ThreadActor
+ * The parent thread actor for this frame.
+ */
+ initialize: function(frame, threadActor, depth) {
+ Actor.prototype.initialize.call(this, threadActor.conn);
+
+ this.frame = frame;
+ this.threadActor = threadActor;
+ this.depth = depth;
+ },
+
+ /**
+ * A pool that contains frame-lifetime objects, like the environment.
+ */
+ _frameLifetimePool: null,
+ get frameLifetimePool() {
+ if (!this._frameLifetimePool) {
+ this._frameLifetimePool = new Pool(this.conn, "frame");
+ }
+ return this._frameLifetimePool;
+ },
+
+ /**
+ * Finalization handler that is called when the actor is being evicted from
+ * the pool.
+ */
+ destroy: function() {
+ if (this._frameLifetimePool) {
+ this._frameLifetimePool.destroy();
+ this._frameLifetimePool = null;
+ }
+ Actor.prototype.destroy.call(this);
+ },
+
+ getEnvironment: function() {
+ try {
+ if (!this.frame.environment) {
+ return {};
+ }
+ } catch (e) {
+ // |this.frame| might not be live. FIXME Bug 1477030 we shouldn't be
+ // using frames we derived from a point where we are not currently
+ // paused at.
+ return {};
+ }
+
+ const envActor = this.threadActor.createEnvironmentActor(
+ this.frame.environment,
+ this.frameLifetimePool
+ );
+
+ return envActor.form();
+ },
+
+ /**
+ * Returns a frame form for use in a protocol message.
+ */
+ form: function() {
+ // SavedFrame actors have their own frame handling.
+ if (!(this.frame instanceof Debugger.Frame)) {
+ // The Frame actor shouldn't be used after evaluation is resumed, so
+ // there shouldn't be an easy way for the saved frame to be referenced
+ // once it has died.
+ assert(!isDeadSavedFrame(this.frame));
+
+ const obj = {
+ actor: this.actorID,
+ // TODO: Bug 1610418 - Consider updating SavedFrame to have a type.
+ type: "dead",
+ asyncCause: this.frame.asyncCause,
+ state: "dead",
+ displayName: this.frame.functionDisplayName,
+ arguments: [],
+ where: {
+ // The frame's source should always be known because
+ // getSavedFrameParent will skip over frames with unknown sources.
+ actor: getSavedFrameSource(this.threadActor, this.frame).actorID,
+ line: this.frame.line,
+ // SavedFrame objects have a 1-based column number, but this API and
+ // Debugger API objects use a 0-based column value.
+ column: this.frame.column - 1,
+ },
+ oldest: !getSavedFrameParent(this.threadActor, this.frame),
+ };
+
+ return obj;
+ }
+
+ const threadActor = this.threadActor;
+ const form = {
+ actor: this.actorID,
+ type: this.frame.type,
+ asyncCause: this.frame.onStack ? null : "await",
+ state: this.frame.onStack ? "on-stack" : "suspended",
+ };
+
+ if (this.depth) {
+ form.depth = this.depth;
+ }
+
+ if (this.frame.type != "wasmcall") {
+ form.this = createValueGrip(
+ this.frame.this,
+ threadActor._pausePool,
+ threadActor.objectGrip
+ );
+ }
+
+ form.displayName = formatDisplayName(this.frame);
+ form.arguments = this._args();
+
+ if (this.frame.script) {
+ const location = this.threadActor.sourcesManager.getFrameLocation(
+ this.frame
+ );
+ form.where = {
+ actor: location.sourceActor.actorID,
+ line: location.line,
+ column: location.column,
+ };
+ }
+
+ if (!this.frame.older) {
+ form.oldest = true;
+ }
+
+ return form;
+ },
+
+ _args: function() {
+ if (!this.frame.onStack || !this.frame.arguments) {
+ return [];
+ }
+
+ return this.frame.arguments.map(arg =>
+ createValueGrip(
+ arg,
+ this.threadActor._pausePool,
+ this.threadActor.objectGrip
+ )
+ );
+ },
+});
+
+exports.FrameActor = FrameActor;
+exports.formatDisplayName = formatDisplayName;
+exports.getSavedFrameParent = getSavedFrameParent;
+exports.isValidSavedFrame = isValidSavedFrame;
diff --git a/devtools/server/actors/framerate.js b/devtools/server/actors/framerate.js
new file mode 100644
index 0000000000..af12c72f81
--- /dev/null
+++ b/devtools/server/actors/framerate.js
@@ -0,0 +1,32 @@
+/* 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";
+
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { actorBridgeWithSpec } = require("devtools/server/actors/common");
+const { Framerate } = require("devtools/server/performance/framerate");
+const { framerateSpec } = require("devtools/shared/specs/framerate");
+
+/**
+ * An actor wrapper around Framerate. Uses exposed
+ * methods via bridge and provides RDP definitions.
+ *
+ * @see devtools/server/performance/framerate.js for documentation.
+ */
+exports.FramerateActor = ActorClassWithSpec(framerateSpec, {
+ initialize: function(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ this.bridge = new Framerate(targetActor);
+ },
+ destroy: function(conn) {
+ Actor.prototype.destroy.call(this, conn);
+ this.bridge.destroy();
+ },
+
+ startRecording: actorBridgeWithSpec("startRecording"),
+ stopRecording: actorBridgeWithSpec("stopRecording"),
+ cancelRecording: actorBridgeWithSpec("cancelRecording"),
+ isRecording: actorBridgeWithSpec("isRecording"),
+ getPendingTicks: actorBridgeWithSpec("getPendingTicks"),
+});
diff --git a/devtools/server/actors/heap-snapshot-file.js b/devtools/server/actors/heap-snapshot-file.js
new file mode 100644
index 0000000000..d78fcc1a38
--- /dev/null
+++ b/devtools/server/actors/heap-snapshot-file.js
@@ -0,0 +1,83 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const Services = require("Services");
+
+const {
+ heapSnapshotFileSpec,
+} = require("devtools/shared/specs/heap-snapshot-file");
+
+loader.lazyRequireGetter(
+ this,
+ "DevToolsUtils",
+ "devtools/shared/DevToolsUtils"
+);
+loader.lazyRequireGetter(this, "OS", "resource://gre/modules/osfile.jsm", true);
+loader.lazyRequireGetter(
+ this,
+ "HeapSnapshotFileUtils",
+ "devtools/shared/heapsnapshot/HeapSnapshotFileUtils"
+);
+
+/**
+ * The HeapSnapshotFileActor handles transferring heap snapshot files from the
+ * server to the client. This has to be a global actor in the parent process
+ * because child processes are sandboxed and do not have access to the file
+ * system.
+ */
+exports.HeapSnapshotFileActor = protocol.ActorClassWithSpec(
+ heapSnapshotFileSpec,
+ {
+ initialize: function(conn, parent) {
+ if (
+ Services.appinfo.processType !== Services.appinfo.PROCESS_TYPE_DEFAULT
+ ) {
+ const err = new Error(
+ "Attempt to create a HeapSnapshotFileActor in a " +
+ "child process! The HeapSnapshotFileActor *MUST* " +
+ "be in the parent process!"
+ );
+ DevToolsUtils.reportException(
+ "HeapSnapshotFileActor.prototype.initialize",
+ err
+ );
+ return;
+ }
+
+ protocol.Actor.prototype.initialize.call(this, conn, parent);
+ },
+
+ /**
+ * @see MemoryFront.prototype.transferHeapSnapshot
+ */
+ async transferHeapSnapshot(snapshotId) {
+ const snapshotFilePath = HeapSnapshotFileUtils.getHeapSnapshotTempFilePath(
+ snapshotId
+ );
+ if (!snapshotFilePath) {
+ throw new Error(`No heap snapshot with id: ${snapshotId}`);
+ }
+
+ const streamPromise = DevToolsUtils.openFileStream(snapshotFilePath);
+
+ const { size } = await OS.File.stat(snapshotFilePath);
+ const bulkPromise = this.conn.startBulkSend({
+ actor: this.actorID,
+ type: "heap-snapshot",
+ length: size,
+ });
+
+ const [bulk, stream] = await Promise.all([bulkPromise, streamPromise]);
+
+ try {
+ await bulk.copyFrom(stream);
+ } finally {
+ stream.close();
+ }
+ },
+ }
+);
diff --git a/devtools/server/actors/highlighters.css b/devtools/server/actors/highlighters.css
new file mode 100644
index 0000000000..edbc0879bc
--- /dev/null
+++ b/devtools/server/actors/highlighters.css
@@ -0,0 +1,963 @@
+/* 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/. */
+
+/*
+ The :-moz-native-anonymous selector prefix prevents the styles defined here
+ from impacting web content. Indeed, this pseudo-class is only available to chrome code.
+ This stylesheet is loaded as a ua stylesheet via the addon sdk, so having this
+ pseudo-class is important.
+
+ A specific selector should still be specified to avoid impacting non-devtools
+ chrome content.
+*/
+
+:-moz-native-anonymous .highlighter-container {
+ /*
+ Content CSS applying to the html element impact the highlighters.
+ To avoid that, possible cases have been set to initial.
+ */
+ text-transform: initial;
+ text-indent: initial;
+ letter-spacing: initial;
+ word-spacing: initial;
+ color: initial;
+ direction: initial;
+ writing-mode: initial;
+}
+
+:-moz-native-anonymous .highlighter-container {
+ --highlighter-guide-color: hsl(200, 100%, 40%);
+ --highlighter-content-color: hsl(197, 71%, 73%);
+ --highlighter-bubble-text-color: hsl(216, 33%, 97%);
+ --highlighter-bubble-background-color: hsl(214, 13%, 24%);
+ --highlighter-bubble-border-color: rgba(255, 255, 255, 0.2);
+ --highlighter-bubble-arrow-size: 8px;
+ --highlighter-font-family: message-box;
+ --highlighter-font-size: 11px;
+ --highlighter-infobar-color: hsl(210, 30%, 85%);
+ --highlighter-marker-color: #000;
+
+ --grey-40: #b1b1b3;
+ --red-40: #ff3b6b;
+ --yellow-60: #d7b600;
+ --blue-60: #0060df;
+}
+
+/**
+ * Highlighters are asbolute positioned in the page by default.
+ * A single highlighter can have fixed position in its css class if needed (see below the
+ * eye dropper or rulers highlighter, for example); but if it has to handle the
+ * document's scrolling (as rulers does), it would lag a bit behind due the APZ (Async
+ * Pan/Zoom module), that performs asynchronously panning and zooming on the compositor
+ * thread rather than the main thread.
+ */
+:-moz-native-anonymous .highlighter-container {
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ /* The container for all highlighters doesn't react to pointer-events by
+ default. This is because most highlighters cover the whole viewport but
+ don't contain UIs that need to be accessed.
+ If your highlighter has UI that needs to be interacted with, add
+ 'pointer-events:auto;' on its container element. */
+ pointer-events: none;
+}
+
+:-moz-native-anonymous .highlighter-container.box-model {
+ /* Make the box-model container have a z-index other than auto so it always sits above
+ other highlighters. */
+ z-index: 1;
+}
+
+:-moz-native-anonymous .highlighter-container [hidden] {
+ display: none;
+}
+
+:-moz-native-anonymous .highlighter-container [dragging] {
+ cursor: grabbing;
+}
+
+/* Box Model Highlighter */
+
+:-moz-native-anonymous .box-model-regions {
+ opacity: 0.6;
+}
+
+/* Box model regions can be faded (see the onlyRegionArea option in
+ highlighters.js) in order to only display certain regions. */
+:-moz-native-anonymous .box-model-regions [faded] {
+ display: none;
+}
+
+:-moz-native-anonymous .box-model-content {
+ fill: var(--highlighter-content-color);
+}
+
+:-moz-native-anonymous .box-model-padding {
+ fill: #6a5acd;
+}
+
+:-moz-native-anonymous .box-model-border {
+ fill: #444444;
+}
+
+:-moz-native-anonymous .box-model-margin {
+ fill: #edff64;
+}
+
+:-moz-native-anonymous .box-model-content,
+:-moz-native-anonymous .box-model-padding,
+:-moz-native-anonymous .box-model-border,
+:-moz-native-anonymous .box-model-margin {
+ stroke: none;
+}
+
+:-moz-native-anonymous .box-model-guide-top,
+:-moz-native-anonymous .box-model-guide-right,
+:-moz-native-anonymous .box-model-guide-bottom,
+:-moz-native-anonymous .box-model-guide-left {
+ stroke: var(--highlighter-guide-color);
+ stroke-dasharray: 5 3;
+ shape-rendering: crispEdges;
+}
+
+/* Highlighter - Infobar */
+
+:-moz-native-anonymous [class$="infobar-container"] {
+ position: absolute;
+ max-width: 95%;
+
+ font: var(--highlighter-font-family);
+ font-size: var(--highlighter-font-size);
+}
+
+:-moz-native-anonymous [class$="infobar"] {
+ position: relative;
+
+ padding: 5px;
+ min-width: 75px;
+
+ border-radius: 3px;
+ background: var(--highlighter-bubble-background-color) no-repeat padding-box;
+
+ color: var(--highlighter-bubble-text-color);
+ text-shadow: none;
+
+ border: 1px solid var(--highlighter-bubble-border-color);
+}
+
+/* Arrows */
+
+:-moz-native-anonymous
+ [class$="infobar-container"]
+ > [class$="infobar"]:before {
+ left: calc(50% - var(--highlighter-bubble-arrow-size));
+ border: var(--highlighter-bubble-arrow-size) solid
+ var(--highlighter-bubble-border-color);
+}
+
+:-moz-native-anonymous [class$="infobar-container"] > [class$="infobar"]:after {
+ left: calc(50% - 7px);
+ border: 7px solid var(--highlighter-bubble-background-color);
+}
+
+:-moz-native-anonymous [class$="infobar-container"] > [class$="infobar"]:before,
+:-moz-native-anonymous [class$="infobar-container"] > [class$="infobar"]:after {
+ content: "";
+ display: none;
+ position: absolute;
+ height: 0;
+ width: 0;
+ border-left-color: transparent;
+ border-right-color: transparent;
+}
+
+:-moz-native-anonymous
+ [class$="infobar-container"][position="top"]:not([hide-arrow])
+ > [class$="infobar"]:before,
+:-moz-native-anonymous
+ [class$="infobar-container"][position="top"]:not([hide-arrow])
+ > [class$="infobar"]:after {
+ border-bottom: 0;
+ top: 100%;
+ display: block;
+}
+
+:-moz-native-anonymous
+ [class$="infobar-container"][position="bottom"]:not([hide-arrow])
+ > [class$="infobar"]:before,
+:-moz-native-anonymous
+ [class$="infobar-container"][position="bottom"]:not([hide-arrow])
+ > [class$="infobar"]:after {
+ border-top: 0;
+ bottom: 100%;
+ display: block;
+}
+
+/* Text Container */
+
+:-moz-native-anonymous [class$="infobar-text"] {
+ overflow: hidden;
+ white-space: nowrap;
+ direction: ltr;
+ padding-bottom: 1px;
+ display: flex;
+ justify-content: center;
+ max-width: 768px;
+}
+
+:-moz-native-anonymous .box-model-infobar-tagname {
+ color: hsl(285, 100%, 75%);
+}
+
+:-moz-native-anonymous .box-model-infobar-id {
+ color: hsl(103, 46%, 54%);
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+:-moz-native-anonymous .box-model-infobar-classes,
+:-moz-native-anonymous .box-model-infobar-pseudo-classes {
+ color: hsl(200, 74%, 57%);
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+:-moz-native-anonymous [class$="infobar-dimensions"],
+:-moz-native-anonymous [class$="infobar-grid-type"],
+:-moz-native-anonymous [class$="infobar-flex-type"] {
+ border-inline-start: 1px solid #5a6169;
+ margin-inline-start: 6px;
+ padding-inline-start: 6px;
+}
+
+:-moz-native-anonymous [class$="infobar-grid-type"]:empty,
+:-moz-native-anonymous [class$="infobar-flex-type"]:empty {
+ display: none;
+}
+
+:-moz-native-anonymous [class$="infobar-dimensions"] {
+ color: var(--highlighter-infobar-color);
+}
+
+:-moz-native-anonymous [class$="infobar-grid-type"],
+:-moz-native-anonymous [class$="infobar-flex-type"] {
+ color: var(--grey-40);
+}
+
+/* CSS Grid Highlighter */
+
+:-moz-native-anonymous .css-grid-canvas {
+ position: absolute;
+ pointer-events: none;
+ top: 0;
+ left: 0;
+ image-rendering: -moz-crisp-edges;
+}
+
+:-moz-native-anonymous .css-grid-regions {
+ opacity: 0.6;
+}
+
+:-moz-native-anonymous .css-grid-areas,
+:-moz-native-anonymous .css-grid-cells {
+ opacity: 0.5;
+ stroke: none;
+}
+
+:-moz-native-anonymous .css-grid-area-infobar-name,
+:-moz-native-anonymous .css-grid-cell-infobar-position,
+:-moz-native-anonymous .css-grid-line-infobar-number {
+ color: hsl(285, 100%, 75%);
+}
+
+:-moz-native-anonymous .css-grid-line-infobar-names:not(:empty) {
+ color: var(--highlighter-infobar-color);
+ border-inline-start: 1px solid #5a6169;
+ margin-inline-start: 6px;
+ padding-inline-start: 6px;
+}
+
+/* CSS Transform Highlighter */
+
+:-moz-native-anonymous .css-transform-transformed {
+ fill: var(--highlighter-content-color);
+ opacity: 0.8;
+}
+
+:-moz-native-anonymous .css-transform-untransformed {
+ fill: #66cc52;
+ opacity: 0.8;
+}
+
+:-moz-native-anonymous .css-transform-transformed,
+:-moz-native-anonymous .css-transform-untransformed,
+:-moz-native-anonymous .css-transform-line {
+ stroke: var(--highlighter-guide-color);
+ stroke-dasharray: 5 3;
+ stroke-width: 2;
+}
+
+/* Element Geometry Highlighter */
+
+:-moz-native-anonymous .geometry-editor-root {
+ /* The geometry editor can be interacted with, so it needs to react to
+ pointer events */
+ pointer-events: auto;
+ user-select: none;
+}
+
+:-moz-native-anonymous .geometry-editor-offset-parent {
+ stroke: var(--highlighter-guide-color);
+ shape-rendering: crispEdges;
+ stroke-dasharray: 5 3;
+ fill: transparent;
+}
+
+:-moz-native-anonymous .geometry-editor-current-node {
+ stroke: var(--highlighter-guide-color);
+ fill: var(--highlighter-content-color);
+ shape-rendering: crispEdges;
+ opacity: 0.6;
+}
+
+:-moz-native-anonymous .geometry-editor-arrow {
+ stroke: var(--highlighter-guide-color);
+ shape-rendering: crispEdges;
+}
+
+:-moz-native-anonymous .geometry-editor-root circle {
+ stroke: var(--highlighter-guide-color);
+ fill: var(--highlighter-content-color);
+}
+
+:-moz-native-anonymous .geometry-editor-handler-top,
+:-moz-native-anonymous .geometry-editor-handler-bottom {
+ cursor: ns-resize;
+}
+
+:-moz-native-anonymous .geometry-editor-handler-right,
+:-moz-native-anonymous .geometry-editor-handler-left {
+ cursor: ew-resize;
+}
+
+:-moz-native-anonymous [dragging] .geometry-editor-handler-top,
+:-moz-native-anonymous [dragging] .geometry-editor-handler-right,
+:-moz-native-anonymous [dragging] .geometry-editor-handler-bottom,
+:-moz-native-anonymous [dragging] .geometry-editor-handler-left {
+ cursor: grabbing;
+}
+
+:-moz-native-anonymous .geometry-editor-handler-top.dragging,
+:-moz-native-anonymous .geometry-editor-handler-right.dragging,
+:-moz-native-anonymous .geometry-editor-handler-bottom.dragging,
+:-moz-native-anonymous .geometry-editor-handler-left.dragging {
+ fill: var(--highlighter-guide-color);
+}
+
+:-moz-native-anonymous .geometry-editor-label-bubble {
+ fill: var(--highlighter-bubble-background-color);
+ shape-rendering: crispEdges;
+}
+
+:-moz-native-anonymous .geometry-editor-label-text {
+ fill: var(--highlighter-bubble-text-color);
+ font: var(--highlighter-font-family);
+ font-size: 10px;
+ text-anchor: middle;
+ dominant-baseline: middle;
+}
+
+/* Rulers Highlighter */
+
+:-moz-native-anonymous .rulers-highlighter-elements {
+ shape-rendering: crispEdges;
+ pointer-events: none;
+ position: fixed;
+ top: 0;
+ left: 0;
+}
+
+:-moz-native-anonymous .rulers-highlighter-elements > g {
+ opacity: 0.8;
+}
+
+:-moz-native-anonymous .rulers-highlighter-elements > g > rect {
+ fill: #fff;
+}
+
+:-moz-native-anonymous .rulers-highlighter-ruler-graduations {
+ stroke: #bebebe;
+}
+
+:-moz-native-anonymous .rulers-highlighter-ruler-markers {
+ stroke: #202020;
+}
+
+:-moz-native-anonymous .rulers-highlighter-horizontal-labels > text,
+:-moz-native-anonymous .rulers-highlighter-vertical-labels > text {
+ stroke: none;
+ fill: #202020;
+ font: var(--highlighter-font-family);
+ font-size: 9px;
+ dominant-baseline: hanging;
+}
+
+:-moz-native-anonymous .rulers-highlighter-horizontal-labels > text {
+ text-anchor: start;
+}
+
+:-moz-native-anonymous .rulers-highlighter-vertical-labels > text {
+ transform: rotate(-90deg);
+ text-anchor: end;
+}
+
+:-moz-native-anonymous .rulers-highlighter-viewport-infobar-container {
+ shape-rendering: crispEdges;
+ background-color: rgba(255, 255, 255, 0.7);
+ font: var(--highlighter-font-family);
+ position: fixed;
+ top: 30px;
+ right: 0px;
+ font-size: 12px;
+ padding: 4px;
+}
+
+/* Measuring Tool Highlighter */
+
+:-moz-native-anonymous .measuring-tool-tool {
+ pointer-events: auto;
+}
+
+:-moz-native-anonymous .measuring-tool-root {
+ position: absolute;
+ top: 0;
+ left: 0;
+ pointer-events: auto;
+ cursor: crosshair;
+}
+
+:-moz-native-anonymous .measuring-tool-elements {
+ position: absolute;
+}
+
+:-moz-native-anonymous .measuring-tool-root path {
+ shape-rendering: geometricPrecision;
+ pointer-events: auto;
+}
+
+:-moz-native-anonymous .measuring-tool-root .measuring-tool-box-path,
+:-moz-native-anonymous .measuring-tool-root .measuring-tool-diagonal-path {
+ fill: rgba(135, 206, 235, 0.6);
+ stroke: var(--highlighter-guide-color);
+}
+
+:-moz-native-anonymous .measuring-tool-root circle {
+ stroke: var(--highlighter-guide-color);
+ stroke-width: 2px;
+ fill: #fff;
+ vector-effect: non-scaling-stroke;
+}
+
+:-moz-native-anonymous .measuring-tool-handler-top,
+:-moz-native-anonymous .measuring-tool-handler-bottom {
+ cursor: ns-resize;
+}
+
+:-moz-native-anonymous .measuring-tool-handler-right,
+:-moz-native-anonymous .measuring-tool-handler-left {
+ cursor: ew-resize;
+}
+
+:-moz-native-anonymous .measuring-tool-handler-topleft,
+:-moz-native-anonymous .measuring-tool-handler-bottomright {
+ cursor: nwse-resize;
+}
+
+:-moz-native-anonymous .measuring-tool-handler-topright,
+:-moz-native-anonymous .measuring-tool-handler-bottomleft {
+ cursor: nesw-resize;
+}
+
+:-moz-native-anonymous .mirrored .measuring-tool-handler-topleft,
+:-moz-native-anonymous .mirrored .measuring-tool-handler-bottomright {
+ cursor: nesw-resize;
+}
+
+:-moz-native-anonymous .mirrored .measuring-tool-handler-topright,
+:-moz-native-anonymous .mirrored .measuring-tool-handler-bottomleft {
+ cursor: nwse-resize;
+}
+
+:-moz-native-anonymous [class^=measuring-tool-handler].dragging {
+ fill: var(--highlighter-guide-color);
+}
+
+:-moz-native-anonymous .dragging .measuring-tool-box-path,
+:-moz-native-anonymous .dragging .measuring-tool-diagonal-path {
+ opacity: 0.45;
+}
+
+:-moz-native-anonymous .measuring-tool-label-size,
+:-moz-native-anonymous .measuring-tool-label-position {
+ position: absolute;
+ top: 0;
+ left: 0;
+ display: inline-block;
+ border-radius: 4px;
+ padding: 4px;
+ white-space: pre-line;
+ font: var(--highlighter-font-family);
+ font-size: 10px;
+ pointer-events: none;
+ user-select: none;
+ box-sizing: border-box;
+}
+
+:-moz-native-anonymous .measuring-tool-label-position {
+ color: #fff;
+ background: hsla(214, 13%, 24%, 0.8);
+}
+
+:-moz-native-anonymous .measuring-tool-label-size {
+ color: var(--highlighter-bubble-text-color);
+ background: var(--highlighter-bubble-background-color);
+ border: 1px solid var(--highlighter-bubble-border-color);
+ line-height: 1.5em;
+}
+
+:-moz-native-anonymous [class^=measuring-tool-guide] {
+ stroke: var(--highlighter-guide-color);
+ stroke-dasharray: 5 3;
+ shape-rendering: crispEdges;
+}
+
+/* Eye Dropper */
+
+:-moz-native-anonymous .eye-dropper-root {
+ --magnifier-width: 96px;
+ --magnifier-height: 96px;
+ /* Width accounts for all color formats (hsl being the longest) */
+ --label-width: 160px;
+ --label-height: 23px;
+ --color: #e0e0e0;
+
+ position: fixed;
+ /* Tool start position. This should match the X/Y defines in JS */
+ top: 100px;
+ left: 100px;
+
+ /* Prevent interacting with the page when hovering and clicking */
+ pointer-events: auto;
+
+ /* Offset the UI so it is centered around the pointer */
+ transform: translate(
+ calc(var(--magnifier-width) / -2),
+ calc(var(--magnifier-height) / -2)
+ );
+
+ filter: drop-shadow(0 0 1px rgba(0, 0, 0, 0.4));
+
+ /* We don't need the UI to be reversed in RTL locales, otherwise the # would appear
+ to the right of the hex code. Force LTR */
+ direction: ltr;
+}
+
+:-moz-native-anonymous .eye-dropper-canvas {
+ image-rendering: -moz-crisp-edges;
+ cursor: none;
+ width: var(--magnifier-width);
+ height: var(--magnifier-height);
+ border-radius: 50%;
+ box-shadow: 0 0 0 3px var(--color);
+ display: block;
+}
+
+:-moz-native-anonymous .eye-dropper-color-container {
+ background-color: var(--color);
+ border-radius: 2px;
+ width: var(--label-width);
+ height: var(--label-height);
+ position: relative;
+
+ --label-horizontal-center: translateX(
+ calc((var(--magnifier-width) - var(--label-width)) / 2)
+ );
+ --label-horizontal-left: translateX(
+ calc((-1 * var(--label-width) + var(--magnifier-width) / 2))
+ );
+ --label-horizontal-right: translateX(calc(var(--magnifier-width) / 2));
+ --label-vertical-top: translateY(
+ calc((-1 * var(--magnifier-height)) - var(--label-height))
+ );
+
+ /* By default the color label container sits below the canvas.
+ Here we just center it horizontally */
+ transform: var(--label-horizontal-center);
+ transition: transform 0.1s ease-in-out;
+}
+
+/* If there isn't enough space below the canvas, we move the label container to the top */
+:-moz-native-anonymous .eye-dropper-root[top] .eye-dropper-color-container {
+ transform: var(--label-horizontal-center) var(--label-vertical-top);
+}
+
+/* If there isn't enough space right of the canvas to horizontally center the label
+ container, offset it to the left */
+:-moz-native-anonymous .eye-dropper-root[left] .eye-dropper-color-container {
+ transform: var(--label-horizontal-left);
+}
+:-moz-native-anonymous
+ .eye-dropper-root[left][top]
+ .eye-dropper-color-container {
+ transform: var(--label-horizontal-left) var(--label-vertical-top);
+}
+
+/* If there isn't enough space left of the canvas to horizontally center the label
+ container, offset it to the right */
+:-moz-native-anonymous .eye-dropper-root[right] .eye-dropper-color-container {
+ transform: var(--label-horizontal-right);
+}
+:-moz-native-anonymous
+ .eye-dropper-root[right][top]
+ .eye-dropper-color-container {
+ transform: var(--label-horizontal-right) var(--label-vertical-top);
+}
+
+:-moz-native-anonymous .eye-dropper-color-preview {
+ width: 16px;
+ height: 16px;
+ position: absolute;
+ inset-inline-start: 3px;
+ inset-block-start: 3px;
+ box-shadow: 0px 0px 0px black;
+ border: solid 1px #fff;
+}
+
+:-moz-native-anonymous .eye-dropper-color-value {
+ text-shadow: 1px 1px 1px #fff;
+ font: var(--highlighter-font-family);
+ font-size: var(--highlighter-font-size);
+ text-align: center;
+ padding: 4px 0;
+}
+
+/* Paused Debugger Overlay */
+
+:-moz-native-anonymous .paused-dbg-root {
+ position: fixed;
+ top: 0;
+ left: 0;
+ zoom: 1;
+ right: 0;
+ bottom: 0;
+
+ width: 100vw;
+ height: 100vh;
+
+ display: flex;
+ align-items: center;
+ flex-direction: column;
+
+ /* We don't have access to DevTools themes here, but some of these colors come from the
+ themes. Theme variable names are given in comments. */
+ --text-color: #585959; /* --theme-body-color-alt */
+ --toolbar-background: #fcfcfc; /* --theme-toolbar-background */
+ --toolbar-border: #dde1e4; /* --theme-splitter-color */
+ --toolbar-box-shadow: 0 2px 2px 0 rgba(155, 155, 155, 0.26); /* --rdm-box-shadow */
+ --overlay-background: #dde1e4a8;
+}
+
+:-moz-native-anonymous .paused-dbg-root[overlay] {
+ background-color: var(--overlay-background);
+ pointer-events: auto;
+}
+
+:-moz-native-anonymous .paused-dbg-toolbar {
+ margin-top: 15px;
+ display: inline-flex;
+ user-select: none;
+
+ color: var(--text-color);
+ border-radius: 2px;
+ box-shadow: var(--toolbar-box-shadow);
+ background-color: var(--toolbar-background);
+ border: 1px solid var(--toolbar-border);
+ border-radius: 4px;
+
+ font: var(--highlighter-font-family);
+ font-size: var(--highlighter-font-size);
+}
+
+:-moz-native-anonymous .paused-dbg-toolbar button {
+ margin: 8px 4px 6px 6px;
+ width: 16px;
+ height: 16px;
+ mask-size: contain;
+ mask-repeat: no-repeat;
+ mask-position: center;
+ mask-size: 16px 16px;
+ background-color: var(--text-color);
+
+ border: 0px;
+ appearance: none;
+}
+
+:-moz-native-anonymous .paused-dbg-divider {
+ width: 1px;
+ height: 16px;
+ margin-top: 10px;
+ background-color: var(--toolbar-border);
+}
+
+:-moz-native-anonymous .paused-dbg-reason,
+:-moz-native-anonymous .paused-dbg-step-button-wrapper,
+:-moz-native-anonymous .paused-dbg-resume-button-wrapper {
+ margin-top: 2px;
+ margin-bottom: 2px;
+}
+
+:-moz-native-anonymous .paused-dbg-step-button-wrapper,
+:-moz-native-anonymous .paused-dbg-resume-button-wrapper {
+ margin-left: 2px;
+ margin-right: 2px;
+}
+
+:-moz-native-anonymous button.paused-dbg-step-button {
+ margin-left: 6px;
+ margin-right: 6px;
+ mask-image: url(chrome://devtools/content/debugger/images/stepOver.svg);
+ padding: 0;
+}
+
+:-moz-native-anonymous button.paused-dbg-resume-button {
+ margin-right: 6px;
+ margin-right: 6px;
+ mask-image: url(chrome://devtools/content/debugger/images/resume.svg);
+ padding: 0;
+}
+
+:-moz-native-anonymous .paused-dbg-step-button-wrapper.hover,
+:-moz-native-anonymous .paused-dbg-resume-button-wrapper.hover {
+ background-color: var(--toolbar-border);
+ border-radius: 2px;
+}
+
+:-moz-native-anonymous .paused-dbg-reason {
+ padding: 3px 16px;
+ margin: 8px 0px;
+ line-height: 20px;
+ font-size: 18px;
+ font: var(--highlighter-font-family);
+ font-size: var(--highlighter-font-size);
+}
+
+/* Shapes highlighter */
+
+:-moz-native-anonymous .shapes-root {
+ pointer-events: none;
+}
+
+:-moz-native-anonymous .shapes-shape-container {
+ position: absolute;
+ overflow: visible;
+}
+
+:-moz-native-anonymous .shapes-polygon,
+:-moz-native-anonymous .shapes-ellipse,
+:-moz-native-anonymous .shapes-rect,
+:-moz-native-anonymous .shapes-bounding-box,
+:-moz-native-anonymous .shapes-rotate-line,
+:-moz-native-anonymous .shapes-quad {
+ fill: transparent;
+ stroke: var(--highlighter-guide-color);
+ shape-rendering: geometricPrecision;
+ vector-effect: non-scaling-stroke;
+}
+
+:-moz-native-anonymous .shapes-markers {
+ fill: #fff;
+}
+
+:-moz-native-anonymous .shapes-markers-outline {
+ fill: var(--highlighter-guide-color);
+}
+
+:-moz-native-anonymous .shapes-marker-hover {
+ fill: var(--highlighter-guide-color);
+}
+
+/* Accessible highlighter */
+
+:-moz-native-anonymous .accessible-infobar {
+ min-width: unset;
+}
+
+:-moz-native-anonymous .accessible-infobar-text {
+ display: grid;
+ grid-template-areas:
+ "role name"
+ "audit audit";
+ grid-template-columns: min-content 1fr;
+}
+
+:-moz-native-anonymous .accessible-infobar-role {
+ grid-area: role;
+ color: #9cdcfe;
+}
+
+:-moz-native-anonymous .accessible-infobar-name {
+ grid-area: name;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit {
+ grid-area: audit;
+ padding-top: 5px;
+ padding-bottom: 2px;
+}
+
+:-moz-native-anonymous .accessible-bounds {
+ opacity: 0.6;
+ fill: #6a5acd;
+}
+
+:-moz-native-anonymous .accessible-infobar-name,
+:-moz-native-anonymous .accessible-infobar-audit {
+ color: var(--highlighter-infobar-color);
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio:empty::before,
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio:empty::after,
+:-moz-native-anonymous .accessible-infobar-name:empty {
+ display: none;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio::before {
+ content: "";
+ height: 8px;
+ width: 8px;
+ display: inline-flex;
+ background-color: var(--accessibility-highlighter-contrast-ratio-color);
+ box-shadow: 0 0 0 1px var(--grey-40),
+ 4px 3px var(--accessibility-highlighter-contrast-ratio-bg),
+ 4px 3px 0 1px var(--grey-40);
+ margin-inline-start: 3px;
+ margin-inline-end: 9px;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio::after {
+ margin-inline-start: 2px;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio.AA::after,
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio.AAA::after {
+ color: #90E274;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit::before,
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio.FAIL::after {
+ display: inline-block;
+ width: 12px;
+ height: 12px;
+ content: "";
+ vertical-align: -2px;
+ background-position: center;
+ background-repeat: no-repeat;
+ -moz-context-properties: fill;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio.FAIL:after {
+ color: #E57180;
+ margin-inline-start: 3px;
+ background-image: url(chrome://devtools/skin/images/error-small.svg);
+ fill: var(--red-40);
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio.AA::after {
+ content: "AA\2713";
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio.AAA::after {
+ content: "AAA\2713";
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio-label,
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio-separator::before {
+ margin-inline-end: 3px;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-contrast-ratio-separator::before {
+ content: "-";
+ margin-inline-start: 3px;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit {
+ display: block;
+ padding-block-end: 5px;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit:last-child {
+ padding-block-end: 0;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit::before {
+ margin-inline-end: 4px;
+ background-image: none;
+ fill: currentColor;
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit.FAIL::before {
+ background-image: url(chrome://devtools/skin/images/error-small.svg);
+ fill: var(--red-40);
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit.WARNING::before {
+ background-image: url(chrome://devtools/skin/images/alert-small.svg);
+ fill: var(--yellow-60);
+}
+
+:-moz-native-anonymous .accessible-infobar-audit .accessible-audit.BEST_PRACTICES::before {
+ background-image: url(chrome://devtools/skin/images/info-small.svg);
+}
+
+:-moz-native-anonymous .accessible-infobar-name {
+ border-inline-start: 1px solid #5a6169;
+ margin-inline-start: 6px;
+ padding-inline-start: 6px;
+}
+
+/* Tabbing-order highlighter */
+
+:-moz-native-anonymous .tabbing-order-infobar {
+ min-width: unset;
+}
+
+:-moz-native-anonymous .tabbing-order .tabbing-order-infobar-container {
+ font-size:calc(var(--highlighter-font-size) + 2px);
+}
+
+:-moz-native-anonymous .tabbing-order .tabbing-order-bounds {
+ position: absolute;
+ display: block;
+ outline: 2px solid #000;
+ outline-offset: -2px;
+ -moz-outline-radius: 4px;
+}
+
+:-moz-native-anonymous .tabbing-order.focused .tabbing-order-bounds {
+ outline-color: var(--blue-60);
+}
+
+:-moz-native-anonymous .tabbing-order.focused .tabbing-order-infobar {
+ background-color: var(--blue-60);
+}
+
+:-moz-native-anonymous .tabbing-order.focused .tabbing-order-infobar-text {
+ text-decoration: underline;
+}
+
+:-moz-native-anonymous .tabbing-order.focused .tabbing-order-infobar:after {
+ border-top-color: var(--blue-60);
+ border-bottom-color: var(--blue-60);
+}
diff --git a/devtools/server/actors/highlighters.js b/devtools/server/actors/highlighters.js
new file mode 100644
index 0000000000..9677632af9
--- /dev/null
+++ b/devtools/server/actors/highlighters.js
@@ -0,0 +1,393 @@
+/* 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";
+
+const { Ci, Cu } = require("chrome");
+
+const ChromeUtils = require("ChromeUtils");
+const EventEmitter = require("devtools/shared/event-emitter");
+const protocol = require("devtools/shared/protocol");
+const { customHighlighterSpec } = require("devtools/shared/specs/highlighters");
+
+loader.lazyRequireGetter(
+ this,
+ "isXUL",
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+
+/**
+ * The registration mechanism for highlighters provides a quick way to
+ * have modular highlighters instead of a hard coded list.
+ */
+const highlighterTypes = new Map();
+
+/**
+ * Returns `true` if a highlighter for the given `typeName` is registered,
+ * `false` otherwise.
+ */
+const isTypeRegistered = typeName => highlighterTypes.has(typeName);
+exports.isTypeRegistered = isTypeRegistered;
+
+/**
+ * Registers a given constructor as highlighter, for the `typeName` given.
+ */
+const registerHighlighter = (typeName, modulePath) => {
+ if (highlighterTypes.has(typeName)) {
+ throw Error(`${typeName} is already registered.`);
+ }
+
+ highlighterTypes.set(typeName, modulePath);
+};
+
+/**
+ * CustomHighlighterActor is a generic Actor that instantiates a custom implementation of
+ * a highlighter class given its type name which must be registered in `highlighterTypes`.
+ * CustomHighlighterActor proxies calls to methods of the highlighter class instance:
+ * constructor(targetActor), show(node, options), hide(), destroy()
+ */
+exports.CustomHighlighterActor = protocol.ActorClassWithSpec(
+ customHighlighterSpec,
+ {
+ /**
+ * Create a highlighter instance given its typeName.
+ */
+ initialize: function(parent, typeName) {
+ protocol.Actor.prototype.initialize.call(this, null);
+
+ this._parent = parent;
+
+ const modulePath = highlighterTypes.get(typeName);
+ if (!modulePath) {
+ const list = [...highlighterTypes.keys()];
+
+ throw new Error(
+ `${typeName} isn't a valid highlighter class (${list})`
+ );
+ }
+
+ const constructor = require(modulePath)[typeName];
+ // The assumption is that custom highlighters either need the canvasframe
+ // container to append their elements and thus a non-XUL window or they have
+ // to define a static XULSupported flag that indicates that the highlighter
+ // supports XUL windows. Otherwise, bail out.
+ if (!isXUL(this._parent.targetActor.window) || constructor.XULSupported) {
+ this._highlighterEnv = new HighlighterEnvironment();
+ this._highlighterEnv.initFromTargetActor(parent.targetActor);
+ this._highlighter = new constructor(this._highlighterEnv);
+ if (this._highlighter.on) {
+ this._highlighter.on(
+ "highlighter-event",
+ this._onHighlighterEvent.bind(this)
+ );
+ }
+ } else {
+ throw new Error(
+ "Custom " + typeName + "highlighter cannot be created in a XUL window"
+ );
+ }
+ },
+
+ get conn() {
+ return this._parent && this._parent.conn;
+ },
+
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+ this.finalize();
+ this._parent = null;
+ },
+
+ release: function() {},
+
+ /**
+ * Get current instance of the highlighter object.
+ */
+ get instance() {
+ return this._highlighter;
+ },
+
+ /**
+ * Show the highlighter.
+ * This calls through to the highlighter instance's |show(node, options)|
+ * method.
+ *
+ * Most custom highlighters are made to highlight DOM nodes, hence the first
+ * NodeActor argument (NodeActor as in devtools/server/actor/inspector).
+ * Note however that some highlighters use this argument merely as a context
+ * node: The SelectorHighlighter for instance uses it as a base node to run the
+ * provided CSS selector on.
+ *
+ * @param {NodeActor} The node to be highlighted
+ * @param {Object} Options for the custom highlighter
+ * @return {Boolean} True, if the highlighter has been successfully shown
+ */
+ show: function(node, options) {
+ if (!this._highlighter) {
+ return null;
+ }
+
+ const rawNode = node?.rawNode;
+
+ return this._highlighter.show(rawNode, options);
+ },
+
+ /**
+ * Hide the highlighter if it was shown before
+ */
+ hide: function() {
+ if (this._highlighter) {
+ this._highlighter.hide();
+ }
+ },
+
+ /**
+ * Upon receiving an event from the highlighter, forward it to the client.
+ */
+ _onHighlighterEvent: function(data) {
+ this.emit("highlighter-event", data);
+ },
+
+ /**
+ * Destroy the custom highlighter implementation.
+ * This method is called automatically just before the actor is destroyed.
+ */
+ finalize: function() {
+ if (this._highlighter) {
+ if (this._highlighter.off) {
+ this._highlighter.off(
+ "highlighter-event",
+ this._onHighlighterEvent.bind(this)
+ );
+ }
+ this._highlighter.destroy();
+ this._highlighter = null;
+ }
+
+ if (this._highlighterEnv) {
+ this._highlighterEnv.destroy();
+ this._highlighterEnv = null;
+ }
+ },
+ }
+);
+
+/**
+ * The HighlighterEnvironment is an object that holds all the required data for
+ * highlighters to work: the window, docShell, event listener target, ...
+ * It also emits "will-navigate", "navigate" and "window-ready" events,
+ * similarly to the BrowsingContextTargetActor.
+ *
+ * It can be initialized either from a BrowsingContextTargetActor (which is the
+ * most frequent way of using it, since highlighters are initialized by
+ * CustomHighlighterActor, which has a targetActor reference).
+ * It can also be initialized just with a window object (which is
+ * useful for when a highlighter is used outside of the devtools server context.
+ */
+function HighlighterEnvironment() {
+ this.relayTargetActorWindowReady = this.relayTargetActorWindowReady.bind(
+ this
+ );
+ this.relayTargetActorNavigate = this.relayTargetActorNavigate.bind(this);
+ this.relayTargetActorWillNavigate = this.relayTargetActorWillNavigate.bind(
+ this
+ );
+
+ EventEmitter.decorate(this);
+}
+
+exports.HighlighterEnvironment = HighlighterEnvironment;
+
+HighlighterEnvironment.prototype = {
+ initFromTargetActor: function(targetActor) {
+ this._targetActor = targetActor;
+ this._targetActor.on("window-ready", this.relayTargetActorWindowReady);
+ this._targetActor.on("navigate", this.relayTargetActorNavigate);
+ this._targetActor.on("will-navigate", this.relayTargetActorWillNavigate);
+ },
+
+ initFromWindow: function(win) {
+ this._win = win;
+
+ // We need a progress listener to know when the window will navigate/has
+ // navigated.
+ const self = this;
+ this.listener = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIWebProgressListener",
+ "nsISupportsWeakReference",
+ ]),
+
+ onStateChange: function(progress, request, flag) {
+ const isStart = flag & Ci.nsIWebProgressListener.STATE_START;
+ const isStop = flag & Ci.nsIWebProgressListener.STATE_STOP;
+ const isWindow = flag & Ci.nsIWebProgressListener.STATE_IS_WINDOW;
+ const isDocument = flag & Ci.nsIWebProgressListener.STATE_IS_DOCUMENT;
+
+ if (progress.DOMWindow !== win) {
+ return;
+ }
+
+ if (isDocument && isStart) {
+ // One of the earliest events that tells us a new URI is being loaded
+ // in this window.
+ self.emit("will-navigate", {
+ window: win,
+ isTopLevel: true,
+ });
+ }
+ if (isWindow && isStop) {
+ self.emit("navigate", {
+ window: win,
+ isTopLevel: true,
+ });
+ }
+ },
+ };
+
+ this.webProgress.addProgressListener(
+ this.listener,
+ Ci.nsIWebProgress.NOTIFY_STATE_WINDOW |
+ Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT
+ );
+ },
+
+ get isInitialized() {
+ return this._win || this._targetActor;
+ },
+
+ get isXUL() {
+ return isXUL(this.window);
+ },
+
+ get window() {
+ if (!this.isInitialized) {
+ throw new Error(
+ "Initialize HighlighterEnvironment with a targetActor " +
+ "or window first"
+ );
+ }
+ const win = this._targetActor ? this._targetActor.window : this._win;
+
+ try {
+ return Cu.isDeadWrapper(win) ? null : win;
+ } catch (e) {
+ // win is null
+ return null;
+ }
+ },
+
+ get document() {
+ return this.window && this.window.document;
+ },
+
+ get docShell() {
+ return this.window && this.window.docShell;
+ },
+
+ get webProgress() {
+ return (
+ this.docShell &&
+ this.docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress)
+ );
+ },
+
+ /**
+ * Get the right target for listening to events on the page.
+ * - If the environment was initialized from a BrowsingContextTargetActor
+ * *and* if we're in the Browser Toolbox (to inspect Firefox Desktop): the
+ * targetActor is the RootActor, in which case, the window property can be
+ * used to listen to events.
+ * - With Firefox Desktop, the targetActor is a FrameTargetActor, and we use
+ * the chromeEventHandler which gives us a target we can use to listen to
+ * events, even from nested iframes.
+ * - If the environment was initialized from a window, we also use the
+ * chromeEventHandler.
+ */
+ get pageListenerTarget() {
+ if (this._targetActor && this._targetActor.isRootActor) {
+ return this.window;
+ }
+ return this.docShell && this.docShell.chromeEventHandler;
+ },
+
+ relayTargetActorWindowReady: function(data) {
+ this.emit("window-ready", data);
+ },
+
+ relayTargetActorNavigate: function(data) {
+ this.emit("navigate", data);
+ },
+
+ relayTargetActorWillNavigate: function(data) {
+ this.emit("will-navigate", data);
+ },
+
+ destroy: function() {
+ if (this._targetActor) {
+ this._targetActor.off("window-ready", this.relayTargetActorWindowReady);
+ this._targetActor.off("navigate", this.relayTargetActorNavigate);
+ this._targetActor.off("will-navigate", this.relayTargetActorWillNavigate);
+ }
+
+ // In case the environment was initialized from a window, we need to remove
+ // the progress listener.
+ if (this._win) {
+ try {
+ this.webProgress.removeProgressListener(this.listener);
+ } catch (e) {
+ // Which may fail in case the window was already destroyed.
+ }
+ }
+
+ this._targetActor = null;
+ this._win = null;
+ },
+};
+
+// This constant object is created to make the calls array more
+// readable. Otherwise, linting rules force some array defs to span 4
+// lines instead, which is much harder to parse.
+const HIGHLIGHTERS = {
+ accessible: "devtools/server/actors/highlighters/accessible",
+ boxModel: "devtools/server/actors/highlighters/box-model",
+ cssGrid: "devtools/server/actors/highlighters/css-grid",
+ cssTransform: "devtools/server/actors/highlighters/css-transform",
+ eyeDropper: "devtools/server/actors/highlighters/eye-dropper",
+ flexbox: "devtools/server/actors/highlighters/flexbox",
+ fonts: "devtools/server/actors/highlighters/fonts",
+ geometryEditor: "devtools/server/actors/highlighters/geometry-editor",
+ measuringTool: "devtools/server/actors/highlighters/measuring-tool",
+ pausedDebugger: "devtools/server/actors/highlighters/paused-debugger",
+ rulers: "devtools/server/actors/highlighters/rulers",
+ selector: "devtools/server/actors/highlighters/selector",
+ shapes: "devtools/server/actors/highlighters/shapes",
+ tabbingOrder: "devtools/server/actors/highlighters/tabbing-order",
+};
+
+// Each array in this array is called as register(arr[0], arr[1]).
+const registerCalls = [
+ ["AccessibleHighlighter", HIGHLIGHTERS.accessible],
+ ["BoxModelHighlighter", HIGHLIGHTERS.boxModel],
+ ["CssGridHighlighter", HIGHLIGHTERS.cssGrid],
+ ["CssTransformHighlighter", HIGHLIGHTERS.cssTransform],
+ ["EyeDropper", HIGHLIGHTERS.eyeDropper],
+ ["FlexboxHighlighter", HIGHLIGHTERS.flexbox],
+ ["FontsHighlighter", HIGHLIGHTERS.fonts],
+ ["GeometryEditorHighlighter", HIGHLIGHTERS.geometryEditor],
+ ["MeasuringToolHighlighter", HIGHLIGHTERS.measuringTool],
+ ["PausedDebuggerOverlay", HIGHLIGHTERS.pausedDebugger],
+ ["RulersHighlighter", HIGHLIGHTERS.rulers],
+ ["SelectorHighlighter", HIGHLIGHTERS.selector],
+ ["ShapesHighlighter", HIGHLIGHTERS.shapes],
+ ["TabbingOrderHighlighter", HIGHLIGHTERS.tabbingOrder],
+];
+
+// Register each highlighter above.
+registerCalls.forEach(arr => {
+ registerHighlighter(arr[0], arr[1]);
+});
diff --git a/devtools/server/actors/highlighters/accessible.js b/devtools/server/actors/highlighters/accessible.js
new file mode 100644
index 0000000000..07d99411cc
--- /dev/null
+++ b/devtools/server/actors/highlighters/accessible.js
@@ -0,0 +1,387 @@
+/* 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";
+
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const {
+ CanvasFrameAnonymousContentHelper,
+ isNodeValid,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ TEXT_NODE,
+ DOCUMENT_NODE,
+} = require("devtools/shared/dom-node-constants");
+const {
+ getCurrentZoom,
+ setIgnoreLayoutChanges,
+} = require("devtools/shared/layout/utils");
+
+loader.lazyRequireGetter(
+ this,
+ ["getBounds", "getBoundsXUL", "Infobar"],
+ "devtools/server/actors/highlighters/utils/accessibility",
+ true
+);
+
+/**
+ * The AccessibleHighlighter draws the bounds of an accessible object.
+ *
+ * Usage example:
+ *
+ * let h = new AccessibleHighlighter(env);
+ * h.show(node, { x, y, w, h, [duration] });
+ * h.hide();
+ * h.destroy();
+ *
+ * @param {Number} options.x
+ * X coordinate of the top left corner of the accessible object
+ * @param {Number} options.y
+ * Y coordinate of the top left corner of the accessible object
+ * @param {Number} options.w
+ * Width of the the accessible object
+ * @param {Number} options.h
+ * Height of the the accessible object
+ * @param {Number} options.duration
+ * Duration of time that the highlighter should be shown.
+ * @param {String|null} options.name
+ * Name of the the accessible object
+ * @param {String} options.role
+ * Role of the the accessible object
+ *
+ * Structure:
+ * <div class="highlighter-container" aria-hidden="true">
+ * <div class="accessible-root">
+ * <svg class="accessible-elements" hidden="true">
+ * <path class="accessible-bounds" points="..." />
+ * </svg>
+ * <div class="accessible-infobar-container">
+ * <div class="accessible-infobar">
+ * <div class="accessible-infobar-text">
+ * <span class="accessible-infobar-role">Accessible Role</span>
+ * <span class="accessible-infobar-name">Accessible Name</span>
+ * </div>
+ * </div>
+ * </div>
+ * </div>
+ * </div>
+ */
+class AccessibleHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+ this.ID_CLASS_PREFIX = "accessible-";
+ this.accessibleInfobar = new Infobar(this);
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ this.onPageHide = this.onPageHide.bind(this);
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ this.highlighterEnv.on("will-navigate", this.onWillNavigate);
+
+ this.pageListenerTarget = highlighterEnv.pageListenerTarget;
+ this.pageListenerTarget.addEventListener("pagehide", this.onPageHide);
+ }
+
+ /**
+ * Static getter that indicates that AccessibleHighlighter supports
+ * highlighting in XUL windows.
+ */
+ static get XULSupported() {
+ return true;
+ }
+
+ /**
+ * Build highlighter markup.
+ *
+ * @return {Object} Container element for the highlighter markup.
+ */
+ _buildMarkup() {
+ const container = this.markup.createNode({
+ attributes: {
+ class: "highlighter-container",
+ "aria-hidden": "true",
+ },
+ });
+
+ const root = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the SVG element.
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: root,
+ attributes: {
+ id: "elements",
+ width: "100%",
+ height: "100%",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: svg,
+ attributes: {
+ class: "bounds",
+ id: "bounds",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the accessible's infobar markup.
+ this.accessibleInfobar.buildMarkup(root);
+
+ return container;
+ }
+
+ /**
+ * Destroy the nodes. Remove listeners.
+ */
+ destroy() {
+ if (this._highlightTimer) {
+ clearTimeout(this._highlightTimer);
+ this._highlightTimer = null;
+ }
+
+ this.highlighterEnv.off("will-navigate", this.onWillNavigate);
+ this.pageListenerTarget.removeEventListener("pagehide", this.onPageHide);
+ this.pageListenerTarget = null;
+
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+
+ this.accessibleInfobar.destroy();
+ this.accessibleInfobar = null;
+ this.markup.destroy();
+ }
+
+ /**
+ * Find an element in highlighter markup.
+ *
+ * @param {String} id
+ * Highlighter markup elemet id attribute.
+ * @return {DOMNode} Element in the highlighter markup.
+ */
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ /**
+ * Check if node is a valid element, document or text node.
+ *
+ * @override AutoRefreshHighlighter.prototype._isNodeValid
+ * @param {DOMNode} node
+ * The node to highlight.
+ * @return {Boolean} whether or not node is valid.
+ */
+ _isNodeValid(node) {
+ return (
+ super._isNodeValid(node) ||
+ isNodeValid(node, TEXT_NODE) ||
+ isNodeValid(node, DOCUMENT_NODE)
+ );
+ }
+
+ /**
+ * Show the highlighter on a given accessible.
+ *
+ * @return {Boolean} True if accessible is highlighted, false otherwise.
+ */
+ _show() {
+ if (this._highlightTimer) {
+ clearTimeout(this._highlightTimer);
+ this._highlightTimer = null;
+ }
+
+ const { duration } = this.options;
+ const shown = this._update();
+ if (shown) {
+ this.emit("highlighter-event", { options: this.options, type: "shown" });
+ if (duration) {
+ this._highlightTimer = setTimeout(() => {
+ this.hide();
+ }, duration);
+ }
+ }
+
+ return shown;
+ }
+
+ /**
+ * Update and show accessible bounds for a current accessible.
+ *
+ * @return {Boolean} True if accessible is highlighted, false otherwise.
+ */
+ _update() {
+ let shown = false;
+ setIgnoreLayoutChanges(true);
+
+ if (this._updateAccessibleBounds()) {
+ this._showAccessibleBounds();
+
+ this.accessibleInfobar.show();
+
+ shown = true;
+ } else {
+ // Nothing to highlight (0px rectangle like a <script> tag for instance)
+ this.hide();
+ }
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+
+ return shown;
+ }
+
+ /**
+ * Hide the highlighter.
+ */
+ _hide() {
+ setIgnoreLayoutChanges(true);
+ this._hideAccessibleBounds();
+ this.accessibleInfobar.hide();
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ /**
+ * Public API method to temporarily hide accessible bounds for things like
+ * color contrast calculation.
+ */
+ hideAccessibleBounds() {
+ if (this.getElement("elements").hasAttribute("hidden")) {
+ return;
+ }
+
+ this._hideAccessibleBounds();
+ this._shouldRestoreBoundsVisibility = true;
+ }
+
+ /**
+ * Public API method to show accessible bounds in case they were temporarily
+ * hidden.
+ */
+ showAccessibleBounds() {
+ if (this._shouldRestoreBoundsVisibility) {
+ this._showAccessibleBounds();
+ }
+ }
+
+ /**
+ * Hide the accessible bounds container.
+ */
+ _hideAccessibleBounds() {
+ this._shouldRestoreBoundsVisibility = null;
+ setIgnoreLayoutChanges(true);
+ this.getElement("elements").setAttribute("hidden", "true");
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ /**
+ * Show the accessible bounds container.
+ */
+ _showAccessibleBounds() {
+ this._shouldRestoreBoundsVisibility = null;
+ if (!this.currentNode || !this.highlighterEnv.window) {
+ return;
+ }
+
+ setIgnoreLayoutChanges(true);
+ this.getElement("elements").removeAttribute("hidden");
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ /**
+ * Get current accessible bounds.
+ *
+ * @return {Object|null} Returns, if available, positioning and bounds
+ * information for the accessible object.
+ */
+ get _bounds() {
+ let { win, options } = this;
+ let getBoundsFn = getBounds;
+ if (this.options.isXUL) {
+ // Zoom level for the top level browser window does not change and only
+ // inner frames do. So we need to get the zoom level of the current node's
+ // parent window.
+ let zoom = getCurrentZoom(this.currentNode);
+ zoom *= zoom;
+ options = { ...options, zoom };
+ getBoundsFn = getBoundsXUL;
+ win = this.win.parent.ownerGlobal;
+ }
+
+ return getBoundsFn(win, options);
+ }
+
+ /**
+ * Update accessible bounds for a current accessible. Re-draw highlighter
+ * markup.
+ *
+ * @return {Boolean} True if accessible is highlighted, false otherwise.
+ */
+ _updateAccessibleBounds() {
+ const bounds = this._bounds;
+ if (!bounds) {
+ this._hide();
+ return false;
+ }
+
+ const boundsEl = this.getElement("bounds");
+ const { left, right, top, bottom } = bounds;
+ const path = `M${left},${top} L${right},${top} L${right},${bottom} L${left},${bottom}`;
+ boundsEl.setAttribute("d", path);
+
+ // Un-zoom the root wrapper if the page was zoomed.
+ const rootId = this.ID_CLASS_PREFIX + "elements";
+ this.markup.scaleRootElement(this.currentNode, rootId);
+
+ return true;
+ }
+
+ /**
+ * Hide highlighter on page hide.
+ */
+ onPageHide({ target }) {
+ // If a pagehide event is triggered for current window's highlighter, hide
+ // the highlighter.
+ if (target.defaultView === this.win) {
+ this.hide();
+ }
+ }
+
+ /**
+ * Hide highlighter on navigation.
+ */
+ onWillNavigate({ isTopLevel }) {
+ if (isTopLevel) {
+ this.hide();
+ }
+ }
+}
+
+exports.AccessibleHighlighter = AccessibleHighlighter;
diff --git a/devtools/server/actors/highlighters/auto-refresh.js b/devtools/server/actors/highlighters/auto-refresh.js
new file mode 100644
index 0000000000..d927471b96
--- /dev/null
+++ b/devtools/server/actors/highlighters/auto-refresh.js
@@ -0,0 +1,318 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const EventEmitter = require("devtools/shared/event-emitter");
+const {
+ isNodeValid,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ getAdjustedQuads,
+ getWindowDimensions,
+} = require("devtools/shared/layout/utils");
+
+// Note that the order of items in this array is important because it is used
+// for drawing the BoxModelHighlighter's path elements correctly.
+const BOX_MODEL_REGIONS = ["margin", "border", "padding", "content"];
+const QUADS_PROPS = ["p1", "p2", "p3", "p4"];
+
+function arePointsDifferent(pointA, pointB) {
+ return (
+ Math.abs(pointA.x - pointB.x) >= 0.5 ||
+ Math.abs(pointA.y - pointB.y) >= 0.5 ||
+ Math.abs(pointA.w - pointB.w) >= 0.5
+ );
+}
+
+function areQuadsDifferent(oldQuads, newQuads) {
+ for (const region of BOX_MODEL_REGIONS) {
+ const { length } = oldQuads[region];
+
+ if (length !== newQuads[region].length) {
+ return true;
+ }
+
+ for (let i = 0; i < length; i++) {
+ for (const prop of QUADS_PROPS) {
+ const oldPoint = oldQuads[region][i][prop];
+ const newPoint = newQuads[region][i][prop];
+
+ if (arePointsDifferent(oldPoint, newPoint)) {
+ return true;
+ }
+ }
+ }
+ }
+
+ return false;
+}
+
+/**
+ * Base class for auto-refresh-on-change highlighters. Sub classes will have a
+ * chance to update whenever the current node's geometry changes.
+ *
+ * Sub classes must implement the following methods:
+ * _show: called when the highlighter should be shown,
+ * _hide: called when the highlighter should be hidden,
+ * _update: called while the highlighter is shown and the geometry of the
+ * current node changes.
+ *
+ * Sub classes will have access to the following properties:
+ * - this.currentNode: the node to be shown
+ * - this.currentQuads: all of the node's box model region quads
+ * - this.win: the current window
+ *
+ * Emits the following events:
+ * - shown
+ * - hidden
+ * - updated
+ */
+function AutoRefreshHighlighter(highlighterEnv) {
+ EventEmitter.decorate(this);
+
+ this.highlighterEnv = highlighterEnv;
+
+ this.currentNode = null;
+ this.currentQuads = {};
+
+ this._winDimensions = getWindowDimensions(this.win);
+ this._scroll = { x: this.win.pageXOffset, y: this.win.pageYOffset };
+
+ this.update = this.update.bind(this);
+}
+
+AutoRefreshHighlighter.prototype = {
+ _ignoreZoom: false,
+ _ignoreScroll: false,
+
+ /**
+ * Window corresponding to the current highlighterEnv.
+ */
+ get win() {
+ if (!this.highlighterEnv) {
+ return null;
+ }
+ return this.highlighterEnv.window;
+ },
+
+ /* Window containing the target content. */
+ get contentWindow() {
+ return this.win;
+ },
+
+ /**
+ * Show the highlighter on a given node
+ * @param {DOMNode} node
+ * @param {Object} options
+ * Object used for passing options
+ */
+ show: function(node, options = {}) {
+ const isSameNode = node === this.currentNode;
+ const isSameOptions = this._isSameOptions(options);
+
+ if (!this._isNodeValid(node) || (isSameNode && isSameOptions)) {
+ return false;
+ }
+
+ this.options = options;
+
+ this._stopRefreshLoop();
+ this.currentNode = node;
+ this._updateAdjustedQuads();
+ this._startRefreshLoop();
+
+ const shown = this._show();
+ if (shown) {
+ this.emit("shown");
+ }
+ return shown;
+ },
+
+ /**
+ * Hide the highlighter
+ */
+ hide: function() {
+ if (!this.currentNode || !this.highlighterEnv.window) {
+ return;
+ }
+
+ this._hide();
+ this._stopRefreshLoop();
+ this.currentNode = null;
+ this.currentQuads = {};
+ this.options = null;
+
+ this.emit("hidden");
+ },
+
+ /**
+ * Whether the current node is valid for this highlighter type.
+ * This is implemented by default to check if the node is an element node. Highlighter
+ * sub-classes should override this method if they want to highlight other node types.
+ * @param {DOMNode} node
+ * @return {Boolean}
+ */
+ _isNodeValid: function(node) {
+ return isNodeValid(node);
+ },
+
+ /**
+ * Are the provided options the same as the currently stored options?
+ * Returns false if there are no options stored currently.
+ */
+ _isSameOptions: function(options) {
+ if (!this.options) {
+ return false;
+ }
+
+ const keys = Object.keys(options);
+
+ if (keys.length !== Object.keys(this.options).length) {
+ return false;
+ }
+
+ for (const key of keys) {
+ if (this.options[key] !== options[key]) {
+ return false;
+ }
+ }
+
+ return true;
+ },
+
+ /**
+ * Update the stored box quads by reading the current node's box quads.
+ */
+ _updateAdjustedQuads: function() {
+ this.currentQuads = {};
+
+ for (const region of BOX_MODEL_REGIONS) {
+ this.currentQuads[region] = getAdjustedQuads(
+ this.contentWindow,
+ this.currentNode,
+ region,
+ { ignoreScroll: this._ignoreScroll, ignoreZoom: this._ignoreZoom }
+ );
+ }
+ },
+
+ /**
+ * Update the knowledge we have of the current node's boxquads and return true
+ * if any of the points x/y or bounds have change since.
+ * @return {Boolean}
+ */
+ _hasMoved: function() {
+ const oldQuads = this.currentQuads;
+ this._updateAdjustedQuads();
+
+ return areQuadsDifferent(oldQuads, this.currentQuads);
+ },
+
+ /**
+ * Update the knowledge we have of the current window's scrolling offset, both
+ * horizontal and vertical, and return `true` if they have changed since.
+ * @return {Boolean}
+ */
+ _hasWindowScrolled: function() {
+ if (!this.win) {
+ return false;
+ }
+
+ const { pageXOffset, pageYOffset } = this.win;
+ const hasChanged =
+ this._scroll.x !== pageXOffset || this._scroll.y !== pageYOffset;
+
+ this._scroll = { x: pageXOffset, y: pageYOffset };
+
+ return hasChanged;
+ },
+
+ /**
+ * Update the knowledge we have of the current window's dimensions and return `true`
+ * if they have changed since.
+ * @return {Boolean}
+ */
+ _haveWindowDimensionsChanged: function() {
+ const { width, height } = getWindowDimensions(this.win);
+ const haveChanged =
+ this._winDimensions.width !== width ||
+ this._winDimensions.height !== height;
+
+ this._winDimensions = { width, height };
+ return haveChanged;
+ },
+
+ /**
+ * Update the highlighter if the node has moved since the last update.
+ */
+ update: function() {
+ if (
+ !this._isNodeValid(this.currentNode) ||
+ (!this._hasMoved() && !this._haveWindowDimensionsChanged())
+ ) {
+ // At this point we're not calling the `_update` method. However, if the window has
+ // scrolled, we want to invoke `_scrollUpdate`.
+ if (this._hasWindowScrolled()) {
+ this._scrollUpdate();
+ }
+
+ return;
+ }
+
+ this._update();
+ this.emit("updated");
+ },
+
+ _show: function() {
+ // To be implemented by sub classes
+ // When called, sub classes should actually show the highlighter for
+ // this.currentNode, potentially using options in this.options
+ throw new Error("Custom highlighter class had to implement _show method");
+ },
+
+ _update: function() {
+ // To be implemented by sub classes
+ // When called, sub classes should update the highlighter shown for
+ // this.currentNode
+ // This is called as a result of a page zoom or repaint
+ throw new Error("Custom highlighter class had to implement _update method");
+ },
+
+ _scrollUpdate: function() {
+ // Can be implemented by sub classes
+ // When called, sub classes can upate the highlighter shown for
+ // this.currentNode
+ // This is called as a result of a page scroll
+ },
+
+ _hide: function() {
+ // To be implemented by sub classes
+ // When called, sub classes should actually hide the highlighter
+ throw new Error("Custom highlighter class had to implement _hide method");
+ },
+
+ _startRefreshLoop: function() {
+ const win = this.currentNode.ownerGlobal;
+ this.rafID = win.requestAnimationFrame(this._startRefreshLoop.bind(this));
+ this.rafWin = win;
+ this.update();
+ },
+
+ _stopRefreshLoop: function() {
+ if (this.rafID && !Cu.isDeadWrapper(this.rafWin)) {
+ this.rafWin.cancelAnimationFrame(this.rafID);
+ }
+ this.rafID = this.rafWin = null;
+ },
+
+ destroy: function() {
+ this.hide();
+
+ this.highlighterEnv = null;
+ this.currentNode = null;
+ },
+};
+exports.AutoRefreshHighlighter = AutoRefreshHighlighter;
diff --git a/devtools/server/actors/highlighters/box-model.js b/devtools/server/actors/highlighters/box-model.js
new file mode 100644
index 0000000000..055672d4a0
--- /dev/null
+++ b/devtools/server/actors/highlighters/box-model.js
@@ -0,0 +1,875 @@
+/* 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";
+
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const {
+ CanvasFrameAnonymousContentHelper,
+ getBindingElementAndPseudo,
+ hasPseudoClassLock,
+ isNodeValid,
+ moveInfobar,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const { PSEUDO_CLASSES } = require("devtools/shared/css/constants");
+const {
+ getCurrentZoom,
+ setIgnoreLayoutChanges,
+} = require("devtools/shared/layout/utils");
+const {
+ getNodeDisplayName,
+ getNodeGridFlexType,
+} = require("devtools/server/actors/inspector/utils");
+const nodeConstants = require("devtools/shared/dom-node-constants");
+const { LocalizationHelper } = require("devtools/shared/l10n");
+const STRINGS_URI = "devtools/shared/locales/highlighters.properties";
+const L10N = new LocalizationHelper(STRINGS_URI);
+
+// Note that the order of items in this array is important because it is used
+// for drawing the BoxModelHighlighter's path elements correctly.
+const BOX_MODEL_REGIONS = ["margin", "border", "padding", "content"];
+const BOX_MODEL_SIDES = ["top", "right", "bottom", "left"];
+// Width of boxmodelhighlighter guides
+const GUIDE_STROKE_WIDTH = 1;
+
+/**
+ * The BoxModelHighlighter draws the box model regions on top of a node.
+ * If the node is a block box, then each region will be displayed as 1 polygon.
+ * If the node is an inline box though, each region may be represented by 1 or
+ * more polygons, depending on how many line boxes the inline element has.
+ *
+ * Usage example:
+ *
+ * let h = new BoxModelHighlighter(env);
+ * h.show(node, options);
+ * h.hide();
+ * h.destroy();
+ *
+ * @param {String} options.region
+ * Specifies the region that the guides should outline:
+ * "content" (default), "padding", "border" or "margin".
+ * @param {Boolean} options.hideGuides
+ * Defaults to false
+ * @param {Boolean} options.hideInfoBar
+ * Defaults to false
+ * @param {String} options.showOnly
+ * If set, only this region will be highlighted. Use with onlyRegionArea
+ * to only highlight the area of the region:
+ * "content", "padding", "border" or "margin"
+ * @param {Boolean} options.onlyRegionArea
+ * This can be set to true to make each region's box only highlight the
+ * area of the corresponding region rather than the area of nested
+ * regions too. This is useful when used with showOnly.
+ *
+ * Structure:
+ * <div class="highlighter-container" aria-hidden="true">
+ * <div class="box-model-root">
+ * <svg class="box-model-elements" hidden="true">
+ * <g class="box-model-regions">
+ * <path class="box-model-margin" points="..." />
+ * <path class="box-model-border" points="..." />
+ * <path class="box-model-padding" points="..." />
+ * <path class="box-model-content" points="..." />
+ * </g>
+ * <line class="box-model-guide-top" x1="..." y1="..." x2="..." y2="..." />
+ * <line class="box-model-guide-right" x1="..." y1="..." x2="..." y2="..." />
+ * <line class="box-model-guide-bottom" x1="..." y1="..." x2="..." y2="..." />
+ * <line class="box-model-guide-left" x1="..." y1="..." x2="..." y2="..." />
+ * </svg>
+ * <div class="box-model-infobar-container">
+ * <div class="box-model-infobar-arrow highlighter-infobar-arrow-top" />
+ * <div class="box-model-infobar">
+ * <div class="box-model-infobar-text" align="center">
+ * <span class="box-model-infobar-tagname">Node name</span>
+ * <span class="box-model-infobar-id">Node id</span>
+ * <span class="box-model-infobar-classes">.someClass</span>
+ * <span class="box-model-infobar-pseudo-classes">:hover</span>
+ * <span class="box-model-infobar-grid-type">Grid Type</span>
+ * <span class="box-model-infobar-flex-type">Flex Type</span>
+ * </div>
+ * </div>
+ * <div class="box-model-infobar-arrow box-model-infobar-arrow-bottom"/>
+ * </div>
+ * </div>
+ * </div>
+ */
+class BoxModelHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+
+ this.ID_CLASS_PREFIX = "box-model-";
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ this.onPageHide = this.onPageHide.bind(this);
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ this.highlighterEnv.on("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = highlighterEnv;
+ pageListenerTarget.addEventListener("pagehide", this.onPageHide);
+ }
+
+ /**
+ * Static getter that indicates that BoxModelHighlighter supports
+ * highlighting in XUL windows.
+ */
+ static get XULSupported() {
+ return true;
+ }
+
+ _buildMarkup() {
+ const highlighterContainer = this.markup.anonymousContentDocument.createElement(
+ "div"
+ );
+ highlighterContainer.className = "highlighter-container box-model";
+ // We need a better solution for how to handle the highlighter from the
+ // accessibility standpoint. For now, in order to avoid displaying it in the
+ // accessibility tree lets hide it altogether. See bug 1598667 for more
+ // context.
+ highlighterContainer.setAttribute("aria-hidden", "true");
+
+ // Build the root wrapper, used to adapt to the page zoom.
+ const rootWrapper = this.markup.createNode({
+ parent: highlighterContainer,
+ attributes: {
+ id: "root",
+ class: "root",
+ role: "presentation",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Building the SVG element with its polygons and lines
+
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: rootWrapper,
+ attributes: {
+ id: "elements",
+ width: "100%",
+ height: "100%",
+ hidden: "true",
+ role: "presentation",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const regions = this.markup.createSVGNode({
+ nodeType: "g",
+ parent: svg,
+ attributes: {
+ class: "regions",
+ role: "presentation",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ for (const region of BOX_MODEL_REGIONS) {
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: regions,
+ attributes: {
+ class: region,
+ id: region,
+ role: "presentation",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ }
+
+ for (const side of BOX_MODEL_SIDES) {
+ this.markup.createSVGNode({
+ nodeType: "line",
+ parent: svg,
+ attributes: {
+ class: "guide-" + side,
+ id: "guide-" + side,
+ "stroke-width": GUIDE_STROKE_WIDTH,
+ role: "presentation",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ }
+
+ // Building the nodeinfo bar markup
+
+ const infobarContainer = this.markup.createNode({
+ parent: rootWrapper,
+ attributes: {
+ class: "infobar-container",
+ id: "infobar-container",
+ position: "top",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const infobar = this.markup.createNode({
+ parent: infobarContainer,
+ attributes: {
+ class: "infobar",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const texthbox = this.markup.createNode({
+ parent: infobar,
+ attributes: {
+ class: "infobar-text",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-tagname",
+ id: "infobar-tagname",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-id",
+ id: "infobar-id",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-classes",
+ id: "infobar-classes",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-pseudo-classes",
+ id: "infobar-pseudo-classes",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-dimensions",
+ id: "infobar-dimensions",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-grid-type",
+ id: "infobar-grid-type",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: texthbox,
+ attributes: {
+ class: "infobar-flex-type",
+ id: "infobar-flex-type",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ return highlighterContainer;
+ }
+
+ /**
+ * Destroy the nodes. Remove listeners.
+ */
+ destroy() {
+ this.highlighterEnv.off("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = this.highlighterEnv;
+ if (pageListenerTarget) {
+ pageListenerTarget.removeEventListener("pagehide", this.onPageHide);
+ }
+
+ this.markup.destroy();
+
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+ }
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ /**
+ * Override the AutoRefreshHighlighter's _isNodeValid method to also return true for
+ * text nodes since these can also be highlighted.
+ * @param {DOMNode} node
+ * @return {Boolean}
+ */
+ _isNodeValid(node) {
+ return (
+ node && (isNodeValid(node) || isNodeValid(node, nodeConstants.TEXT_NODE))
+ );
+ }
+
+ /**
+ * Show the highlighter on a given node
+ */
+ _show() {
+ if (!BOX_MODEL_REGIONS.includes(this.options.region)) {
+ this.options.region = "content";
+ }
+
+ const shown = this._update();
+ this._trackMutations();
+ return shown;
+ }
+
+ /**
+ * Track the current node markup mutations so that the node info bar can be
+ * updated to reflects the node's attributes
+ */
+ _trackMutations() {
+ if (isNodeValid(this.currentNode)) {
+ const win = this.currentNode.ownerGlobal;
+ this.currentNodeObserver = new win.MutationObserver(this.update);
+ this.currentNodeObserver.observe(this.currentNode, { attributes: true });
+ }
+ }
+
+ _untrackMutations() {
+ if (isNodeValid(this.currentNode) && this.currentNodeObserver) {
+ this.currentNodeObserver.disconnect();
+ this.currentNodeObserver = null;
+ }
+ }
+
+ /**
+ * Update the highlighter on the current highlighted node (the one that was
+ * passed as an argument to show(node)).
+ * Should be called whenever node size or attributes change
+ */
+ _update() {
+ const node = this.currentNode;
+ let shown = false;
+ setIgnoreLayoutChanges(true);
+
+ if (this._updateBoxModel()) {
+ // Show the infobar only if configured to do so and the node is an element or a text
+ // node.
+ if (
+ !this.options.hideInfoBar &&
+ (node.nodeType === node.ELEMENT_NODE ||
+ node.nodeType === node.TEXT_NODE)
+ ) {
+ this._showInfobar();
+ } else {
+ this._hideInfobar();
+ }
+ this._showBoxModel();
+ shown = true;
+ } else {
+ // Nothing to highlight (0px rectangle like a <script> tag for instance)
+ this._hide();
+ }
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+
+ return shown;
+ }
+
+ _scrollUpdate() {
+ this._moveInfobar();
+ }
+
+ /**
+ * Hide the highlighter, the outline and the infobar.
+ */
+ _hide() {
+ setIgnoreLayoutChanges(true);
+
+ this._untrackMutations();
+ this._hideBoxModel();
+ this._hideInfobar();
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ /**
+ * Hide the infobar
+ */
+ _hideInfobar() {
+ this.getElement("infobar-container").setAttribute("hidden", "true");
+ }
+
+ /**
+ * Show the infobar
+ */
+ _showInfobar() {
+ this.getElement("infobar-container").removeAttribute("hidden");
+ this._updateInfobar();
+ }
+
+ /**
+ * Hide the box model
+ */
+ _hideBoxModel() {
+ this.getElement("elements").setAttribute("hidden", "true");
+ }
+
+ /**
+ * Show the box model
+ */
+ _showBoxModel() {
+ this.getElement("elements").removeAttribute("hidden");
+ }
+
+ /**
+ * Calculate an outer quad based on the quads returned by getAdjustedQuads.
+ * The BoxModelHighlighter may highlight more than one boxes, so in this case
+ * create a new quad that "contains" all of these quads.
+ * This is useful to position the guides and infobar.
+ * This may happen if the BoxModelHighlighter is used to highlight an inline
+ * element that spans line breaks.
+ * @param {String} region The box-model region to get the outer quad for.
+ * @return {Object} A quad-like object {p1,p2,p3,p4,bounds}
+ */
+ _getOuterQuad(region) {
+ const quads = this.currentQuads[region];
+ if (!quads || !quads.length) {
+ return null;
+ }
+
+ const quad = {
+ p1: { x: Infinity, y: Infinity },
+ p2: { x: -Infinity, y: Infinity },
+ p3: { x: -Infinity, y: -Infinity },
+ p4: { x: Infinity, y: -Infinity },
+ bounds: {
+ bottom: -Infinity,
+ height: 0,
+ left: Infinity,
+ right: -Infinity,
+ top: Infinity,
+ width: 0,
+ x: 0,
+ y: 0,
+ },
+ };
+
+ for (const q of quads) {
+ quad.p1.x = Math.min(quad.p1.x, q.p1.x);
+ quad.p1.y = Math.min(quad.p1.y, q.p1.y);
+ quad.p2.x = Math.max(quad.p2.x, q.p2.x);
+ quad.p2.y = Math.min(quad.p2.y, q.p2.y);
+ quad.p3.x = Math.max(quad.p3.x, q.p3.x);
+ quad.p3.y = Math.max(quad.p3.y, q.p3.y);
+ quad.p4.x = Math.min(quad.p4.x, q.p4.x);
+ quad.p4.y = Math.max(quad.p4.y, q.p4.y);
+
+ quad.bounds.bottom = Math.max(quad.bounds.bottom, q.bounds.bottom);
+ quad.bounds.top = Math.min(quad.bounds.top, q.bounds.top);
+ quad.bounds.left = Math.min(quad.bounds.left, q.bounds.left);
+ quad.bounds.right = Math.max(quad.bounds.right, q.bounds.right);
+ }
+ quad.bounds.x = quad.bounds.left;
+ quad.bounds.y = quad.bounds.top;
+ quad.bounds.width = quad.bounds.right - quad.bounds.left;
+ quad.bounds.height = quad.bounds.bottom - quad.bounds.top;
+
+ return quad;
+ }
+
+ /**
+ * Update the box model as per the current node.
+ *
+ * @return {boolean}
+ * True if the current node has a box model to be highlighted
+ */
+ _updateBoxModel() {
+ const options = this.options;
+ options.region = options.region || "content";
+
+ if (!this._nodeNeedsHighlighting()) {
+ this._hideBoxModel();
+ return false;
+ }
+
+ for (let i = 0; i < BOX_MODEL_REGIONS.length; i++) {
+ const boxType = BOX_MODEL_REGIONS[i];
+ const nextBoxType = BOX_MODEL_REGIONS[i + 1];
+ const box = this.getElement(boxType);
+
+ // Highlight all quads for this region by setting the "d" attribute of the
+ // corresponding <path>.
+ const path = [];
+ for (let j = 0; j < this.currentQuads[boxType].length; j++) {
+ const boxQuad = this.currentQuads[boxType][j];
+ const nextBoxQuad = this.currentQuads[nextBoxType]
+ ? this.currentQuads[nextBoxType][j]
+ : null;
+ path.push(this._getBoxPathCoordinates(boxQuad, nextBoxQuad));
+ }
+
+ box.setAttribute("d", path.join(" "));
+ box.removeAttribute("faded");
+
+ // If showOnly is defined, either hide the other regions, or fade them out
+ // if onlyRegionArea is set too.
+ if (options.showOnly && options.showOnly !== boxType) {
+ if (options.onlyRegionArea) {
+ box.setAttribute("faded", "true");
+ } else {
+ box.removeAttribute("d");
+ }
+ }
+
+ if (boxType === options.region && !options.hideGuides) {
+ this._showGuides(boxType);
+ } else if (options.hideGuides) {
+ this._hideGuides();
+ }
+ }
+
+ // Un-zoom the root wrapper if the page was zoomed.
+ const rootId = this.ID_CLASS_PREFIX + "elements";
+ this.markup.scaleRootElement(this.currentNode, rootId);
+
+ return true;
+ }
+
+ _getBoxPathCoordinates(boxQuad, nextBoxQuad) {
+ const { p1, p2, p3, p4 } = boxQuad;
+
+ let path;
+ if (!nextBoxQuad || !this.options.onlyRegionArea) {
+ // If this is the content box (inner-most box) or if we're not being asked
+ // to highlight only region areas, then draw a simple rectangle.
+ path =
+ "M" +
+ p1.x +
+ "," +
+ p1.y +
+ " " +
+ "L" +
+ p2.x +
+ "," +
+ p2.y +
+ " " +
+ "L" +
+ p3.x +
+ "," +
+ p3.y +
+ " " +
+ "L" +
+ p4.x +
+ "," +
+ p4.y;
+ } else {
+ // Otherwise, just draw the region itself, not a filled rectangle.
+ const { p1: np1, p2: np2, p3: np3, p4: np4 } = nextBoxQuad;
+ path =
+ "M" +
+ p1.x +
+ "," +
+ p1.y +
+ " " +
+ "L" +
+ p2.x +
+ "," +
+ p2.y +
+ " " +
+ "L" +
+ p3.x +
+ "," +
+ p3.y +
+ " " +
+ "L" +
+ p4.x +
+ "," +
+ p4.y +
+ " " +
+ "L" +
+ p1.x +
+ "," +
+ p1.y +
+ " " +
+ "L" +
+ np1.x +
+ "," +
+ np1.y +
+ " " +
+ "L" +
+ np4.x +
+ "," +
+ np4.y +
+ " " +
+ "L" +
+ np3.x +
+ "," +
+ np3.y +
+ " " +
+ "L" +
+ np2.x +
+ "," +
+ np2.y +
+ " " +
+ "L" +
+ np1.x +
+ "," +
+ np1.y;
+ }
+
+ return path;
+ }
+
+ /**
+ * Can the current node be highlighted? Does it have quads.
+ * @return {Boolean}
+ */
+ _nodeNeedsHighlighting() {
+ return (
+ this.currentQuads.margin.length ||
+ this.currentQuads.border.length ||
+ this.currentQuads.padding.length ||
+ this.currentQuads.content.length
+ );
+ }
+
+ _getOuterBounds() {
+ for (const region of ["margin", "border", "padding", "content"]) {
+ const quad = this._getOuterQuad(region);
+
+ if (!quad) {
+ // Invisible element such as a script tag.
+ break;
+ }
+
+ const { bottom, height, left, right, top, width, x, y } = quad.bounds;
+
+ if (width > 0 || height > 0) {
+ return { bottom, height, left, right, top, width, x, y };
+ }
+ }
+
+ return {
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 0,
+ top: 0,
+ width: 0,
+ x: 0,
+ y: 0,
+ };
+ }
+
+ /**
+ * We only want to show guides for horizontal and vertical edges as this helps
+ * to line them up. This method finds these edges and displays a guide there.
+ * @param {String} region The region around which the guides should be shown.
+ */
+ _showGuides(region) {
+ const quad = this._getOuterQuad(region);
+
+ if (!quad) {
+ // Invisible element such as a script tag.
+ return;
+ }
+
+ const { p1, p2, p3, p4 } = quad;
+
+ const allX = [p1.x, p2.x, p3.x, p4.x].sort((a, b) => a - b);
+ const allY = [p1.y, p2.y, p3.y, p4.y].sort((a, b) => a - b);
+ const toShowX = [];
+ const toShowY = [];
+
+ for (const arr of [allX, allY]) {
+ for (let i = 0; i < arr.length; i++) {
+ const val = arr[i];
+
+ if (i !== arr.lastIndexOf(val)) {
+ if (arr === allX) {
+ toShowX.push(val);
+ } else {
+ toShowY.push(val);
+ }
+ arr.splice(arr.lastIndexOf(val), 1);
+ }
+ }
+ }
+
+ // Move guide into place or hide it if no valid co-ordinate was found.
+ this._updateGuide("top", Math.round(toShowY[0]));
+ this._updateGuide("right", Math.round(toShowX[1]) - 1);
+ this._updateGuide("bottom", Math.round(toShowY[1] - 1));
+ this._updateGuide("left", Math.round(toShowX[0]));
+ }
+
+ _hideGuides() {
+ for (const side of BOX_MODEL_SIDES) {
+ this.getElement("guide-" + side).setAttribute("hidden", "true");
+ }
+ }
+
+ /**
+ * Move a guide to the appropriate position and display it. If no point is
+ * passed then the guide is hidden.
+ *
+ * @param {String} side
+ * The guide to update
+ * @param {Integer} point
+ * x or y co-ordinate. If this is undefined we hide the guide.
+ */
+ _updateGuide(side, point = -1) {
+ const guide = this.getElement("guide-" + side);
+
+ if (point <= 0) {
+ guide.setAttribute("hidden", "true");
+ return false;
+ }
+
+ if (side === "top" || side === "bottom") {
+ guide.setAttribute("x1", "0");
+ guide.setAttribute("y1", point + "");
+ guide.setAttribute("x2", "100%");
+ guide.setAttribute("y2", point + "");
+ } else {
+ guide.setAttribute("x1", point + "");
+ guide.setAttribute("y1", "0");
+ guide.setAttribute("x2", point + "");
+ guide.setAttribute("y2", "100%");
+ }
+
+ guide.removeAttribute("hidden");
+
+ return true;
+ }
+
+ /**
+ * Update node information (displayName#id.class)
+ */
+ _updateInfobar() {
+ if (!this.currentNode) {
+ return;
+ }
+
+ const { bindingElement: node, pseudo } = getBindingElementAndPseudo(
+ this.currentNode
+ );
+
+ // Update the tag, id, classes, pseudo-classes and dimensions
+ const displayName = getNodeDisplayName(node);
+
+ const id = node.id ? "#" + node.id : "";
+
+ const classList = (node.classList || []).length
+ ? "." + [...node.classList].join(".")
+ : "";
+
+ let pseudos = this._getPseudoClasses(node).join("");
+ if (pseudo) {
+ // Display :after as ::after
+ pseudos += ":" + pseudo;
+ }
+
+ // We want to display the original `width` and `height`, instead of the ones affected
+ // by any zoom. Since the infobar can be displayed also for text nodes, we can't
+ // access the computed style for that, and this is why we recalculate them here.
+ const zoom = getCurrentZoom(this.win);
+ const quad = this._getOuterQuad("border");
+
+ if (!quad) {
+ return;
+ }
+
+ const { width, height } = quad.bounds;
+ const dim =
+ parseFloat((width / zoom).toPrecision(6)) +
+ " \u00D7 " +
+ parseFloat((height / zoom).toPrecision(6));
+
+ const { grid: gridType, flex: flexType } = getNodeGridFlexType(node);
+ const gridLayoutTextType = this._getLayoutTextType("gridType", gridType);
+ const flexLayoutTextType = this._getLayoutTextType("flexType", flexType);
+
+ this.getElement("infobar-tagname").setTextContent(displayName);
+ this.getElement("infobar-id").setTextContent(id);
+ this.getElement("infobar-classes").setTextContent(classList);
+ this.getElement("infobar-pseudo-classes").setTextContent(pseudos);
+ this.getElement("infobar-dimensions").setTextContent(dim);
+ this.getElement("infobar-grid-type").setTextContent(gridLayoutTextType);
+ this.getElement("infobar-flex-type").setTextContent(flexLayoutTextType);
+
+ this._moveInfobar();
+ }
+
+ _getLayoutTextType(layoutTypeKey, { isContainer, isItem }) {
+ if (!isContainer && !isItem) {
+ return "";
+ }
+ if (isContainer && !isItem) {
+ return L10N.getStr(`${layoutTypeKey}.container`);
+ }
+ if (!isContainer && isItem) {
+ return L10N.getStr(`${layoutTypeKey}.item`);
+ }
+ return L10N.getStr(`${layoutTypeKey}.dual`);
+ }
+
+ _getPseudoClasses(node) {
+ if (node.nodeType !== nodeConstants.ELEMENT_NODE) {
+ // hasPseudoClassLock can only be used on Elements.
+ return [];
+ }
+
+ return PSEUDO_CLASSES.filter(pseudo => hasPseudoClassLock(node, pseudo));
+ }
+
+ /**
+ * Move the Infobar to the right place in the highlighter.
+ */
+ _moveInfobar() {
+ const bounds = this._getOuterBounds();
+ const container = this.getElement("infobar-container");
+
+ moveInfobar(container, bounds, this.win);
+ }
+
+ onPageHide({ target }) {
+ // If a pagehide event is triggered for current window's highlighter, hide the
+ // highlighter.
+ if (target.defaultView === this.win) {
+ this.hide();
+ }
+ }
+
+ onWillNavigate({ isTopLevel }) {
+ if (isTopLevel) {
+ this.hide();
+ }
+ }
+}
+
+exports.BoxModelHighlighter = BoxModelHighlighter;
diff --git a/devtools/server/actors/highlighters/css-grid.js b/devtools/server/actors/highlighters/css-grid.js
new file mode 100644
index 0000000000..bed5b106c5
--- /dev/null
+++ b/devtools/server/actors/highlighters/css-grid.js
@@ -0,0 +1,1958 @@
+/* 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";
+
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const {
+ CANVAS_SIZE,
+ DEFAULT_COLOR,
+ drawBubbleRect,
+ drawLine,
+ drawRect,
+ drawRoundedRect,
+ getBoundsFromPoints,
+ getCurrentMatrix,
+ getPathDescriptionFromPoints,
+ getPointsFromDiagonal,
+ updateCanvasElement,
+ updateCanvasPosition,
+} = require("devtools/server/actors/highlighters/utils/canvas");
+const {
+ CanvasFrameAnonymousContentHelper,
+ getComputedStyle,
+ moveInfobar,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const { apply } = require("devtools/shared/layout/dom-matrix-2d");
+const {
+ getCurrentZoom,
+ getDisplayPixelRatio,
+ getWindowDimensions,
+ setIgnoreLayoutChanges,
+} = require("devtools/shared/layout/utils");
+const {
+ stringifyGridFragments,
+} = require("devtools/server/actors/utils/css-grid-utils");
+const { LocalizationHelper } = require("devtools/shared/l10n");
+
+const STRINGS_URI = "devtools/shared/locales/highlighters.properties";
+const L10N = new LocalizationHelper(STRINGS_URI);
+
+const COLUMNS = "cols";
+const ROWS = "rows";
+
+const GRID_FONT_SIZE = 10;
+const GRID_FONT_FAMILY = "sans-serif";
+const GRID_AREA_NAME_FONT_SIZE = "20";
+
+const GRID_LINES_PROPERTIES = {
+ edge: {
+ lineDash: [0, 0],
+ alpha: 1,
+ },
+ explicit: {
+ lineDash: [5, 3],
+ alpha: 0.75,
+ },
+ implicit: {
+ lineDash: [2, 2],
+ alpha: 0.5,
+ },
+ areaEdge: {
+ lineDash: [0, 0],
+ alpha: 1,
+ lineWidth: 3,
+ },
+};
+
+const GRID_GAP_PATTERN_WIDTH = 14; // px
+const GRID_GAP_PATTERN_HEIGHT = 14; // px
+const GRID_GAP_PATTERN_LINE_DASH = [5, 3]; // px
+const GRID_GAP_ALPHA = 0.5;
+
+// This is the minimum distance a line can be to the edge of the document under which we
+// push the line number arrow to be inside the grid. This offset is enough to fit the
+// entire arrow + a stacked arrow behind it.
+const OFFSET_FROM_EDGE = 32;
+// This is how much inside the grid we push the arrow. This a factor of the arrow size.
+// The goal here is for a row and a column arrow that have both been pushed inside the
+// grid, in a corner, not to overlap.
+const FLIP_ARROW_INSIDE_FACTOR = 2.5;
+
+/**
+ * Given an `edge` of a box, return the name of the edge one move to the right.
+ */
+function rotateEdgeRight(edge) {
+ switch (edge) {
+ case "top":
+ return "right";
+ case "right":
+ return "bottom";
+ case "bottom":
+ return "left";
+ case "left":
+ return "top";
+ default:
+ return edge;
+ }
+}
+
+/**
+ * Given an `edge` of a box, return the name of the edge one move to the left.
+ */
+function rotateEdgeLeft(edge) {
+ switch (edge) {
+ case "top":
+ return "left";
+ case "right":
+ return "top";
+ case "bottom":
+ return "right";
+ case "left":
+ return "bottom";
+ default:
+ return edge;
+ }
+}
+
+/**
+ * Given an `edge` of a box, return the name of the opposite edge.
+ */
+function reflectEdge(edge) {
+ switch (edge) {
+ case "top":
+ return "bottom";
+ case "right":
+ return "left";
+ case "bottom":
+ return "top";
+ case "left":
+ return "right";
+ default:
+ return edge;
+ }
+}
+
+/**
+ * Cached used by `CssGridHighlighter.getGridGapPattern`.
+ */
+const gCachedGridPattern = new Map();
+
+/**
+ * The CssGridHighlighter is the class that overlays a visual grid on top of
+ * display:[inline-]grid elements.
+ *
+ * Usage example:
+ * let h = new CssGridHighlighter(env);
+ * h.show(node, options);
+ * h.hide();
+ * h.destroy();
+ *
+ * @param {String} options.color
+ * The color that should be used to draw the highlighter for this grid.
+ * @param {Number} options.globalAlpha
+ * The alpha (transparency) value that should be used to draw the highlighter for
+ * this grid.
+ * @param {Boolean} options.showAllGridAreas
+ * Shows all the grid area highlights for the current grid if isShown is
+ * true.
+ * @param {String} options.showGridArea
+ * Shows the grid area highlight for the given area name.
+ * @param {Boolean} options.showGridAreasOverlay
+ * Displays an overlay of all the grid areas for the current grid
+ * container if isShown is true.
+ * @param {Object} options.showGridCell
+ * An object containing the grid fragment index, row and column numbers
+ * to the corresponding grid cell to highlight for the current grid.
+ * @param {Number} options.showGridCell.gridFragmentIndex
+ * Index of the grid fragment to render the grid cell highlight.
+ * @param {Number} options.showGridCell.rowNumber
+ * Row number of the grid cell to highlight.
+ * @param {Number} options.showGridCell.columnNumber
+ * Column number of the grid cell to highlight.
+ * @param {Object} options.showGridLineNames
+ * An object containing the grid fragment index and line number to the
+ * corresponding grid line to highlight for the current grid.
+ * @param {Number} options.showGridLineNames.gridFragmentIndex
+ * Index of the grid fragment to render the grid line highlight.
+ * @param {Number} options.showGridLineNames.lineNumber
+ * Line number of the grid line to highlight.
+ * @param {String} options.showGridLineNames.type
+ * The dimension type of the grid line.
+ * @param {Boolean} options.showGridLineNumbers
+ * Displays the grid line numbers on the grid lines if isShown is true.
+ * @param {Boolean} options.showInfiniteLines
+ * Displays an infinite line to represent the grid lines if isShown is
+ * true.
+ * @param {Number} options.zIndex
+ * The z-index to decide the displaying order.
+ *
+ * Structure:
+ * <div class="highlighter-container">
+ * <canvas id="css-grid-canvas" class="css-grid-canvas">
+ * <svg class="css-grid-elements" hidden="true">
+ * <g class="css-grid-regions">
+ * <path class="css-grid-areas" points="..." />
+ * <path class="css-grid-cells" points="..." />
+ * </g>
+ * </svg>
+ * <div class="css-grid-area-infobar-container">
+ * <div class="css-grid-infobar">
+ * <div class="css-grid-infobar-text">
+ * <span class="css-grid-area-infobar-name">Grid Area Name</span>
+ * <span class="css-grid-area-infobar-dimensions">Grid Area Dimensions></span>
+ * </div>
+ * </div>
+ * </div>
+ * <div class="css-grid-cell-infobar-container">
+ * <div class="css-grid-infobar">
+ * <div class="css-grid-infobar-text">
+ * <span class="css-grid-cell-infobar-position">Grid Cell Position</span>
+ * <span class="css-grid-cell-infobar-dimensions">Grid Cell Dimensions></span>
+ * </div>
+ * </div>
+ * <div class="css-grid-line-infobar-container">
+ * <div class="css-grid-infobar">
+ * <div class="css-grid-infobar-text">
+ * <span class="css-grid-line-infobar-number">Grid Line Number</span>
+ * <span class="css-grid-line-infobar-names">Grid Line Names></span>
+ * </div>
+ * </div>
+ * </div>
+ * </div>
+ */
+
+class CssGridHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+
+ this.ID_CLASS_PREFIX = "css-grid-";
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ this.onPageHide = this.onPageHide.bind(this);
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ this.highlighterEnv.on("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = highlighterEnv;
+ pageListenerTarget.addEventListener("pagehide", this.onPageHide);
+
+ // Initialize the <canvas> position to the top left corner of the page.
+ this._canvasPosition = {
+ x: 0,
+ y: 0,
+ };
+
+ // Calling `updateCanvasPosition` anyway since the highlighter could be initialized
+ // on a page that has scrolled already.
+ updateCanvasPosition(
+ this._canvasPosition,
+ this._scroll,
+ this.win,
+ this._winDimensions
+ );
+ }
+
+ _buildMarkup() {
+ const container = this.markup.createNode({
+ attributes: {
+ class: "highlighter-container",
+ },
+ });
+
+ const root = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // We use a <canvas> element so that we can draw an arbitrary number of lines
+ // which wouldn't be possible with HTML or SVG without having to insert and remove
+ // the whole markup on every update.
+ this.markup.createNode({
+ parent: root,
+ nodeType: "canvas",
+ attributes: {
+ id: "canvas",
+ class: "canvas",
+ hidden: "true",
+ width: CANVAS_SIZE,
+ height: CANVAS_SIZE,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the SVG element.
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: root,
+ attributes: {
+ id: "elements",
+ width: "100%",
+ height: "100%",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const regions = this.markup.createSVGNode({
+ nodeType: "g",
+ parent: svg,
+ attributes: {
+ class: "regions",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: regions,
+ attributes: {
+ class: "areas",
+ id: "areas",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: regions,
+ attributes: {
+ class: "cells",
+ id: "cells",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the grid area infobar markup.
+ const areaInfobarContainer = this.markup.createNode({
+ parent: container,
+ attributes: {
+ class: "area-infobar-container",
+ id: "area-infobar-container",
+ position: "top",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const areaInfobar = this.markup.createNode({
+ parent: areaInfobarContainer,
+ attributes: {
+ class: "infobar",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const areaTextbox = this.markup.createNode({
+ parent: areaInfobar,
+ attributes: {
+ class: "infobar-text",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: areaTextbox,
+ attributes: {
+ class: "area-infobar-name",
+ id: "area-infobar-name",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: areaTextbox,
+ attributes: {
+ class: "area-infobar-dimensions",
+ id: "area-infobar-dimensions",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the grid cell infobar markup.
+ const cellInfobarContainer = this.markup.createNode({
+ parent: container,
+ attributes: {
+ class: "cell-infobar-container",
+ id: "cell-infobar-container",
+ position: "top",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const cellInfobar = this.markup.createNode({
+ parent: cellInfobarContainer,
+ attributes: {
+ class: "infobar",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const cellTextbox = this.markup.createNode({
+ parent: cellInfobar,
+ attributes: {
+ class: "infobar-text",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: cellTextbox,
+ attributes: {
+ class: "cell-infobar-position",
+ id: "cell-infobar-position",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: cellTextbox,
+ attributes: {
+ class: "cell-infobar-dimensions",
+ id: "cell-infobar-dimensions",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the grid line infobar markup.
+ const lineInfobarContainer = this.markup.createNode({
+ parent: container,
+ attributes: {
+ class: "line-infobar-container",
+ id: "line-infobar-container",
+ position: "top",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const lineInfobar = this.markup.createNode({
+ parent: lineInfobarContainer,
+ attributes: {
+ class: "infobar",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const lineTextbox = this.markup.createNode({
+ parent: lineInfobar,
+ attributes: {
+ class: "infobar-text",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: lineTextbox,
+ attributes: {
+ class: "line-infobar-number",
+ id: "line-infobar-number",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "span",
+ parent: lineTextbox,
+ attributes: {
+ class: "line-infobar-names",
+ id: "line-infobar-names",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ return container;
+ }
+
+ clearCache() {
+ gCachedGridPattern.clear();
+ }
+
+ /**
+ * Clear the grid area highlights.
+ */
+ clearGridAreas() {
+ const areas = this.getElement("areas");
+ areas.setAttribute("d", "");
+ }
+
+ /**
+ * Clear the grid cell highlights.
+ */
+ clearGridCell() {
+ const cells = this.getElement("cells");
+ cells.setAttribute("d", "");
+ }
+
+ destroy() {
+ const { highlighterEnv } = this;
+ highlighterEnv.off("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = highlighterEnv;
+ if (pageListenerTarget) {
+ pageListenerTarget.removeEventListener("pagehide", this.onPageHide);
+ }
+
+ this.markup.destroy();
+
+ // Clear the pattern cache to avoid dead object exceptions (Bug 1342051).
+ this.clearCache();
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+ }
+
+ get canvas() {
+ return this.getElement("canvas");
+ }
+
+ get color() {
+ return this.options.color || DEFAULT_COLOR;
+ }
+
+ get ctx() {
+ return this.canvas.getCanvasContext("2d");
+ }
+
+ get globalAlpha() {
+ return this.options.globalAlpha || 1;
+ }
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ getFirstColLinePos(fragment) {
+ return fragment.cols.lines[0].start;
+ }
+
+ getFirstRowLinePos(fragment) {
+ return fragment.rows.lines[0].start;
+ }
+
+ /**
+ * Gets the grid gap pattern used to render the gap regions based on the device
+ * pixel ratio given.
+ *
+ * @param {Number} devicePixelRatio
+ * The device pixel ratio we want the pattern for.
+ * @param {Object} dimension
+ * Refers to the Map key for the grid dimension type which is either the
+ * constant COLUMNS or ROWS.
+ * @return {CanvasPattern} grid gap pattern.
+ */
+ getGridGapPattern(devicePixelRatio, dimension) {
+ let gridPatternMap = null;
+
+ if (gCachedGridPattern.has(devicePixelRatio)) {
+ gridPatternMap = gCachedGridPattern.get(devicePixelRatio);
+ } else {
+ gridPatternMap = new Map();
+ }
+
+ if (gridPatternMap.has(dimension)) {
+ return gridPatternMap.get(dimension);
+ }
+
+ // Create the diagonal lines pattern for the rendering the grid gaps.
+ const canvas = this.markup.createNode({ nodeType: "canvas" });
+ const width = (canvas.width = GRID_GAP_PATTERN_WIDTH * devicePixelRatio);
+ const height = (canvas.height = GRID_GAP_PATTERN_HEIGHT * devicePixelRatio);
+
+ const ctx = canvas.getContext("2d");
+ ctx.save();
+ ctx.setLineDash(GRID_GAP_PATTERN_LINE_DASH);
+ ctx.beginPath();
+ ctx.translate(0.5, 0.5);
+
+ if (dimension === COLUMNS) {
+ ctx.moveTo(0, 0);
+ ctx.lineTo(width, height);
+ } else {
+ ctx.moveTo(width, 0);
+ ctx.lineTo(0, height);
+ }
+
+ ctx.strokeStyle = this.color;
+ ctx.globalAlpha = GRID_GAP_ALPHA * this.globalAlpha;
+ ctx.stroke();
+ ctx.restore();
+
+ const pattern = ctx.createPattern(canvas, "repeat");
+
+ gridPatternMap.set(dimension, pattern);
+ gCachedGridPattern.set(devicePixelRatio, gridPatternMap);
+
+ return pattern;
+ }
+
+ getLastColLinePos(fragment) {
+ return fragment.cols.lines[fragment.cols.lines.length - 1].start;
+ }
+
+ /**
+ * Get the GridLine index of the last edge of the explicit grid for a grid dimension.
+ *
+ * @param {GridTracks} tracks
+ * The grid track of a given grid dimension.
+ * @return {Number} index of the last edge of the explicit grid for a grid dimension.
+ */
+ getLastEdgeLineIndex(tracks) {
+ let trackIndex = tracks.length - 1;
+
+ // Traverse the grid track backwards until we find an explicit track.
+ while (trackIndex >= 0 && tracks[trackIndex].type != "explicit") {
+ trackIndex--;
+ }
+
+ // The grid line index is the grid track index + 1.
+ return trackIndex + 1;
+ }
+
+ getLastRowLinePos(fragment) {
+ return fragment.rows.lines[fragment.rows.lines.length - 1].start;
+ }
+
+ /**
+ * The AutoRefreshHighlighter's _hasMoved method returns true only if the
+ * element's quads have changed. Override it so it also returns true if the
+ * element's grid has changed (which can happen when you change the
+ * grid-template-* CSS properties with the highlighter displayed).
+ */
+ _hasMoved() {
+ const hasMoved = AutoRefreshHighlighter.prototype._hasMoved.call(this);
+
+ const oldGridData = stringifyGridFragments(this.gridData);
+ this.gridData = this.currentNode.getGridFragments();
+ const newGridData = stringifyGridFragments(this.gridData);
+
+ return hasMoved || oldGridData !== newGridData;
+ }
+
+ /**
+ * Hide the highlighter, the canvas and the infobars.
+ */
+ _hide() {
+ setIgnoreLayoutChanges(true);
+ this._hideGrid();
+ this._hideGridElements();
+ this._hideGridAreaInfoBar();
+ this._hideGridCellInfoBar();
+ this._hideGridLineInfoBar();
+ setIgnoreLayoutChanges(false, this.highlighterEnv.document.documentElement);
+ }
+
+ _hideGrid() {
+ this.getElement("canvas").setAttribute("hidden", "true");
+ }
+
+ _hideGridAreaInfoBar() {
+ this.getElement("area-infobar-container").setAttribute("hidden", "true");
+ }
+
+ _hideGridCellInfoBar() {
+ this.getElement("cell-infobar-container").setAttribute("hidden", "true");
+ }
+
+ _hideGridElements() {
+ this.getElement("elements").setAttribute("hidden", "true");
+ }
+
+ _hideGridLineInfoBar() {
+ this.getElement("line-infobar-container").setAttribute("hidden", "true");
+ }
+
+ /**
+ * Checks if the current node has a CSS Grid layout.
+ *
+ * @return {Boolean} true if the current node has a CSS grid layout, false otherwise.
+ */
+ isGrid() {
+ return this.currentNode.hasGridFragments();
+ }
+
+ /**
+ * Is a given grid fragment valid? i.e. does it actually have tracks? In some cases, we
+ * may have a fragment that defines column tracks but doesn't have any rows (or vice
+ * versa). In which case we do not want to draw anything for that fragment.
+ *
+ * @param {Object} fragment
+ * @return {Boolean}
+ */
+ isValidFragment(fragment) {
+ return fragment.cols.tracks.length && fragment.rows.tracks.length;
+ }
+
+ /**
+ * The <canvas>'s position needs to be updated if the page scrolls too much, in order
+ * to give the illusion that it always covers the viewport.
+ */
+ _scrollUpdate() {
+ const hasUpdated = updateCanvasPosition(
+ this._canvasPosition,
+ this._scroll,
+ this.win,
+ this._winDimensions
+ );
+
+ if (hasUpdated) {
+ this._update();
+ }
+ }
+
+ _show() {
+ if (!this.isGrid()) {
+ this.hide();
+ return false;
+ }
+
+ // The grid pattern cache should be cleared in case the color changed.
+ this.clearCache();
+
+ // Hide the canvas, grid element highlights and infobar.
+ this._hide();
+
+ return this._update();
+ }
+
+ _showGrid() {
+ this.getElement("canvas").removeAttribute("hidden");
+ }
+
+ _showGridAreaInfoBar() {
+ this.getElement("area-infobar-container").removeAttribute("hidden");
+ }
+
+ _showGridCellInfoBar() {
+ this.getElement("cell-infobar-container").removeAttribute("hidden");
+ }
+
+ _showGridElements() {
+ this.getElement("elements").removeAttribute("hidden");
+ }
+
+ _showGridLineInfoBar() {
+ this.getElement("line-infobar-container").removeAttribute("hidden");
+ }
+
+ /**
+ * Shows all the grid area highlights for the current grid.
+ */
+ showAllGridAreas() {
+ this.renderGridArea();
+ }
+
+ /**
+ * Shows the grid area highlight for the given area name.
+ *
+ * @param {String} areaName
+ * Grid area name.
+ */
+ showGridArea(areaName) {
+ this.renderGridArea(areaName);
+ }
+
+ /**
+ * Shows the grid cell highlight for the given grid cell options.
+ *
+ * @param {Number} options.gridFragmentIndex
+ * Index of the grid fragment to render the grid cell highlight.
+ * @param {Number} options.rowNumber
+ * Row number of the grid cell to highlight.
+ * @param {Number} options.columnNumber
+ * Column number of the grid cell to highlight.
+ */
+ showGridCell({ gridFragmentIndex, rowNumber, columnNumber }) {
+ this.renderGridCell(gridFragmentIndex, rowNumber, columnNumber);
+ }
+
+ /**
+ * Shows the grid line highlight for the given grid line options.
+ *
+ * @param {Number} options.gridFragmentIndex
+ * Index of the grid fragment to render the grid line highlight.
+ * @param {Number} options.lineNumber
+ * Line number of the grid line to highlight.
+ * @param {String} options.type
+ * The dimension type of the grid line.
+ */
+ showGridLineNames({ gridFragmentIndex, lineNumber, type }) {
+ this.renderGridLineNames(gridFragmentIndex, lineNumber, type);
+ }
+
+ /**
+ * If a page hide event is triggered for current window's highlighter, hide the
+ * highlighter.
+ */
+ onPageHide({ target }) {
+ if (target.defaultView === this.win) {
+ this.hide();
+ }
+ }
+
+ /**
+ * Called when the page will-navigate. Used to hide the grid highlighter and clear
+ * the cached gap patterns and avoid using DeadWrapper obejcts as gap patterns the
+ * next time.
+ */
+ onWillNavigate({ isTopLevel }) {
+ this.clearCache();
+
+ if (isTopLevel) {
+ this.hide();
+ }
+ }
+
+ renderFragment(fragment) {
+ if (!this.isValidFragment(fragment)) {
+ return;
+ }
+
+ this.renderLines(
+ fragment.cols,
+ COLUMNS,
+ this.getFirstRowLinePos(fragment),
+ this.getLastRowLinePos(fragment)
+ );
+ this.renderLines(
+ fragment.rows,
+ ROWS,
+ this.getFirstColLinePos(fragment),
+ this.getLastColLinePos(fragment)
+ );
+
+ if (this.options.showGridAreasOverlay) {
+ this.renderGridAreaOverlay();
+ }
+
+ // Line numbers are rendered in a 2nd step to avoid overlapping with existing lines.
+ if (this.options.showGridLineNumbers) {
+ this.renderLineNumbers(
+ fragment.cols,
+ COLUMNS,
+ this.getFirstRowLinePos(fragment)
+ );
+ this.renderLineNumbers(
+ fragment.rows,
+ ROWS,
+ this.getFirstColLinePos(fragment)
+ );
+ this.renderNegativeLineNumbers(
+ fragment.cols,
+ COLUMNS,
+ this.getLastRowLinePos(fragment)
+ );
+ this.renderNegativeLineNumbers(
+ fragment.rows,
+ ROWS,
+ this.getLastColLinePos(fragment)
+ );
+ }
+ }
+
+ /**
+ * Render the grid area highlight for the given area name or for all the grid areas.
+ *
+ * @param {String} areaName
+ * Name of the grid area to be highlighted. If no area name is provided, all
+ * the grid areas should be highlighted.
+ */
+ renderGridArea(areaName) {
+ const { devicePixelRatio } = this.win;
+ const displayPixelRatio = getDisplayPixelRatio(this.win);
+ const paths = [];
+
+ for (let i = 0; i < this.gridData.length; i++) {
+ const fragment = this.gridData[i];
+
+ for (const area of fragment.areas) {
+ if (areaName && areaName != area.name) {
+ continue;
+ }
+
+ const rowStart = fragment.rows.lines[area.rowStart - 1];
+ const rowEnd = fragment.rows.lines[area.rowEnd - 1];
+ const columnStart = fragment.cols.lines[area.columnStart - 1];
+ const columnEnd = fragment.cols.lines[area.columnEnd - 1];
+
+ const x1 = columnStart.start + columnStart.breadth;
+ const y1 = rowStart.start + rowStart.breadth;
+ const x2 = columnEnd.start;
+ const y2 = rowEnd.start;
+
+ const points = getPointsFromDiagonal(
+ x1,
+ y1,
+ x2,
+ y2,
+ this.currentMatrix
+ );
+
+ // Scale down by `devicePixelRatio` since SVG element already take them into
+ // account.
+ const svgPoints = points.map(point => ({
+ x: Math.round(point.x / devicePixelRatio),
+ y: Math.round(point.y / devicePixelRatio),
+ }));
+
+ // Scale down by `displayPixelRatio` since infobar's HTML elements already take it
+ // into account; and the zoom scaling is handled by `moveInfobar`.
+ const bounds = getBoundsFromPoints(
+ points.map(point => ({
+ x: Math.round(point.x / displayPixelRatio),
+ y: Math.round(point.y / displayPixelRatio),
+ }))
+ );
+
+ paths.push(getPathDescriptionFromPoints(svgPoints));
+
+ // Update and show the info bar when only displaying a single grid area.
+ if (areaName) {
+ this._showGridAreaInfoBar();
+ this._updateGridAreaInfobar(area, bounds);
+ }
+ }
+ }
+
+ const areas = this.getElement("areas");
+ areas.setAttribute("d", paths.join(" "));
+ }
+
+ /**
+ * Render grid area name on the containing grid area cell.
+ *
+ * @param {Object} fragment
+ * The grid fragment of the grid container.
+ * @param {Object} area
+ * The area overlay to render on the CSS highlighter canvas.
+ */
+ renderGridAreaName(fragment, area) {
+ const { rowStart, rowEnd, columnStart, columnEnd } = area;
+ const { devicePixelRatio } = this.win;
+ const displayPixelRatio = getDisplayPixelRatio(this.win);
+ const offset = (displayPixelRatio / 2) % 1;
+ let fontSize = GRID_AREA_NAME_FONT_SIZE * displayPixelRatio;
+ const canvasX = Math.round(this._canvasPosition.x * devicePixelRatio);
+ const canvasY = Math.round(this._canvasPosition.y * devicePixelRatio);
+
+ this.ctx.save();
+ this.ctx.translate(offset - canvasX, offset - canvasY);
+ this.ctx.font = fontSize + "px " + GRID_FONT_FAMILY;
+ this.ctx.globalAlpha = this.globalAlpha;
+ this.ctx.strokeStyle = this.color;
+ this.ctx.textAlign = "center";
+ this.ctx.textBaseline = "middle";
+
+ // Draw the text for the grid area name.
+ for (let rowNumber = rowStart; rowNumber < rowEnd; rowNumber++) {
+ for (
+ let columnNumber = columnStart;
+ columnNumber < columnEnd;
+ columnNumber++
+ ) {
+ const row = fragment.rows.tracks[rowNumber - 1];
+ const column = fragment.cols.tracks[columnNumber - 1];
+
+ // If the font size exceeds the bounds of the containing grid cell, size it its
+ // row or column dimension, whichever is smallest.
+ if (
+ fontSize > column.breadth * displayPixelRatio ||
+ fontSize > row.breadth * displayPixelRatio
+ ) {
+ fontSize = Math.min([column.breadth, row.breadth]);
+ this.ctx.font = fontSize + "px " + GRID_FONT_FAMILY;
+ }
+
+ const textWidth = this.ctx.measureText(area.name).width;
+ // The width of the character 'm' approximates the height of the text.
+ const textHeight = this.ctx.measureText("m").width;
+ // Padding in pixels for the line number text inside of the line number container.
+ const padding = 3 * displayPixelRatio;
+
+ const boxWidth = textWidth + 2 * padding;
+ const boxHeight = textHeight + 2 * padding;
+
+ let x = column.start + column.breadth / 2;
+ let y = row.start + row.breadth / 2;
+
+ [x, y] = apply(this.currentMatrix, [x, y]);
+
+ const rectXPos = x - boxWidth / 2;
+ const rectYPos = y - boxHeight / 2;
+
+ // Draw a rounded rectangle with a border width of 1 pixel,
+ // a border color matching the grid color, and a white background.
+ this.ctx.lineWidth = 1 * displayPixelRatio;
+ this.ctx.strokeStyle = this.color;
+ this.ctx.fillStyle = "white";
+ const radius = 2 * displayPixelRatio;
+ drawRoundedRect(
+ this.ctx,
+ rectXPos,
+ rectYPos,
+ boxWidth,
+ boxHeight,
+ radius
+ );
+
+ this.ctx.fillStyle = this.color;
+ this.ctx.fillText(area.name, x, y + padding);
+ }
+ }
+
+ this.ctx.restore();
+ }
+
+ /**
+ * Renders the grid area overlay on the css grid highlighter canvas.
+ */
+ renderGridAreaOverlay() {
+ const padding = 1;
+
+ for (let i = 0; i < this.gridData.length; i++) {
+ const fragment = this.gridData[i];
+
+ for (const area of fragment.areas) {
+ const { rowStart, rowEnd, columnStart, columnEnd, type } = area;
+
+ if (type === "implicit") {
+ continue;
+ }
+
+ // Draw the line edges for the grid area.
+ const areaColStart = fragment.cols.lines[columnStart - 1];
+ const areaColEnd = fragment.cols.lines[columnEnd - 1];
+
+ const areaRowStart = fragment.rows.lines[rowStart - 1];
+ const areaRowEnd = fragment.rows.lines[rowEnd - 1];
+
+ const areaColStartLinePos = areaColStart.start + areaColStart.breadth;
+ const areaRowStartLinePos = areaRowStart.start + areaRowStart.breadth;
+
+ this.renderLine(
+ areaColStartLinePos + padding,
+ areaRowStartLinePos,
+ areaRowEnd.start,
+ COLUMNS,
+ "areaEdge"
+ );
+ this.renderLine(
+ areaColEnd.start - padding,
+ areaRowStartLinePos,
+ areaRowEnd.start,
+ COLUMNS,
+ "areaEdge"
+ );
+
+ this.renderLine(
+ areaRowStartLinePos + padding,
+ areaColStartLinePos,
+ areaColEnd.start,
+ ROWS,
+ "areaEdge"
+ );
+ this.renderLine(
+ areaRowEnd.start - padding,
+ areaColStartLinePos,
+ areaColEnd.start,
+ ROWS,
+ "areaEdge"
+ );
+
+ this.renderGridAreaName(fragment, area);
+ }
+ }
+ }
+
+ /**
+ * Render the grid cell highlight for the given grid fragment index, row and column
+ * number.
+ *
+ * @param {Number} gridFragmentIndex
+ * Index of the grid fragment to render the grid cell highlight.
+ * @param {Number} rowNumber
+ * Row number of the grid cell to highlight.
+ * @param {Number} columnNumber
+ * Column number of the grid cell to highlight.
+ */
+ renderGridCell(gridFragmentIndex, rowNumber, columnNumber) {
+ const fragment = this.gridData[gridFragmentIndex];
+
+ if (!fragment) {
+ return;
+ }
+
+ const row = fragment.rows.tracks[rowNumber - 1];
+ const column = fragment.cols.tracks[columnNumber - 1];
+
+ if (!row || !column) {
+ return;
+ }
+
+ const x1 = column.start;
+ const y1 = row.start;
+ const x2 = column.start + column.breadth;
+ const y2 = row.start + row.breadth;
+
+ const { devicePixelRatio } = this.win;
+ const displayPixelRatio = getDisplayPixelRatio(this.win);
+ const points = getPointsFromDiagonal(x1, y1, x2, y2, this.currentMatrix);
+
+ // Scale down by `devicePixelRatio` since SVG element already take them into account.
+ const svgPoints = points.map(point => ({
+ x: Math.round(point.x / devicePixelRatio),
+ y: Math.round(point.y / devicePixelRatio),
+ }));
+
+ // Scale down by `displayPixelRatio` since infobar's HTML elements already take it
+ // into account, and the zoom scaling is handled by `moveInfobar`.
+ const bounds = getBoundsFromPoints(
+ points.map(point => ({
+ x: Math.round(point.x / displayPixelRatio),
+ y: Math.round(point.y / displayPixelRatio),
+ }))
+ );
+
+ const cells = this.getElement("cells");
+ cells.setAttribute("d", getPathDescriptionFromPoints(svgPoints));
+
+ this._showGridCellInfoBar();
+ this._updateGridCellInfobar(rowNumber, columnNumber, bounds);
+ }
+
+ /**
+ * Render the grid gap area on the css grid highlighter canvas.
+ *
+ * @param {Number} linePos
+ * The line position along the x-axis for a column grid line and
+ * y-axis for a row grid line.
+ * @param {Number} startPos
+ * The start position of the cross side of the grid line.
+ * @param {Number} endPos
+ * The end position of the cross side of the grid line.
+ * @param {Number} breadth
+ * The grid line breadth value.
+ * @param {String} dimensionType
+ * The grid dimension type which is either the constant COLUMNS or ROWS.
+ */
+ renderGridGap(linePos, startPos, endPos, breadth, dimensionType) {
+ const { devicePixelRatio } = this.win;
+ const displayPixelRatio = getDisplayPixelRatio(this.win);
+ const offset = (displayPixelRatio / 2) % 1;
+ const canvasX = Math.round(this._canvasPosition.x * devicePixelRatio);
+ const canvasY = Math.round(this._canvasPosition.y * devicePixelRatio);
+
+ linePos = Math.round(linePos);
+ startPos = Math.round(startPos);
+ breadth = Math.round(breadth);
+
+ this.ctx.save();
+ this.ctx.fillStyle = this.getGridGapPattern(
+ devicePixelRatio,
+ dimensionType
+ );
+ this.ctx.translate(offset - canvasX, offset - canvasY);
+
+ if (dimensionType === COLUMNS) {
+ if (isFinite(endPos)) {
+ endPos = Math.round(endPos);
+ } else {
+ endPos = this._winDimensions.height;
+ startPos = -endPos;
+ }
+ drawRect(
+ this.ctx,
+ linePos,
+ startPos,
+ linePos + breadth,
+ endPos,
+ this.currentMatrix
+ );
+ } else {
+ if (isFinite(endPos)) {
+ endPos = Math.round(endPos);
+ } else {
+ endPos = this._winDimensions.width;
+ startPos = -endPos;
+ }
+ drawRect(
+ this.ctx,
+ startPos,
+ linePos,
+ endPos,
+ linePos + breadth,
+ this.currentMatrix
+ );
+ }
+
+ // Find current angle of grid by measuring the angle of two arbitrary points,
+ // then rotate canvas, so the hash pattern stays 45deg to the gridlines.
+ const p1 = apply(this.currentMatrix, [0, 0]);
+ const p2 = apply(this.currentMatrix, [1, 0]);
+ const angleRad = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]);
+ this.ctx.rotate(angleRad);
+
+ this.ctx.fill();
+ this.ctx.restore();
+ }
+
+ /**
+ * Render the grid line name highlight for the given grid fragment index, lineNumber,
+ * and dimensionType.
+ *
+ * @param {Number} gridFragmentIndex
+ * Index of the grid fragment to render the grid line highlight.
+ * @param {Number} lineNumber
+ * Line number of the grid line to highlight.
+ * @param {String} dimensionType
+ * The dimension type of the grid line.
+ */
+ renderGridLineNames(gridFragmentIndex, lineNumber, dimensionType) {
+ const fragment = this.gridData[gridFragmentIndex];
+
+ if (!fragment || !lineNumber || !dimensionType) {
+ return;
+ }
+
+ const { names } = fragment[dimensionType].lines[lineNumber - 1];
+ let linePos;
+
+ if (dimensionType === ROWS) {
+ linePos = fragment.rows.lines[lineNumber - 1];
+ } else if (dimensionType === COLUMNS) {
+ linePos = fragment.cols.lines[lineNumber - 1];
+ }
+
+ if (!linePos) {
+ return;
+ }
+
+ const currentZoom = getCurrentZoom(this.win);
+ const { bounds } = this.currentQuads.content[gridFragmentIndex];
+
+ const rowYPosition = fragment.rows.lines[0];
+ const colXPosition = fragment.rows.lines[0];
+
+ const x =
+ dimensionType === COLUMNS
+ ? linePos.start + bounds.left / currentZoom
+ : colXPosition.start + bounds.left / currentZoom;
+
+ const y =
+ dimensionType === ROWS
+ ? linePos.start + bounds.top / currentZoom
+ : rowYPosition.start + bounds.top / currentZoom;
+
+ this._showGridLineInfoBar();
+ this._updateGridLineInfobar(names.join(", "), lineNumber, x, y);
+ }
+
+ /**
+ * Render the grid line number on the css grid highlighter canvas.
+ *
+ * @param {Number} lineNumber
+ * The grid line number.
+ * @param {Number} linePos
+ * The line position along the x-axis for a column grid line and
+ * y-axis for a row grid line.
+ * @param {Number} startPos
+ * The start position of the cross side of the grid line.
+ * @param {Number} breadth
+ * The grid line breadth value.
+ * @param {String} dimensionType
+ * The grid dimension type which is either the constant COLUMNS or ROWS.
+ * @param {Boolean||undefined} isStackedLine
+ * Boolean indicating if the line is stacked.
+ */
+ // eslint-disable-next-line complexity
+ renderGridLineNumber(
+ lineNumber,
+ linePos,
+ startPos,
+ breadth,
+ dimensionType,
+ isStackedLine
+ ) {
+ const displayPixelRatio = getDisplayPixelRatio(this.win);
+ const { devicePixelRatio } = this.win;
+ const offset = (displayPixelRatio / 2) % 1;
+ const fontSize = GRID_FONT_SIZE * devicePixelRatio;
+ const canvasX = Math.round(this._canvasPosition.x * devicePixelRatio);
+ const canvasY = Math.round(this._canvasPosition.y * devicePixelRatio);
+
+ linePos = Math.round(linePos);
+ startPos = Math.round(startPos);
+ breadth = Math.round(breadth);
+
+ if (linePos + breadth < 0) {
+ // Don't render the line number since the line is not visible on screen.
+ return;
+ }
+
+ this.ctx.save();
+ this.ctx.translate(offset - canvasX, offset - canvasY);
+ this.ctx.font = fontSize + "px " + GRID_FONT_FAMILY;
+
+ // For a general grid box, the height of the character "m" will be its minimum width
+ // and height. If line number's text width is greater, then use the grid box's text
+ // width instead.
+ const textHeight = this.ctx.measureText("m").width;
+ const textWidth = Math.max(
+ textHeight,
+ this.ctx.measureText(lineNumber).width
+ );
+
+ // Padding in pixels for the line number text inside of the line number container.
+ const padding = 3 * devicePixelRatio;
+ const offsetFromEdge = 2 * devicePixelRatio;
+
+ let boxWidth = textWidth + 2 * padding;
+ let boxHeight = textHeight + 2 * padding;
+
+ // Calculate the x & y coordinates for the line number container, so that its arrow
+ // tip is centered on the line (or the gap if there is one), and is offset by the
+ // calculated padding value from the grid container edge.
+ let x, y;
+
+ if (dimensionType === COLUMNS) {
+ x = linePos + breadth / 2;
+ y =
+ lineNumber > 0 ? startPos - offsetFromEdge : startPos + offsetFromEdge;
+ } else if (dimensionType === ROWS) {
+ y = linePos + breadth / 2;
+ x =
+ lineNumber > 0 ? startPos - offsetFromEdge : startPos + offsetFromEdge;
+ }
+
+ [x, y] = apply(this.currentMatrix, [x, y]);
+
+ // Draw a bubble rectangular arrow with a border width of 2 pixels, a border color
+ // matching the grid color and a white background (the line number will be written in
+ // black).
+ this.ctx.lineWidth = 2 * displayPixelRatio;
+ this.ctx.strokeStyle = this.color;
+ this.ctx.fillStyle = "white";
+ this.ctx.globalAlpha = this.globalAlpha;
+
+ // See param definitions of drawBubbleRect.
+ const radius = 2 * displayPixelRatio;
+ const margin = 2 * displayPixelRatio;
+ const arrowSize = 8 * displayPixelRatio;
+
+ const minBoxSize = arrowSize * 2 + padding;
+ boxWidth = Math.max(boxWidth, minBoxSize);
+ boxHeight = Math.max(boxHeight, minBoxSize);
+
+ // Determine which edge of the box to aim the line number arrow at.
+ const boxEdge = this.getBoxEdge(dimensionType, lineNumber);
+
+ let { width, height } = this._winDimensions;
+ width *= displayPixelRatio;
+ height *= displayPixelRatio;
+
+ // Don't draw if the line is out of the viewport.
+ if (
+ (dimensionType === ROWS && (y < 0 || y > height)) ||
+ (dimensionType === COLUMNS && (x < 0 || x > width))
+ ) {
+ this.ctx.restore();
+ return;
+ }
+
+ // If the arrow's edge (the one perpendicular to the line direction) is too close to
+ // the edge of the viewport. Push the arrow inside the grid.
+ const minOffsetFromEdge = OFFSET_FROM_EDGE * displayPixelRatio;
+ switch (boxEdge) {
+ case "left":
+ if (x < minOffsetFromEdge) {
+ x += FLIP_ARROW_INSIDE_FACTOR * boxWidth;
+ }
+ break;
+ case "right":
+ if (width - x < minOffsetFromEdge) {
+ x -= FLIP_ARROW_INSIDE_FACTOR * boxWidth;
+ }
+ break;
+ case "top":
+ if (y < minOffsetFromEdge) {
+ y += FLIP_ARROW_INSIDE_FACTOR * boxHeight;
+ }
+ break;
+ case "bottom":
+ if (height - y < minOffsetFromEdge) {
+ y -= FLIP_ARROW_INSIDE_FACTOR * boxHeight;
+ }
+ break;
+ }
+
+ // Offset stacked line numbers by a quarter of the box's width/height, so a part of
+ // them remains visible behind the number that sits at the top of the stack.
+ if (isStackedLine) {
+ const xOffset = boxWidth / 4;
+ const yOffset = boxHeight / 4;
+
+ if (lineNumber > 0) {
+ x -= xOffset;
+ y -= yOffset;
+ } else {
+ x += xOffset;
+ y += yOffset;
+ }
+ }
+
+ // If one the edges of the arrow that's parallel to the line is too close to the edge
+ // of the viewport (and therefore partly hidden), grow the arrow's size in the
+ // opposite direction.
+ // The goal is for the part that's not hidden to be exactly the size of a normal
+ // arrow and for the arrow to keep pointing at the line (keep being centered on it).
+ let grewBox = false;
+ const boxWidthBeforeGrowth = boxWidth;
+ const boxHeightBeforeGrowth = boxHeight;
+
+ if (dimensionType === ROWS && y <= boxHeight / 2) {
+ grewBox = true;
+ boxHeight = 2 * (boxHeight - y);
+ } else if (dimensionType === ROWS && y >= height - boxHeight / 2) {
+ grewBox = true;
+ boxHeight = 2 * (y - height + boxHeight);
+ } else if (dimensionType === COLUMNS && x <= boxWidth / 2) {
+ grewBox = true;
+ boxWidth = 2 * (boxWidth - x);
+ } else if (dimensionType === COLUMNS && x >= width - boxWidth / 2) {
+ grewBox = true;
+ boxWidth = 2 * (x - width + boxWidth);
+ }
+
+ // Draw the arrow box itself
+ drawBubbleRect(
+ this.ctx,
+ x,
+ y,
+ boxWidth,
+ boxHeight,
+ radius,
+ margin,
+ arrowSize,
+ boxEdge
+ );
+
+ // Determine the text position for it to be centered nicely inside the arrow box.
+ switch (boxEdge) {
+ case "left":
+ x -= boxWidth + arrowSize + radius - boxWidth / 2;
+ break;
+ case "right":
+ x += boxWidth + arrowSize + radius - boxWidth / 2;
+ break;
+ case "top":
+ y -= boxHeight + arrowSize + radius - boxHeight / 2;
+ break;
+ case "bottom":
+ y += boxHeight + arrowSize + radius - boxHeight / 2;
+ break;
+ }
+
+ // Do a second pass to adjust the position, along the other axis, if the box grew
+ // during the previous step, so the text is also centered on that axis.
+ if (grewBox) {
+ if (dimensionType === ROWS && y <= boxHeightBeforeGrowth / 2) {
+ y = boxHeightBeforeGrowth / 2;
+ } else if (
+ dimensionType === ROWS &&
+ y >= height - boxHeightBeforeGrowth / 2
+ ) {
+ y = height - boxHeightBeforeGrowth / 2;
+ } else if (dimensionType === COLUMNS && x <= boxWidthBeforeGrowth / 2) {
+ x = boxWidthBeforeGrowth / 2;
+ } else if (
+ dimensionType === COLUMNS &&
+ x >= width - boxWidthBeforeGrowth / 2
+ ) {
+ x = width - boxWidthBeforeGrowth / 2;
+ }
+ }
+
+ // Write the line number inside of the rectangle.
+ this.ctx.textAlign = "center";
+ this.ctx.textBaseline = "middle";
+ this.ctx.fillStyle = "black";
+ const numberText = isStackedLine ? "" : lineNumber;
+ this.ctx.fillText(numberText, x, y);
+ this.ctx.restore();
+ }
+
+ /**
+ * Determine which edge of a line number box to aim the line number arrow at.
+ *
+ * @param {String} dimensionType
+ * The grid line dimension type which is either the constant COLUMNS or ROWS.
+ * @param {Number} lineNumber
+ * The grid line number.
+ * @return {String} The edge of the box: top, right, bottom or left.
+ */
+ getBoxEdge(dimensionType, lineNumber) {
+ let boxEdge;
+
+ if (dimensionType === COLUMNS) {
+ boxEdge = lineNumber > 0 ? "top" : "bottom";
+ } else if (dimensionType === ROWS) {
+ boxEdge = lineNumber > 0 ? "left" : "right";
+ }
+
+ // Rotate box edge as needed for writing mode and text direction.
+ const { direction, writingMode } = getComputedStyle(this.currentNode);
+
+ switch (writingMode) {
+ case "horizontal-tb":
+ // This is the initial value. No further adjustment needed.
+ break;
+ case "vertical-rl":
+ boxEdge = rotateEdgeRight(boxEdge);
+ break;
+ case "vertical-lr":
+ if (dimensionType === COLUMNS) {
+ boxEdge = rotateEdgeLeft(boxEdge);
+ } else {
+ boxEdge = rotateEdgeRight(boxEdge);
+ }
+ break;
+ case "sideways-rl":
+ boxEdge = rotateEdgeRight(boxEdge);
+ break;
+ case "sideways-lr":
+ boxEdge = rotateEdgeLeft(boxEdge);
+ break;
+ default:
+ console.error(`Unexpected writing-mode: ${writingMode}`);
+ }
+
+ switch (direction) {
+ case "ltr":
+ // This is the initial value. No further adjustment needed.
+ break;
+ case "rtl":
+ if (dimensionType === ROWS) {
+ boxEdge = reflectEdge(boxEdge);
+ }
+ break;
+ default:
+ console.error(`Unexpected direction: ${direction}`);
+ }
+
+ return boxEdge;
+ }
+
+ /**
+ * Render the grid line on the css grid highlighter canvas.
+ *
+ * @param {Number} linePos
+ * The line position along the x-axis for a column grid line and
+ * y-axis for a row grid line.
+ * @param {Number} startPos
+ * The start position of the cross side of the grid line.
+ * @param {Number} endPos
+ * The end position of the cross side of the grid line.
+ * @param {String} dimensionType
+ * The grid dimension type which is either the constant COLUMNS or ROWS.
+ * @param {String} lineType
+ * The grid line type - "edge", "explicit", or "implicit".
+ */
+ renderLine(linePos, startPos, endPos, dimensionType, lineType) {
+ const { devicePixelRatio } = this.win;
+ const lineWidth = getDisplayPixelRatio(this.win);
+ const offset = (lineWidth / 2) % 1;
+ const canvasX = Math.round(this._canvasPosition.x * devicePixelRatio);
+ const canvasY = Math.round(this._canvasPosition.y * devicePixelRatio);
+
+ linePos = Math.round(linePos);
+ startPos = Math.round(startPos);
+ endPos = Math.round(endPos);
+
+ this.ctx.save();
+ this.ctx.setLineDash(GRID_LINES_PROPERTIES[lineType].lineDash);
+ this.ctx.translate(offset - canvasX, offset - canvasY);
+
+ const lineOptions = {
+ matrix: this.currentMatrix,
+ };
+
+ if (this.options.showInfiniteLines) {
+ lineOptions.extendToBoundaries = [
+ canvasX,
+ canvasY,
+ canvasX + CANVAS_SIZE,
+ canvasY + CANVAS_SIZE,
+ ];
+ }
+
+ if (dimensionType === COLUMNS) {
+ drawLine(this.ctx, linePos, startPos, linePos, endPos, lineOptions);
+ } else {
+ drawLine(this.ctx, startPos, linePos, endPos, linePos, lineOptions);
+ }
+
+ this.ctx.strokeStyle = this.color;
+ this.ctx.globalAlpha =
+ GRID_LINES_PROPERTIES[lineType].alpha * this.globalAlpha;
+
+ if (GRID_LINES_PROPERTIES[lineType].lineWidth) {
+ this.ctx.lineWidth =
+ GRID_LINES_PROPERTIES[lineType].lineWidth * devicePixelRatio;
+ } else {
+ this.ctx.lineWidth = lineWidth;
+ }
+
+ this.ctx.stroke();
+ this.ctx.restore();
+ }
+
+ /**
+ * Render the grid lines given the grid dimension information of the
+ * column or row lines.
+ *
+ * @param {GridDimension} gridDimension
+ * Column or row grid dimension object.
+ * @param {Object} quad.bounds
+ * The content bounds of the box model region quads.
+ * @param {String} dimensionType
+ * The grid dimension type which is either the constant COLUMNS or ROWS.
+ * @param {Number} startPos
+ * The start position of the cross side ("left" for ROWS and "top" for COLUMNS)
+ * of the grid dimension.
+ * @param {Number} endPos
+ * The end position of the cross side ("left" for ROWS and "top" for COLUMNS)
+ * of the grid dimension.
+ */
+ renderLines(gridDimension, dimensionType, startPos, endPos) {
+ const { lines, tracks } = gridDimension;
+ const lastEdgeLineIndex = this.getLastEdgeLineIndex(tracks);
+
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i];
+ const linePos = line.start;
+
+ if (i == 0 || i == lastEdgeLineIndex) {
+ this.renderLine(linePos, startPos, endPos, dimensionType, "edge");
+ } else {
+ this.renderLine(
+ linePos,
+ startPos,
+ endPos,
+ dimensionType,
+ tracks[i - 1].type
+ );
+ }
+
+ // Render a second line to illustrate the gutter for non-zero breadth.
+ if (line.breadth > 0) {
+ this.renderGridGap(
+ linePos,
+ startPos,
+ endPos,
+ line.breadth,
+ dimensionType
+ );
+ this.renderLine(
+ linePos + line.breadth,
+ startPos,
+ endPos,
+ dimensionType,
+ tracks[i].type
+ );
+ }
+ }
+ }
+
+ /**
+ * Render the grid lines given the grid dimension information of the
+ * column or row lines.
+ *
+ * @param {GridDimension} gridDimension
+ * Column or row grid dimension object.
+ * @param {String} dimensionType
+ * The grid dimension type which is either the constant COLUMNS or ROWS.
+ * @param {Number} startPos
+ * The start position of the cross side ("left" for ROWS and "top" for COLUMNS)
+ * of the grid dimension.
+ */
+ renderLineNumbers(gridDimension, dimensionType, startPos) {
+ const { lines, tracks } = gridDimension;
+
+ for (let i = 0, line; (line = lines[i++]); ) {
+ // If you place something using negative numbers, you can trigger some implicit
+ // grid creation above and to the left of the explicit grid (assuming a
+ // horizontal-tb writing mode).
+ //
+ // The first explicit grid line gets the number of 1, and any implicit grid lines
+ // before 1 get negative numbers. Since here we're rendering only the positive line
+ // numbers, we have to skip any implicit grid lines before the first one that is
+ // explicit. The API returns a 0 as the line's number for these implicit lines that
+ // occurs before the first explicit line.
+ if (line.number === 0) {
+ continue;
+ }
+
+ // Check for overlapping lines by measuring the track width between them.
+ // We render a second box beneath the last overlapping
+ // line number to indicate there are lines beneath it.
+ const gridTrack = tracks[i - 1];
+
+ if (gridTrack) {
+ const { breadth } = gridTrack;
+
+ if (breadth === 0) {
+ this.renderGridLineNumber(
+ line.number,
+ line.start,
+ startPos,
+ line.breadth,
+ dimensionType,
+ true
+ );
+ continue;
+ }
+ }
+
+ this.renderGridLineNumber(
+ line.number,
+ line.start,
+ startPos,
+ line.breadth,
+ dimensionType
+ );
+ }
+ }
+
+ /**
+ * Render the negative grid lines given the grid dimension information of the
+ * column or row lines.
+ *
+ * @param {GridDimension} gridDimension
+ * Column or row grid dimension object.
+ * @param {String} dimensionType
+ * The grid dimension type which is either the constant COLUMNS or ROWS.
+ * @param {Number} startPos
+ * The start position of the cross side ("left" for ROWS and "top" for COLUMNS)
+ * of the grid dimension.
+ */
+ renderNegativeLineNumbers(gridDimension, dimensionType, startPos) {
+ const { lines, tracks } = gridDimension;
+
+ for (let i = 0, line; (line = lines[i++]); ) {
+ const linePos = line.start;
+ const negativeLineNumber = line.negativeNumber;
+
+ // Don't render any negative line number greater than -1.
+ if (negativeLineNumber == 0) {
+ break;
+ }
+
+ // Check for overlapping lines by measuring the track width between them.
+ // We render a second box beneath the last overlapping
+ // line number to indicate there are lines beneath it.
+ const gridTrack = tracks[i - 1];
+ if (gridTrack) {
+ const { breadth } = gridTrack;
+
+ // Ensure "-1" is always visible, since it is always the largest number.
+ if (breadth === 0 && negativeLineNumber != -1) {
+ this.renderGridLineNumber(
+ negativeLineNumber,
+ linePos,
+ startPos,
+ line.breadth,
+ dimensionType,
+ true
+ );
+ continue;
+ }
+ }
+
+ this.renderGridLineNumber(
+ negativeLineNumber,
+ linePos,
+ startPos,
+ line.breadth,
+ dimensionType
+ );
+ }
+ }
+
+ /**
+ * Update the highlighter on the current highlighted node (the one that was
+ * passed as an argument to show(node)). Should be called whenever node's geometry
+ * or grid changes.
+ */
+ _update() {
+ setIgnoreLayoutChanges(true);
+
+ // Set z-index.
+ this.markup.content.setStyle("z-index", this.options.zIndex);
+
+ const root = this.getElement("root");
+ const cells = this.getElement("cells");
+ const areas = this.getElement("areas");
+
+ // Set the grid cells and areas fill to the current grid colour.
+ cells.setAttribute("style", `fill: ${this.color}`);
+ areas.setAttribute("style", `fill: ${this.color}`);
+
+ // Hide the root element and force the reflow in order to get the proper window's
+ // dimensions without increasing them.
+ root.setAttribute("style", "display: none");
+ this.win.document.documentElement.offsetWidth;
+ this._winDimensions = getWindowDimensions(this.win);
+ const { width, height } = this._winDimensions;
+
+ // Updates the <canvas> element's position and size.
+ // It also clear the <canvas>'s drawing context.
+ updateCanvasElement(
+ this.canvas,
+ this._canvasPosition,
+ this.win.devicePixelRatio
+ );
+
+ // Clear the grid area highlights.
+ this.clearGridAreas();
+ this.clearGridCell();
+
+ // Update the current matrix used in our canvas' rendering.
+ const { currentMatrix, hasNodeTransformations } = getCurrentMatrix(
+ this.currentNode,
+ this.win
+ );
+ this.currentMatrix = currentMatrix;
+ this.hasNodeTransformations = hasNodeTransformations;
+
+ // Start drawing the grid fragments.
+ for (let i = 0; i < this.gridData.length; i++) {
+ this.renderFragment(this.gridData[i]);
+ }
+
+ // Display the grid area highlights if needed.
+ if (this.options.showAllGridAreas) {
+ this.showAllGridAreas();
+ } else if (this.options.showGridArea) {
+ this.showGridArea(this.options.showGridArea);
+ }
+
+ // Display the grid cell highlights if needed.
+ if (this.options.showGridCell) {
+ this.showGridCell(this.options.showGridCell);
+ }
+
+ // Display the grid line names if needed.
+ if (this.options.showGridLineNames) {
+ this.showGridLineNames(this.options.showGridLineNames);
+ }
+
+ this._showGrid();
+ this._showGridElements();
+
+ root.setAttribute(
+ "style",
+ `position: absolute; width: ${width}px; height: ${height}px; overflow: hidden`
+ );
+
+ setIgnoreLayoutChanges(false, this.highlighterEnv.document.documentElement);
+ return true;
+ }
+
+ /**
+ * Update the grid information displayed in the grid area info bar.
+ *
+ * @param {GridArea} area
+ * The grid area object.
+ * @param {Object} bounds
+ * A DOMRect-like object represent the grid area rectangle.
+ */
+ _updateGridAreaInfobar(area, bounds) {
+ const { width, height } = bounds;
+ const dim =
+ parseFloat(width.toPrecision(6)) +
+ " \u00D7 " +
+ parseFloat(height.toPrecision(6));
+
+ this.getElement("area-infobar-name").setTextContent(area.name);
+ this.getElement("area-infobar-dimensions").setTextContent(dim);
+
+ const container = this.getElement("area-infobar-container");
+ moveInfobar(container, bounds, this.win, {
+ position: "bottom",
+ hideIfOffscreen: true,
+ });
+ }
+
+ /**
+ * Update the grid information displayed in the grid cell info bar.
+ *
+ * @param {Number} rowNumber
+ * The grid cell's row number.
+ * @param {Number} columnNumber
+ * The grid cell's column number.
+ * @param {Object} bounds
+ * A DOMRect-like object represent the grid cell rectangle.
+ */
+ _updateGridCellInfobar(rowNumber, columnNumber, bounds) {
+ const { width, height } = bounds;
+ const dim =
+ parseFloat(width.toPrecision(6)) +
+ " \u00D7 " +
+ parseFloat(height.toPrecision(6));
+ const position = L10N.getFormatStr(
+ "grid.rowColumnPositions",
+ rowNumber,
+ columnNumber
+ );
+
+ this.getElement("cell-infobar-position").setTextContent(position);
+ this.getElement("cell-infobar-dimensions").setTextContent(dim);
+
+ const container = this.getElement("cell-infobar-container");
+ moveInfobar(container, bounds, this.win, {
+ position: "top",
+ hideIfOffscreen: true,
+ });
+ }
+
+ /**
+ * Update the grid information displayed in the grid line info bar.
+ *
+ * @param {String} gridLineNames
+ * Comma-separated string of names for the grid line.
+ * @param {Number} gridLineNumber
+ * The grid line number.
+ * @param {Number} x
+ * The x-coordinate of the grid line.
+ * @param {Number} y
+ * The y-coordinate of the grid line.
+ */
+ _updateGridLineInfobar(gridLineNames, gridLineNumber, x, y) {
+ this.getElement("line-infobar-number").setTextContent(gridLineNumber);
+ this.getElement("line-infobar-names").setTextContent(gridLineNames);
+
+ const container = this.getElement("line-infobar-container");
+ moveInfobar(
+ container,
+ getBoundsFromPoints([
+ { x, y },
+ { x, y },
+ { x, y },
+ { x, y },
+ ]),
+ this.win
+ );
+ }
+}
+
+exports.CssGridHighlighter = CssGridHighlighter;
diff --git a/devtools/server/actors/highlighters/css-transform.js b/devtools/server/actors/highlighters/css-transform.js
new file mode 100644
index 0000000000..b55c2b229f
--- /dev/null
+++ b/devtools/server/actors/highlighters/css-transform.js
@@ -0,0 +1,265 @@
+/* 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";
+
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const {
+ CanvasFrameAnonymousContentHelper,
+ getComputedStyle,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ setIgnoreLayoutChanges,
+ getNodeBounds,
+} = require("devtools/shared/layout/utils");
+
+// The minimum distance a line should be before it has an arrow marker-end
+const ARROW_LINE_MIN_DISTANCE = 10;
+
+var MARKER_COUNTER = 1;
+
+/**
+ * The CssTransformHighlighter is the class that draws an outline around a
+ * transformed element and an outline around where it would be if untransformed
+ * as well as arrows connecting the 2 outlines' corners.
+ */
+class CssTransformHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+
+ this.ID_CLASS_PREFIX = "css-transform-";
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+ }
+
+ _buildMarkup() {
+ const container = this.markup.createNode({
+ attributes: {
+ class: "highlighter-container",
+ },
+ });
+
+ // The root wrapper is used to unzoom the highlighter when needed.
+ const rootWrapper = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: rootWrapper,
+ attributes: {
+ id: "elements",
+ hidden: "true",
+ width: "100%",
+ height: "100%",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Add a marker tag to the svg root for the arrow tip
+ this.markerId = "arrow-marker-" + MARKER_COUNTER;
+ MARKER_COUNTER++;
+ const marker = this.markup.createSVGNode({
+ nodeType: "marker",
+ parent: svg,
+ attributes: {
+ id: this.markerId,
+ markerWidth: "10",
+ markerHeight: "5",
+ orient: "auto",
+ markerUnits: "strokeWidth",
+ refX: "10",
+ refY: "5",
+ viewBox: "0 0 10 10",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: marker,
+ attributes: {
+ d: "M 0 0 L 10 5 L 0 10 z",
+ fill: "#08C",
+ },
+ });
+
+ const shapesGroup = this.markup.createSVGNode({
+ nodeType: "g",
+ parent: svg,
+ });
+
+ // Create the 2 polygons (transformed and untransformed)
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: shapesGroup,
+ attributes: {
+ id: "untransformed",
+ class: "untransformed",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: shapesGroup,
+ attributes: {
+ id: "transformed",
+ class: "transformed",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Create the arrows
+ for (const nb of ["1", "2", "3", "4"]) {
+ this.markup.createSVGNode({
+ nodeType: "line",
+ parent: shapesGroup,
+ attributes: {
+ id: "line" + nb,
+ class: "line",
+ "marker-end": "url(#" + this.markerId + ")",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ }
+
+ return container;
+ }
+
+ /**
+ * Destroy the nodes. Remove listeners.
+ */
+ destroy() {
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+ this.markup.destroy();
+ }
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ /**
+ * Show the highlighter on a given node
+ */
+ _show() {
+ if (!this._isTransformed(this.currentNode)) {
+ this.hide();
+ return false;
+ }
+
+ return this._update();
+ }
+
+ /**
+ * Checks if the supplied node is transformed and not inline
+ */
+ _isTransformed(node) {
+ const style = getComputedStyle(node);
+ return style && style.transform !== "none" && style.display !== "inline";
+ }
+
+ _setPolygonPoints(quad, id) {
+ const points = [];
+ for (const point of ["p1", "p2", "p3", "p4"]) {
+ points.push(quad[point].x + "," + quad[point].y);
+ }
+ this.getElement(id).setAttribute("points", points.join(" "));
+ }
+
+ _setLinePoints(p1, p2, id) {
+ const line = this.getElement(id);
+ line.setAttribute("x1", p1.x);
+ line.setAttribute("y1", p1.y);
+ line.setAttribute("x2", p2.x);
+ line.setAttribute("y2", p2.y);
+
+ const dist = Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
+ if (dist < ARROW_LINE_MIN_DISTANCE) {
+ line.removeAttribute("marker-end");
+ } else {
+ line.setAttribute("marker-end", "url(#" + this.markerId + ")");
+ }
+ }
+
+ /**
+ * Update the highlighter on the current highlighted node (the one that was
+ * passed as an argument to show(node)).
+ * Should be called whenever node size or attributes change
+ */
+ _update() {
+ setIgnoreLayoutChanges(true);
+
+ // Getting the points for the transformed shape
+ const quads = this.currentQuads.border;
+ if (
+ !quads.length ||
+ quads[0].bounds.width <= 0 ||
+ quads[0].bounds.height <= 0
+ ) {
+ this._hideShapes();
+ return false;
+ }
+
+ const [quad] = quads;
+
+ // Getting the points for the untransformed shape
+ const untransformedQuad = getNodeBounds(this.win, this.currentNode);
+
+ this._setPolygonPoints(quad, "transformed");
+ this._setPolygonPoints(untransformedQuad, "untransformed");
+ for (const nb of ["1", "2", "3", "4"]) {
+ this._setLinePoints(
+ untransformedQuad["p" + nb],
+ quad["p" + nb],
+ "line" + nb
+ );
+ }
+
+ // Adapt to the current zoom
+ this.markup.scaleRootElement(
+ this.currentNode,
+ this.ID_CLASS_PREFIX + "root"
+ );
+
+ this._showShapes();
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ return true;
+ }
+
+ /**
+ * Hide the highlighter, the outline and the infobar.
+ */
+ _hide() {
+ setIgnoreLayoutChanges(true);
+ this._hideShapes();
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ _hideShapes() {
+ this.getElement("elements").setAttribute("hidden", "true");
+ }
+
+ _showShapes() {
+ this.getElement("elements").removeAttribute("hidden");
+ }
+}
+
+exports.CssTransformHighlighter = CssTransformHighlighter;
diff --git a/devtools/server/actors/highlighters/eye-dropper.js b/devtools/server/actors/highlighters/eye-dropper.js
new file mode 100644
index 0000000000..564f85394e
--- /dev/null
+++ b/devtools/server/actors/highlighters/eye-dropper.js
@@ -0,0 +1,581 @@
+/* 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";
+
+// Eye-dropper tool. This is implemented as a highlighter so it can be displayed in the
+// content page.
+// It basically displays a magnifier that tracks mouse moves and shows a magnified version
+// of the page. On click, it samples the color at the pixel being hovered.
+
+const { Ci, Cc } = require("chrome");
+const {
+ CanvasFrameAnonymousContentHelper,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const Services = require("Services");
+const EventEmitter = require("devtools/shared/event-emitter");
+const {
+ rgbToHsl,
+ rgbToColorName,
+} = require("devtools/shared/css/color").colorUtils;
+const {
+ getCurrentZoom,
+ getFrameOffsets,
+} = require("devtools/shared/layout/utils");
+
+loader.lazyGetter(this, "clipboardHelper", () =>
+ Cc["@mozilla.org/widget/clipboardhelper;1"].getService(Ci.nsIClipboardHelper)
+);
+loader.lazyGetter(this, "l10n", () =>
+ Services.strings.createBundle(
+ "chrome://devtools-shared/locale/eyedropper.properties"
+ )
+);
+
+const ZOOM_LEVEL_PREF = "devtools.eyedropper.zoom";
+const FORMAT_PREF = "devtools.defaultColorUnit";
+// Width of the canvas.
+const MAGNIFIER_WIDTH = 96;
+// Height of the canvas.
+const MAGNIFIER_HEIGHT = 96;
+// Start position, when the tool is first shown. This should match the top/left position
+// defined in CSS.
+const DEFAULT_START_POS_X = 100;
+const DEFAULT_START_POS_Y = 100;
+// How long to wait before closing after copy.
+const CLOSE_DELAY = 750;
+
+/**
+ * The EyeDropper is the class that draws the gradient line and
+ * color stops as an overlay on top of a linear-gradient background-image.
+ */
+function EyeDropper(highlighterEnv) {
+ EventEmitter.decorate(this);
+
+ this.highlighterEnv = highlighterEnv;
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ // Get a couple of settings from prefs.
+ this.format = Services.prefs.getCharPref(FORMAT_PREF);
+ this.eyeDropperZoomLevel = Services.prefs.getIntPref(ZOOM_LEVEL_PREF);
+}
+
+EyeDropper.prototype = {
+ ID_CLASS_PREFIX: "eye-dropper-",
+
+ get win() {
+ return this.highlighterEnv.window;
+ },
+
+ _buildMarkup() {
+ // Highlighter main container.
+ const container = this.markup.createNode({
+ attributes: { class: "highlighter-container" },
+ });
+
+ // Wrapper element.
+ const wrapper = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // The magnifier canvas element.
+ this.markup.createNode({
+ parent: wrapper,
+ nodeType: "canvas",
+ attributes: {
+ id: "canvas",
+ class: "canvas",
+ width: MAGNIFIER_WIDTH,
+ height: MAGNIFIER_HEIGHT,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // The color label element.
+ const colorLabelContainer = this.markup.createNode({
+ parent: wrapper,
+ attributes: { class: "color-container" },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "div",
+ parent: colorLabelContainer,
+ attributes: { id: "color-preview", class: "color-preview" },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ this.markup.createNode({
+ nodeType: "div",
+ parent: colorLabelContainer,
+ attributes: { id: "color-value", class: "color-value" },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ return container;
+ },
+
+ destroy() {
+ this.hide();
+ this.markup.destroy();
+ },
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ },
+
+ /**
+ * Show the eye-dropper highlighter.
+ * @param {DOMNode} node The node which document the highlighter should be inserted in.
+ * @param {Object} options The options object may contain the following properties:
+ * - {Boolean} copyOnSelect Whether selecting a color should copy it to the clipboard.
+ */
+ show(node, options = {}) {
+ if (this.highlighterEnv.isXUL) {
+ return false;
+ }
+
+ this.options = options;
+
+ // Get the page's current zoom level.
+ this.pageZoom = getCurrentZoom(this.win);
+
+ // Take a screenshot of the viewport. This needs to be done first otherwise the
+ // eyedropper UI will appear in the screenshot itself (since the UI is injected as
+ // native anonymous content in the page).
+ // Once the screenshot is ready, the magnified area will be drawn.
+ this.prepareImageCapture();
+
+ // Start listening for user events.
+ const { pageListenerTarget } = this.highlighterEnv;
+ pageListenerTarget.addEventListener("mousemove", this);
+ pageListenerTarget.addEventListener("click", this, true);
+ pageListenerTarget.addEventListener("keydown", this);
+ pageListenerTarget.addEventListener("DOMMouseScroll", this);
+ pageListenerTarget.addEventListener("FullZoomChange", this);
+
+ // Show the eye-dropper.
+ this.getElement("root").removeAttribute("hidden");
+
+ // Prepare the canvas context on which we're drawing the magnified page portion.
+ this.ctx = this.getElement("canvas").getCanvasContext();
+ this.ctx.imageSmoothingEnabled = false;
+
+ this.magnifiedArea = {
+ width: MAGNIFIER_WIDTH,
+ height: MAGNIFIER_HEIGHT,
+ x: DEFAULT_START_POS_X,
+ y: DEFAULT_START_POS_Y,
+ };
+
+ this.moveTo(DEFAULT_START_POS_X, DEFAULT_START_POS_Y);
+
+ // Focus the content so the keyboard can be used.
+ this.win.focus();
+
+ // Make sure we receive mouse events when the debugger has paused execution
+ // in the page.
+ this.win.document.setSuppressedEventListener(this);
+
+ return true;
+ },
+
+ /**
+ * Hide the eye-dropper highlighter.
+ */
+ hide() {
+ if (this.highlighterEnv.isXUL) {
+ return;
+ }
+
+ this.pageImage = null;
+
+ const { pageListenerTarget } = this.highlighterEnv;
+
+ if (pageListenerTarget) {
+ pageListenerTarget.removeEventListener("mousemove", this);
+ pageListenerTarget.removeEventListener("click", this, true);
+ pageListenerTarget.removeEventListener("keydown", this);
+ pageListenerTarget.removeEventListener("DOMMouseScroll", this);
+ pageListenerTarget.removeEventListener("FullZoomChange", this);
+ }
+
+ this.getElement("root").setAttribute("hidden", "true");
+ this.getElement("root").removeAttribute("drawn");
+
+ this.emit("hidden");
+
+ this.win.document.setSuppressedEventListener(null);
+ },
+
+ prepareImageCapture() {
+ // Get the image data from the content window.
+ const imageData = getWindowAsImageData(this.win);
+
+ // We need to transform imageData to something drawWindow will consume. An ImageBitmap
+ // works well. We could have used an Image, but doing so results in errors if the page
+ // defines CSP headers.
+ this.win.createImageBitmap(imageData).then(image => {
+ this.pageImage = image;
+ // We likely haven't drawn anything yet (no mousemove events yet), so start now.
+ this.draw();
+
+ // Set an attribute on the root element to be able to run tests after the first draw
+ // was done.
+ this.getElement("root").setAttribute("drawn", "true");
+ });
+ },
+
+ /**
+ * Get the number of cells (blown-up pixels) per direction in the grid.
+ */
+ get cellsWide() {
+ // Canvas will render whole "pixels" (cells) only, and an even number at that. Round
+ // up to the nearest even number of pixels.
+ let cellsWide = Math.ceil(
+ this.magnifiedArea.width / this.eyeDropperZoomLevel
+ );
+ cellsWide += cellsWide % 2;
+
+ return cellsWide;
+ },
+
+ /**
+ * Get the size of each cell (blown-up pixel) in the grid.
+ */
+ get cellSize() {
+ return this.magnifiedArea.width / this.cellsWide;
+ },
+
+ /**
+ * Get index of cell in the center of the grid.
+ */
+ get centerCell() {
+ return Math.floor(this.cellsWide / 2);
+ },
+
+ /**
+ * Get color of center cell in the grid.
+ */
+ get centerColor() {
+ const pos = this.centerCell * this.cellSize + this.cellSize / 2;
+ const rgb = this.ctx.getImageData(pos, pos, 1, 1).data;
+ return rgb;
+ },
+
+ draw() {
+ // If the image of the page isn't ready yet, bail out, we'll draw later on mousemove.
+ if (!this.pageImage) {
+ return;
+ }
+
+ const { width, height, x, y } = this.magnifiedArea;
+
+ const zoomedWidth = width / this.eyeDropperZoomLevel;
+ const zoomedHeight = height / this.eyeDropperZoomLevel;
+
+ const sx = x - zoomedWidth / 2;
+ const sy = y - zoomedHeight / 2;
+ const sw = zoomedWidth;
+ const sh = zoomedHeight;
+
+ this.ctx.drawImage(this.pageImage, sx, sy, sw, sh, 0, 0, width, height);
+
+ // Draw the grid on top, but only at 3x or more, otherwise it's too busy.
+ if (this.eyeDropperZoomLevel > 2) {
+ this.drawGrid();
+ }
+
+ this.drawCrosshair();
+
+ // Update the color preview and value.
+ const rgb = this.centerColor;
+ this.getElement("color-preview").setAttribute(
+ "style",
+ `background-color:${toColorString(rgb, "rgb")};`
+ );
+ this.getElement("color-value").setTextContent(
+ toColorString(rgb, this.format)
+ );
+ },
+
+ /**
+ * Draw a grid on the canvas representing pixel boundaries.
+ */
+ drawGrid() {
+ const { width, height } = this.magnifiedArea;
+
+ this.ctx.lineWidth = 1;
+ this.ctx.strokeStyle = "rgba(143, 143, 143, 0.2)";
+
+ for (let i = 0; i < width; i += this.cellSize) {
+ this.ctx.beginPath();
+ this.ctx.moveTo(i - 0.5, 0);
+ this.ctx.lineTo(i - 0.5, height);
+ this.ctx.stroke();
+
+ this.ctx.beginPath();
+ this.ctx.moveTo(0, i - 0.5);
+ this.ctx.lineTo(width, i - 0.5);
+ this.ctx.stroke();
+ }
+ },
+
+ /**
+ * Draw a box on the canvas to highlight the center cell.
+ */
+ drawCrosshair() {
+ const pos = this.centerCell * this.cellSize;
+
+ this.ctx.lineWidth = 1;
+ this.ctx.lineJoin = "miter";
+ this.ctx.strokeStyle = "rgba(0, 0, 0, 1)";
+ this.ctx.strokeRect(
+ pos - 1.5,
+ pos - 1.5,
+ this.cellSize + 2,
+ this.cellSize + 2
+ );
+
+ this.ctx.strokeStyle = "rgba(255, 255, 255, 1)";
+ this.ctx.strokeRect(pos - 0.5, pos - 0.5, this.cellSize, this.cellSize);
+ },
+
+ handleEvent(e) {
+ switch (e.type) {
+ case "mousemove":
+ // We might be getting an event from a child frame, so account for the offset.
+ const [xOffset, yOffset] = getFrameOffsets(this.win, e.target);
+ const x = xOffset + e.pageX - this.win.scrollX;
+ const y = yOffset + e.pageY - this.win.scrollY;
+ // Update the zoom area.
+ this.magnifiedArea.x = x * this.pageZoom;
+ this.magnifiedArea.y = y * this.pageZoom;
+ // Redraw the portion of the screenshot that is now under the mouse.
+ this.draw();
+ // And move the eye-dropper's UI so it follows the mouse.
+ this.moveTo(x, y);
+ break;
+ // Note: when events are suppressed we will only get mousedown/mouseup and
+ // not any click events.
+ case "click":
+ case "mouseup":
+ this.selectColor();
+ break;
+ case "keydown":
+ this.handleKeyDown(e);
+ break;
+ case "DOMMouseScroll":
+ // Prevent scrolling. That's because we only took a screenshot of the viewport, so
+ // scrolling out of the viewport wouldn't draw the expected things. In the future
+ // we can take the screenshot again on scroll, but for now it doesn't seem
+ // important.
+ e.preventDefault();
+ break;
+ case "FullZoomChange":
+ this.hide();
+ this.show();
+ break;
+ }
+ },
+
+ moveTo(x, y) {
+ const root = this.getElement("root");
+ root.setAttribute("style", `top:${y}px;left:${x}px;`);
+
+ // Move the label container to the top if the magnifier is close to the bottom edge.
+ if (y >= this.win.innerHeight - MAGNIFIER_HEIGHT) {
+ root.setAttribute("top", "");
+ } else {
+ root.removeAttribute("top");
+ }
+
+ // Also offset the label container to the right or left if the magnifier is close to
+ // the edge.
+ root.removeAttribute("left");
+ root.removeAttribute("right");
+ if (x <= MAGNIFIER_WIDTH) {
+ root.setAttribute("right", "");
+ } else if (x >= this.win.innerWidth - MAGNIFIER_WIDTH) {
+ root.setAttribute("left", "");
+ }
+ },
+
+ /**
+ * Select the current color that's being previewed. Depending on the current options,
+ * selecting might mean copying to the clipboard and closing the
+ */
+ selectColor() {
+ let onColorSelected = Promise.resolve();
+ if (this.options.copyOnSelect) {
+ onColorSelected = this.copyColor();
+ }
+
+ this.emit("selected", toColorString(this.centerColor, this.format));
+ onColorSelected.then(() => this.hide(), console.error);
+ },
+
+ /**
+ * Handler for the keydown event. Either select the color or move the panel in a
+ * direction depending on the key pressed.
+ */
+ handleKeyDown(e) {
+ // Bail out early if any unsupported modifier is used, so that we let
+ // keyboard shortcuts through.
+ if (e.metaKey || e.ctrlKey || e.altKey) {
+ return;
+ }
+
+ if (e.keyCode === e.DOM_VK_RETURN) {
+ this.selectColor();
+ e.preventDefault();
+ return;
+ }
+
+ if (e.keyCode === e.DOM_VK_ESCAPE) {
+ this.emit("canceled");
+ this.hide();
+ e.preventDefault();
+ return;
+ }
+
+ let offsetX = 0;
+ let offsetY = 0;
+ let modifier = 1;
+
+ if (e.keyCode === e.DOM_VK_LEFT) {
+ offsetX = -1;
+ } else if (e.keyCode === e.DOM_VK_RIGHT) {
+ offsetX = 1;
+ } else if (e.keyCode === e.DOM_VK_UP) {
+ offsetY = -1;
+ } else if (e.keyCode === e.DOM_VK_DOWN) {
+ offsetY = 1;
+ }
+
+ if (e.shiftKey) {
+ modifier = 10;
+ }
+
+ offsetY *= modifier;
+ offsetX *= modifier;
+
+ if (offsetX !== 0 || offsetY !== 0) {
+ this.magnifiedArea.x = cap(
+ this.magnifiedArea.x + offsetX,
+ 0,
+ this.win.innerWidth * this.pageZoom
+ );
+ this.magnifiedArea.y = cap(
+ this.magnifiedArea.y + offsetY,
+ 0,
+ this.win.innerHeight * this.pageZoom
+ );
+
+ this.draw();
+
+ this.moveTo(
+ this.magnifiedArea.x / this.pageZoom,
+ this.magnifiedArea.y / this.pageZoom
+ );
+
+ e.preventDefault();
+ }
+ },
+
+ /**
+ * Copy the currently inspected color to the clipboard.
+ * @return {Promise} Resolves when the copy has been done (after a delay that is used to
+ * let users know that something was copied).
+ */
+ copyColor() {
+ // Copy to the clipboard.
+ const color = toColorString(this.centerColor, this.format);
+ clipboardHelper.copyString(color);
+
+ // Provide some feedback.
+ this.getElement("color-value").setTextContent(
+ "✓ " + l10n.GetStringFromName("colorValue.copied")
+ );
+
+ // Hide the tool after a delay.
+ clearTimeout(this._copyTimeout);
+ return new Promise(resolve => {
+ this._copyTimeout = setTimeout(resolve, CLOSE_DELAY);
+ });
+ },
+};
+
+exports.EyeDropper = EyeDropper;
+
+/**
+ * Draw the visible portion of the window on a canvas and get the resulting ImageData.
+ * @param {Window} win
+ * @return {ImageData} The image data for the window.
+ */
+function getWindowAsImageData(win) {
+ const canvas = win.document.createElementNS(
+ "http://www.w3.org/1999/xhtml",
+ "canvas"
+ );
+ const scale = getCurrentZoom(win);
+ const width = win.innerWidth;
+ const height = win.innerHeight;
+ canvas.width = width * scale;
+ canvas.height = height * scale;
+ canvas.mozOpaque = true;
+
+ const ctx = canvas.getContext("2d");
+
+ ctx.scale(scale, scale);
+ ctx.drawWindow(win, win.scrollX, win.scrollY, width, height, "#fff");
+
+ return ctx.getImageData(0, 0, canvas.width, canvas.height);
+}
+
+/**
+ * Get a formatted CSS color string from a color value.
+ * @param {array} rgb Rgb values of a color to format.
+ * @param {string} format Format of string. One of "hex", "rgb", "hsl", "name".
+ * @return {string} Formatted color value, e.g. "#FFF" or "hsl(20, 10%, 10%)".
+ */
+function toColorString(rgb, format) {
+ const [r, g, b] = rgb;
+
+ switch (format) {
+ case "hex":
+ return hexString(rgb);
+ case "rgb":
+ return "rgb(" + r + ", " + g + ", " + b + ")";
+ case "hsl":
+ const [h, s, l] = rgbToHsl(rgb);
+ return "hsl(" + h + ", " + s + "%, " + l + "%)";
+ case "name":
+ const str = rgbToColorName(r, g, b) || hexString(rgb);
+ return str;
+ default:
+ return hexString(rgb);
+ }
+}
+
+/**
+ * Produce a hex-formatted color string from rgb values.
+ * @param {array} rgb Rgb values of color to stringify.
+ * @return {string} Hex formatted string for color, e.g. "#FFEE00".
+ */
+function hexString([r, g, b]) {
+ const val = (1 << 24) + (r << 16) + (g << 8) + (b << 0);
+ return "#" + val.toString(16).substr(-6);
+}
+
+function cap(value, min, max) {
+ return Math.max(min, Math.min(value, max));
+}
diff --git a/devtools/server/actors/highlighters/flexbox.js b/devtools/server/actors/highlighters/flexbox.js
new file mode 100644
index 0000000000..2b4e751a06
--- /dev/null
+++ b/devtools/server/actors/highlighters/flexbox.js
@@ -0,0 +1,1037 @@
+/* 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";
+
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const { apply } = require("devtools/shared/layout/dom-matrix-2d");
+const {
+ CANVAS_SIZE,
+ DEFAULT_COLOR,
+ clearRect,
+ drawLine,
+ drawRect,
+ getCurrentMatrix,
+ updateCanvasElement,
+ updateCanvasPosition,
+} = require("devtools/server/actors/highlighters/utils/canvas");
+const {
+ CanvasFrameAnonymousContentHelper,
+ getComputedStyle,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ getAbsoluteScrollOffsetsForNode,
+ getCurrentZoom,
+ getDisplayPixelRatio,
+ getUntransformedQuad,
+ getWindowDimensions,
+ setIgnoreLayoutChanges,
+} = require("devtools/shared/layout/utils");
+
+const FLEXBOX_LINES_PROPERTIES = {
+ edge: {
+ lineDash: [5, 3],
+ },
+ item: {
+ lineDash: [0, 0],
+ },
+ alignItems: {
+ lineDash: [0, 0],
+ },
+};
+
+const FLEXBOX_CONTAINER_PATTERN_LINE_DASH = [5, 3]; // px
+const FLEXBOX_CONTAINER_PATTERN_WIDTH = 14; // px
+const FLEXBOX_CONTAINER_PATTERN_HEIGHT = 14; // px
+const FLEXBOX_JUSTIFY_CONTENT_PATTERN_WIDTH = 7; // px
+const FLEXBOX_JUSTIFY_CONTENT_PATTERN_HEIGHT = 7; // px
+
+/**
+ * Cached used by `FlexboxHighlighter.getFlexContainerPattern`.
+ */
+const gCachedFlexboxPattern = new Map();
+
+const FLEXBOX = "flexbox";
+const JUSTIFY_CONTENT = "justify-content";
+
+/**
+ * The FlexboxHighlighter is the class that overlays a visual canvas on top of
+ * display: [inline-]flex elements.
+ *
+ * @param {String} options.color
+ * The color that should be used to draw the highlighter for this flexbox.
+ * Structure:
+ * <div class="highlighter-container">
+ * <div id="flexbox-root" class="flexbox-root">
+ * <canvas id="flexbox-canvas"
+ * class="flexbox-canvas"
+ * width="4096"
+ * height="4096"
+ * hidden="true">
+ * </canvas>
+ * </div>
+ * </div>
+ */
+class FlexboxHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+
+ this.ID_CLASS_PREFIX = "flexbox-";
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ this.onPageHide = this.onPageHide.bind(this);
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ this.highlighterEnv.on("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = highlighterEnv;
+ pageListenerTarget.addEventListener("pagehide", this.onPageHide);
+
+ // Initialize the <canvas> position to the top left corner of the page
+ this._canvasPosition = {
+ x: 0,
+ y: 0,
+ };
+
+ this._ignoreZoom = true;
+
+ // Calling `updateCanvasPosition` anyway since the highlighter could be initialized
+ // on a page that has scrolled already.
+ updateCanvasPosition(
+ this._canvasPosition,
+ this._scroll,
+ this.win,
+ this._winDimensions
+ );
+ }
+
+ _buildMarkup() {
+ const container = this.markup.createNode({
+ attributes: {
+ class: "highlighter-container",
+ },
+ });
+
+ const root = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // We use a <canvas> element because there is an arbitrary number of items and texts
+ // to draw which wouldn't be possible with HTML or SVG without having to insert and
+ // remove the whole markup on every update.
+ this.markup.createNode({
+ parent: root,
+ nodeType: "canvas",
+ attributes: {
+ id: "canvas",
+ class: "canvas",
+ hidden: "true",
+ width: CANVAS_SIZE,
+ height: CANVAS_SIZE,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ return container;
+ }
+
+ clearCache() {
+ gCachedFlexboxPattern.clear();
+ }
+
+ destroy() {
+ const { highlighterEnv } = this;
+ highlighterEnv.off("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = highlighterEnv;
+
+ if (pageListenerTarget) {
+ pageListenerTarget.removeEventListener("pagehide", this.onPageHide);
+ }
+
+ this.markup.destroy();
+
+ // Clear the pattern cache to avoid dead object exceptions (Bug 1342051).
+ this.clearCache();
+
+ this.axes = null;
+ this.crossAxisDirection = null;
+ this.flexData = null;
+ this.mainAxisDirection = null;
+ this.transform = null;
+
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+ }
+
+ /**
+ * Draw the justify content for a given flex item (left, top, right, bottom) position.
+ */
+ drawJustifyContent(left, top, right, bottom) {
+ const { devicePixelRatio } = this.win;
+ this.ctx.fillStyle = this.getJustifyContentPattern(devicePixelRatio);
+ drawRect(this.ctx, left, top, right, bottom, this.currentMatrix);
+ this.ctx.fill();
+ }
+
+ get canvas() {
+ return this.getElement("canvas");
+ }
+
+ get color() {
+ return this.options.color || DEFAULT_COLOR;
+ }
+
+ get container() {
+ return this.currentNode;
+ }
+
+ get ctx() {
+ return this.canvas.getCanvasContext("2d");
+ }
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ /**
+ * Gets the flexbox container pattern used to render the container regions.
+ *
+ * @param {Number} devicePixelRatio
+ * The device pixel ratio we want the pattern for.
+ * @return {CanvasPattern} flex container pattern.
+ */
+ getFlexContainerPattern(devicePixelRatio) {
+ let flexboxPatternMap = null;
+
+ if (gCachedFlexboxPattern.has(devicePixelRatio)) {
+ flexboxPatternMap = gCachedFlexboxPattern.get(devicePixelRatio);
+ } else {
+ flexboxPatternMap = new Map();
+ }
+
+ if (gCachedFlexboxPattern.has(FLEXBOX)) {
+ return gCachedFlexboxPattern.get(FLEXBOX);
+ }
+
+ // Create the diagonal lines pattern for the rendering the flexbox gaps.
+ const canvas = this.markup.createNode({ nodeType: "canvas" });
+ const width = (canvas.width =
+ FLEXBOX_CONTAINER_PATTERN_WIDTH * devicePixelRatio);
+ const height = (canvas.height =
+ FLEXBOX_CONTAINER_PATTERN_HEIGHT * devicePixelRatio);
+
+ const ctx = canvas.getContext("2d");
+ ctx.save();
+ ctx.setLineDash(FLEXBOX_CONTAINER_PATTERN_LINE_DASH);
+ ctx.beginPath();
+ ctx.translate(0.5, 0.5);
+
+ ctx.moveTo(0, 0);
+ ctx.lineTo(width, height);
+
+ ctx.strokeStyle = this.color;
+ ctx.stroke();
+ ctx.restore();
+
+ const pattern = ctx.createPattern(canvas, "repeat");
+ flexboxPatternMap.set(FLEXBOX, pattern);
+ gCachedFlexboxPattern.set(devicePixelRatio, flexboxPatternMap);
+
+ return pattern;
+ }
+
+ /**
+ * Gets the flexbox justify content pattern used to render the justify content regions.
+ *
+ * @param {Number} devicePixelRatio
+ * The device pixel ratio we want the pattern for.
+ * @return {CanvasPattern} flex justify content pattern.
+ */
+ getJustifyContentPattern(devicePixelRatio) {
+ let flexboxPatternMap = null;
+
+ if (gCachedFlexboxPattern.has(devicePixelRatio)) {
+ flexboxPatternMap = gCachedFlexboxPattern.get(devicePixelRatio);
+ } else {
+ flexboxPatternMap = new Map();
+ }
+
+ if (flexboxPatternMap.has(JUSTIFY_CONTENT)) {
+ return flexboxPatternMap.get(JUSTIFY_CONTENT);
+ }
+
+ // Create the inversed diagonal lines pattern
+ // for the rendering the justify content gaps.
+ const canvas = this.markup.createNode({ nodeType: "canvas" });
+ const zoom = getCurrentZoom(this.win);
+ const width = (canvas.width =
+ FLEXBOX_JUSTIFY_CONTENT_PATTERN_WIDTH * devicePixelRatio * zoom);
+ const height = (canvas.height =
+ FLEXBOX_JUSTIFY_CONTENT_PATTERN_HEIGHT * devicePixelRatio * zoom);
+
+ const ctx = canvas.getContext("2d");
+ ctx.save();
+ ctx.setLineDash(FLEXBOX_CONTAINER_PATTERN_LINE_DASH);
+ ctx.beginPath();
+ ctx.translate(0.5, 0.5);
+
+ ctx.moveTo(0, height);
+ ctx.lineTo(width, 0);
+
+ ctx.strokeStyle = this.color;
+ ctx.stroke();
+ ctx.restore();
+
+ const pattern = ctx.createPattern(canvas, "repeat");
+ flexboxPatternMap.set(JUSTIFY_CONTENT, pattern);
+ gCachedFlexboxPattern.set(devicePixelRatio, flexboxPatternMap);
+
+ return pattern;
+ }
+
+ /**
+ * The AutoRefreshHighlighter's _hasMoved method returns true only if the
+ * element's quads have changed. Override it so it also returns true if the
+ * flex container and its flex items have changed.
+ */
+ _hasMoved() {
+ const hasMoved = AutoRefreshHighlighter.prototype._hasMoved.call(this);
+
+ if (!this.computedStyle) {
+ this.computedStyle = getComputedStyle(this.container);
+ }
+
+ const flex = this.container.getAsFlexContainer();
+
+ const oldCrossAxisDirection = this.crossAxisDirection;
+ this.crossAxisDirection = flex ? flex.crossAxisDirection : null;
+ const newCrossAxisDirection = this.crossAxisDirection;
+
+ const oldMainAxisDirection = this.mainAxisDirection;
+ this.mainAxisDirection = flex ? flex.mainAxisDirection : null;
+ const newMainAxisDirection = this.mainAxisDirection;
+
+ // Concatenate the axes to simplify conditionals.
+ this.axes = `${this.mainAxisDirection} ${this.crossAxisDirection}`;
+
+ const oldFlexData = this.flexData;
+ this.flexData = getFlexData(this.container);
+ const hasFlexDataChanged = compareFlexData(oldFlexData, this.flexData);
+
+ const oldAlignItems = this.alignItemsValue;
+ this.alignItemsValue = this.computedStyle.alignItems;
+ const newAlignItems = this.alignItemsValue;
+
+ const oldFlexDirection = this.flexDirection;
+ this.flexDirection = this.computedStyle.flexDirection;
+ const newFlexDirection = this.flexDirection;
+
+ const oldFlexWrap = this.flexWrap;
+ this.flexWrap = this.computedStyle.flexWrap;
+ const newFlexWrap = this.flexWrap;
+
+ const oldJustifyContent = this.justifyContentValue;
+ this.justifyContentValue = this.computedStyle.justifyContent;
+ const newJustifyContent = this.justifyContentValue;
+
+ const oldTransform = this.transformValue;
+ this.transformValue = this.computedStyle.transform;
+ const newTransform = this.transformValue;
+
+ return (
+ hasMoved ||
+ hasFlexDataChanged ||
+ oldAlignItems !== newAlignItems ||
+ oldFlexDirection !== newFlexDirection ||
+ oldFlexWrap !== newFlexWrap ||
+ oldJustifyContent !== newJustifyContent ||
+ oldCrossAxisDirection !== newCrossAxisDirection ||
+ oldMainAxisDirection !== newMainAxisDirection ||
+ oldTransform !== newTransform
+ );
+ }
+
+ _hide() {
+ this.alignItemsValue = null;
+ this.computedStyle = null;
+ this.flexData = null;
+ this.flexDirection = null;
+ this.flexWrap = null;
+ this.justifyContentValue = null;
+
+ setIgnoreLayoutChanges(true);
+ this._hideFlexbox();
+ setIgnoreLayoutChanges(false, this.highlighterEnv.document.documentElement);
+ }
+
+ _hideFlexbox() {
+ this.getElement("canvas").setAttribute("hidden", "true");
+ }
+
+ /**
+ * The <canvas>'s position needs to be updated if the page scrolls too much, in order
+ * to give the illusion that it always covers the viewport.
+ */
+ _scrollUpdate() {
+ const hasUpdated = updateCanvasPosition(
+ this._canvasPosition,
+ this._scroll,
+ this.win,
+ this._winDimensions
+ );
+
+ if (hasUpdated) {
+ this._update();
+ }
+ }
+
+ _show() {
+ this._hide();
+ return this._update();
+ }
+
+ _showFlexbox() {
+ this.getElement("canvas").removeAttribute("hidden");
+ }
+
+ /**
+ * If a page hide event is triggered for current window's highlighter, hide the
+ * highlighter.
+ */
+ onPageHide({ target }) {
+ if (target.defaultView === this.win) {
+ this.hide();
+ }
+ }
+
+ /**
+ * Called when the page will-navigate. Used to hide the flexbox highlighter and clear
+ * the cached gap patterns and avoid using DeadWrapper obejcts as gap patterns the
+ * next time.
+ */
+ onWillNavigate({ isTopLevel }) {
+ this.clearCache();
+
+ if (isTopLevel) {
+ this.hide();
+ }
+ }
+
+ renderFlexContainer() {
+ if (!this.currentQuads.content || !this.currentQuads.content[0]) {
+ return;
+ }
+
+ const { devicePixelRatio } = this.win;
+ const containerQuad = getUntransformedQuad(this.container, "content");
+ const { width, height } = containerQuad.getBounds();
+
+ this.setupCanvas({
+ lineDash: FLEXBOX_LINES_PROPERTIES.alignItems.lineDash,
+ lineWidthMultiplier: 2,
+ });
+
+ this.ctx.fillStyle = this.getFlexContainerPattern(devicePixelRatio);
+
+ drawRect(this.ctx, 0, 0, width, height, this.currentMatrix);
+
+ // Find current angle of outer flex element by measuring the angle of two arbitrary
+ // points, then rotate canvas, so the hash pattern stays 45deg to the boundary.
+ const p1 = apply(this.currentMatrix, [0, 0]);
+ const p2 = apply(this.currentMatrix, [1, 0]);
+ const angleRad = Math.atan2(p2[1] - p1[1], p2[0] - p1[0]);
+ this.ctx.rotate(angleRad);
+
+ this.ctx.fill();
+ this.ctx.stroke();
+ this.ctx.restore();
+ }
+
+ renderFlexItems() {
+ if (
+ !this.flexData ||
+ !this.currentQuads.content ||
+ !this.currentQuads.content[0]
+ ) {
+ return;
+ }
+
+ this.setupCanvas({
+ lineDash: FLEXBOX_LINES_PROPERTIES.item.lineDash,
+ });
+
+ for (const flexLine of this.flexData.lines) {
+ for (const flexItem of flexLine.items) {
+ const { left, top, right, bottom } = flexItem.rect;
+
+ clearRect(this.ctx, left, top, right, bottom, this.currentMatrix);
+ drawRect(this.ctx, left, top, right, bottom, this.currentMatrix);
+ this.ctx.stroke();
+ }
+ }
+
+ this.ctx.restore();
+ }
+
+ renderFlexLines() {
+ if (
+ !this.flexData ||
+ !this.currentQuads.content ||
+ !this.currentQuads.content[0]
+ ) {
+ return;
+ }
+
+ const lineWidth = getDisplayPixelRatio(this.win);
+ const options = { matrix: this.currentMatrix };
+ const {
+ width: containerWidth,
+ height: containerHeight,
+ } = getUntransformedQuad(this.container, "content").getBounds();
+
+ this.setupCanvas({
+ useContainerScrollOffsets: true,
+ });
+
+ for (const flexLine of this.flexData.lines) {
+ const { crossStart, crossSize } = flexLine;
+
+ switch (this.axes) {
+ case "horizontal-lr vertical-tb":
+ case "horizontal-lr vertical-bt":
+ case "horizontal-rl vertical-tb":
+ case "horizontal-rl vertical-bt":
+ clearRect(
+ this.ctx,
+ 0,
+ crossStart,
+ containerWidth,
+ crossStart + crossSize,
+ this.currentMatrix
+ );
+
+ // Avoid drawing the start flex line when they overlap with the flex container.
+ if (crossStart != 0) {
+ drawLine(
+ this.ctx,
+ 0,
+ crossStart,
+ containerWidth,
+ crossStart,
+ options
+ );
+ this.ctx.stroke();
+ }
+
+ // Avoid drawing the end flex line when they overlap with the flex container.
+ if (crossStart + crossSize < containerHeight - lineWidth * 2) {
+ drawLine(
+ this.ctx,
+ 0,
+ crossStart + crossSize,
+ containerWidth,
+ crossStart + crossSize,
+ options
+ );
+ this.ctx.stroke();
+ }
+ break;
+ case "vertical-tb horizontal-lr":
+ case "vertical-bt horizontal-rl":
+ clearRect(
+ this.ctx,
+ crossStart,
+ 0,
+ crossStart + crossSize,
+ containerHeight,
+ this.currentMatrix
+ );
+
+ // Avoid drawing the start flex line when they overlap with the flex container.
+ if (crossStart != 0) {
+ drawLine(
+ this.ctx,
+ crossStart,
+ 0,
+ crossStart,
+ containerHeight,
+ options
+ );
+ this.ctx.stroke();
+ }
+
+ // Avoid drawing the end flex line when they overlap with the flex container.
+ if (crossStart + crossSize < containerWidth - lineWidth * 2) {
+ drawLine(
+ this.ctx,
+ crossStart + crossSize,
+ 0,
+ crossStart + crossSize,
+ containerHeight,
+ options
+ );
+ this.ctx.stroke();
+ }
+ break;
+ case "vertical-bt horizontal-lr":
+ case "vertical-tb horizontal-rl":
+ clearRect(
+ this.ctx,
+ containerWidth - crossStart,
+ 0,
+ containerWidth - crossStart - crossSize,
+ containerHeight,
+ this.currentMatrix
+ );
+
+ // Avoid drawing the start flex line when they overlap with the flex container.
+ if (crossStart != 0) {
+ drawLine(
+ this.ctx,
+ containerWidth - crossStart,
+ 0,
+ containerWidth - crossStart,
+ containerHeight,
+ options
+ );
+ this.ctx.stroke();
+ }
+
+ // Avoid drawing the end flex line when they overlap with the flex container.
+ if (crossStart + crossSize < containerWidth - lineWidth * 2) {
+ drawLine(
+ this.ctx,
+ containerWidth - crossStart - crossSize,
+ 0,
+ containerWidth - crossStart - crossSize,
+ containerHeight,
+ options
+ );
+ this.ctx.stroke();
+ }
+ break;
+ }
+ }
+
+ this.ctx.restore();
+ }
+
+ /**
+ * Clear the whole alignment container along the main axis for each flex item.
+ */
+ // eslint-disable-next-line complexity
+ renderJustifyContent() {
+ if (
+ !this.flexData ||
+ !this.currentQuads.content ||
+ !this.currentQuads.content[0]
+ ) {
+ return;
+ }
+
+ const {
+ width: containerWidth,
+ height: containerHeight,
+ } = getUntransformedQuad(this.container, "content").getBounds();
+
+ this.setupCanvas({
+ lineDash: FLEXBOX_LINES_PROPERTIES.alignItems.lineDash,
+ offset: (getDisplayPixelRatio(this.win) / 2) % 1,
+ skipLineAndStroke: true,
+ useContainerScrollOffsets: true,
+ });
+
+ for (const flexLine of this.flexData.lines) {
+ const { crossStart, crossSize } = flexLine;
+ let mainStart = 0;
+
+ // In these two situations mainStart goes from right to left so set it's
+ // value as appropriate.
+ if (
+ this.axes === "horizontal-lr vertical-bt" ||
+ this.axes === "horizontal-rl vertical-tb"
+ ) {
+ mainStart = containerWidth;
+ }
+
+ for (const flexItem of flexLine.items) {
+ const { left, top, right, bottom } = flexItem.rect;
+
+ switch (this.axes) {
+ case "horizontal-lr vertical-tb":
+ case "horizontal-rl vertical-bt":
+ this.drawJustifyContent(
+ mainStart,
+ crossStart,
+ left,
+ crossStart + crossSize
+ );
+ mainStart = right;
+ break;
+ case "horizontal-lr vertical-bt":
+ case "horizontal-rl vertical-tb":
+ this.drawJustifyContent(
+ right,
+ crossStart,
+ mainStart,
+ crossStart + crossSize
+ );
+ mainStart = left;
+ break;
+ case "vertical-tb horizontal-lr":
+ case "vertical-bt horizontal-rl":
+ this.drawJustifyContent(
+ crossStart,
+ mainStart,
+ crossStart + crossSize,
+ top
+ );
+ mainStart = bottom;
+ break;
+ case "vertical-bt horizontal-lr":
+ case "vertical-tb horizontal-rl":
+ this.drawJustifyContent(
+ containerWidth - crossStart - crossSize,
+ mainStart,
+ containerWidth - crossStart,
+ top
+ );
+ mainStart = bottom;
+ break;
+ }
+ }
+
+ // Draw the last justify-content area after the last flex item.
+ switch (this.axes) {
+ case "horizontal-lr vertical-tb":
+ case "horizontal-rl vertical-bt":
+ this.drawJustifyContent(
+ mainStart,
+ crossStart,
+ containerWidth,
+ crossStart + crossSize
+ );
+ break;
+ case "horizontal-lr vertical-bt":
+ case "horizontal-rl vertical-tb":
+ this.drawJustifyContent(
+ 0,
+ crossStart,
+ mainStart,
+ crossStart + crossSize
+ );
+ break;
+ case "vertical-tb horizontal-lr":
+ case "vertical-bt horizontal-rl":
+ this.drawJustifyContent(
+ crossStart,
+ mainStart,
+ crossStart + crossSize,
+ containerHeight
+ );
+ break;
+ case "vertical-bt horizontal-lr":
+ case "vertical-tb horizontal-rl":
+ this.drawJustifyContent(
+ containerWidth - crossStart - crossSize,
+ mainStart,
+ containerWidth - crossStart,
+ containerHeight
+ );
+ break;
+ }
+ }
+
+ this.ctx.restore();
+ }
+
+ /**
+ * Set up the canvas with the given options prior to drawing.
+ *
+ * @param {String} [options.lineDash = null]
+ * An Array of numbers that specify distances to alternately draw a
+ * line and a gap (in coordinate space units). If the number of
+ * elements in the array is odd, the elements of the array get copied
+ * and concatenated. For example, [5, 15, 25] will become
+ * [5, 15, 25, 5, 15, 25]. If the array is empty, the line dash list is
+ * cleared and line strokes return to being solid.
+ *
+ * We use the following constants here:
+ * FLEXBOX_LINES_PROPERTIES.edge.lineDash,
+ * FLEXBOX_LINES_PROPERTIES.item.lineDash
+ * FLEXBOX_LINES_PROPERTIES.alignItems.lineDash
+ * @param {Number} [options.lineWidthMultiplier = 1]
+ * The width of the line.
+ * @param {Number} [options.offset = `(displayPixelRatio / 2) % 1`]
+ * The single line width used to obtain a crisp line.
+ * @param {Boolean} [options.skipLineAndStroke = false]
+ * Skip the setting of lineWidth and strokeStyle.
+ * @param {Boolean} [options.useContainerScrollOffsets = false]
+ * Take the flexbox container's scroll and zoom offsets into account.
+ * This is needed for drawing flex lines and justify content when the
+ * flexbox container itself is display:scroll.
+ */
+ setupCanvas({
+ lineDash = null,
+ lineWidthMultiplier = 1,
+ offset = (getDisplayPixelRatio(this.win) / 2) % 1,
+ skipLineAndStroke = false,
+ useContainerScrollOffsets = false,
+ }) {
+ const { devicePixelRatio } = this.win;
+ const lineWidth = getDisplayPixelRatio(this.win);
+ const zoom = getCurrentZoom(this.win);
+ const style = getComputedStyle(this.container);
+ const position = style.position;
+ let offsetX = this._canvasPosition.x;
+ let offsetY = this._canvasPosition.y;
+
+ if (useContainerScrollOffsets) {
+ offsetX += this.container.scrollLeft / zoom;
+ offsetY += this.container.scrollTop / zoom;
+ }
+
+ // If the flexbox container is position:fixed we need to subtract the scroll
+ // positions of all ancestral elements.
+ if (position === "fixed") {
+ const { scrollLeft, scrollTop } = getAbsoluteScrollOffsetsForNode(
+ this.container
+ );
+ offsetX -= scrollLeft / zoom;
+ offsetY -= scrollTop / zoom;
+ }
+
+ const canvasX = Math.round(offsetX * devicePixelRatio * zoom);
+ const canvasY = Math.round(offsetY * devicePixelRatio * zoom);
+
+ this.ctx.save();
+ this.ctx.translate(offset - canvasX, offset - canvasY);
+
+ if (lineDash) {
+ this.ctx.setLineDash(lineDash);
+ }
+
+ if (!skipLineAndStroke) {
+ this.ctx.lineWidth = lineWidth * lineWidthMultiplier;
+ this.ctx.strokeStyle = this.color;
+ }
+ }
+
+ _update() {
+ setIgnoreLayoutChanges(true);
+
+ const root = this.getElement("root");
+
+ // Hide the root element and force the reflow in order to get the proper window's
+ // dimensions without increasing them.
+ root.setAttribute("style", "display: none");
+ this.win.document.documentElement.offsetWidth;
+ this._winDimensions = getWindowDimensions(this.win);
+ const { width, height } = this._winDimensions;
+
+ // Updates the <canvas> element's position and size.
+ // It also clear the <canvas>'s drawing context.
+ updateCanvasElement(
+ this.canvas,
+ this._canvasPosition,
+ this.win.devicePixelRatio,
+ {
+ zoomWindow: this.win,
+ }
+ );
+
+ // Update the current matrix used in our canvas' rendering
+ const { currentMatrix, hasNodeTransformations } = getCurrentMatrix(
+ this.container,
+ this.win,
+ {
+ ignoreWritingModeAndTextDirection: true,
+ }
+ );
+ this.currentMatrix = currentMatrix;
+ this.hasNodeTransformations = hasNodeTransformations;
+
+ if (this.prevColor != this.color) {
+ this.clearCache();
+ }
+ this.renderFlexContainer();
+ this.renderFlexLines();
+ this.renderJustifyContent();
+ this.renderFlexItems();
+ this._showFlexbox();
+ this.prevColor = this.color;
+
+ root.setAttribute(
+ "style",
+ `position: absolute; width: ${width}px; height: ${height}px; overflow: hidden`
+ );
+
+ setIgnoreLayoutChanges(false, this.highlighterEnv.document.documentElement);
+ return true;
+ }
+}
+
+/**
+ * Returns an object representation of the Flex data object and its array of FlexLine
+ * and FlexItem objects along with the DOMRects of the flex items.
+ *
+ * @param {DOMNode} container
+ * The flex container.
+ * @return {Object|null} representation of the Flex data object.
+ */
+function getFlexData(container) {
+ const flex = container.getAsFlexContainer();
+
+ if (!flex) {
+ return null;
+ }
+
+ return {
+ lines: flex.getLines().map(line => {
+ return {
+ crossSize: line.crossSize,
+ crossStart: line.crossStart,
+ firstBaselineOffset: line.firstBaselineOffset,
+ growthState: line.growthState,
+ lastBaselineOffset: line.lastBaselineOffset,
+ items: line.getItems().map(item => {
+ return {
+ crossMaxSize: item.crossMaxSize,
+ crossMinSize: item.crossMinSize,
+ mainBaseSize: item.mainBaseSize,
+ mainDeltaSize: item.mainDeltaSize,
+ mainMaxSize: item.mainMaxSize,
+ mainMinSize: item.mainMinSize,
+ node: item.node,
+ rect: getRectFromFlexItemValues(item, container),
+ };
+ }),
+ };
+ }),
+ };
+}
+
+/**
+ * Given a FlexItemValues, return a DOMRect representing the flex item taking
+ * into account its flex container's border and padding.
+ *
+ * @param {FlexItemValues} item
+ * The FlexItemValues for which we need the DOMRect.
+ * @param {DOMNode}
+ * Flex container containing the flex item.
+ * @return {DOMRect} representing the flex item.
+ */
+function getRectFromFlexItemValues(item, container) {
+ const rect = item.frameRect;
+ const domRect = new DOMRect(rect.x, rect.y, rect.width, rect.height);
+ const win = container.ownerGlobal;
+ const style = win.getComputedStyle(container);
+ const borderLeftWidth = parseInt(style.borderLeftWidth, 10) || 0;
+ const borderTopWidth = parseInt(style.borderTopWidth, 10) || 0;
+ const paddingLeft = parseInt(style.paddingLeft, 10) || 0;
+ const paddingTop = parseInt(style.paddingTop, 10) || 0;
+ const scrollX = container.scrollLeft || 0;
+ const scrollY = container.scrollTop || 0;
+
+ domRect.x -= paddingLeft + scrollX;
+ domRect.y -= paddingTop + scrollY;
+
+ if (style.overflow === "visible" || style.overflow === "clip") {
+ domRect.x -= borderLeftWidth;
+ domRect.y -= borderTopWidth;
+ }
+
+ return domRect;
+}
+
+/**
+ * Returns whether or not the flex data has changed.
+ *
+ * @param {Flex} oldFlexData
+ * The old Flex data object.
+ * @param {Flex} newFlexData
+ * The new Flex data object.
+ * @return {Boolean} true if the flex data has changed and false otherwise.
+ */
+// eslint-disable-next-line complexity
+function compareFlexData(oldFlexData, newFlexData) {
+ if (!oldFlexData || !newFlexData) {
+ return true;
+ }
+
+ const oldLines = oldFlexData.lines;
+ const newLines = newFlexData.lines;
+
+ if (oldLines.length !== newLines.length) {
+ return true;
+ }
+
+ for (let i = 0; i < oldLines.length; i++) {
+ const oldLine = oldLines[i];
+ const newLine = newLines[i];
+
+ if (
+ oldLine.crossSize !== newLine.crossSize ||
+ oldLine.crossStart !== newLine.crossStart ||
+ oldLine.firstBaselineOffset !== newLine.firstBaselineOffset ||
+ oldLine.growthState !== newLine.growthState ||
+ oldLine.lastBaselineOffset !== newLine.lastBaselineOffset
+ ) {
+ return true;
+ }
+
+ const oldItems = oldLine.items;
+ const newItems = newLine.items;
+
+ if (oldItems.length !== newItems.length) {
+ return true;
+ }
+
+ for (let j = 0; j < oldItems.length; j++) {
+ const oldItem = oldItems[j];
+ const newItem = newItems[j];
+
+ if (
+ oldItem.crossMaxSize !== newItem.crossMaxSize ||
+ oldItem.crossMinSize !== newItem.crossMinSize ||
+ oldItem.mainBaseSize !== newItem.mainBaseSize ||
+ oldItem.mainDeltaSize !== newItem.mainDeltaSize ||
+ oldItem.mainMaxSize !== newItem.mainMaxSize ||
+ oldItem.mainMinSize !== newItem.mainMinSize
+ ) {
+ return true;
+ }
+
+ const oldItemRect = oldItem.rect;
+ const newItemRect = newItem.rect;
+
+ // We are using DOMRects so we only need to compare x, y, width and
+ // height (left, top, right and bottom are calculated from these values).
+ if (
+ oldItemRect.x !== newItemRect.x ||
+ oldItemRect.y !== newItemRect.y ||
+ oldItemRect.width !== newItemRect.width ||
+ oldItemRect.height !== newItemRect.height
+ ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+exports.FlexboxHighlighter = FlexboxHighlighter;
diff --git a/devtools/server/actors/highlighters/fonts.js b/devtools/server/actors/highlighters/fonts.js
new file mode 100644
index 0000000000..3106e1b1fa
--- /dev/null
+++ b/devtools/server/actors/highlighters/fonts.js
@@ -0,0 +1,122 @@
+/* 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";
+
+const InspectorUtils = require("InspectorUtils");
+loader.lazyRequireGetter(
+ this,
+ "loadSheet",
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "removeSheet",
+ "devtools/shared/layout/utils",
+ true
+);
+
+// How many text runs are we highlighting at a time. There may be many text runs, and we
+// want to prevent performance problems.
+const MAX_TEXT_RANGES = 100;
+
+// This stylesheet is inserted into the page to customize the color of the selected text
+// runs.
+// Note that this color is defined as --highlighter-content-color in the highlighters.css
+// file, and corresponds to the box-model content color. We want to give it an opacity of
+// 0.6 here.
+const STYLESHEET_URI =
+ "data:text/css," +
+ encodeURIComponent(
+ "::selection{background-color:hsl(197,71%,73%,.6)!important;}"
+ );
+
+/**
+ * This highlighter highlights runs of text in the page that have been rendered given a
+ * certain font. The highlighting is done with window selection ranges, so no extra
+ * markup is being inserted into the content page.
+ */
+class FontsHighlighter {
+ constructor(highlighterEnv) {
+ this.env = highlighterEnv;
+ }
+
+ destroy() {
+ this.hide();
+ this.env = this.currentNode = null;
+ }
+
+ get currentNodeDocument() {
+ if (!this.currentNode) {
+ return this.env.document;
+ }
+
+ if (this.currentNode.nodeType === this.currentNode.DOCUMENT_NODE) {
+ return this.currentNode;
+ }
+
+ return this.currentNode.ownerDocument;
+ }
+
+ /**
+ * Show the highlighter for a given node.
+ * @param {DOMNode} node The node in which we want to search for text runs.
+ * @param {Object} options A bunch of options that can be set:
+ * - {String} name The actual font name to look for in the node.
+ * - {String} CSSFamilyName The CSS font-family name given to this font.
+ */
+ show(node, options) {
+ this.currentNode = node;
+ const doc = this.currentNodeDocument;
+
+ // Get all of the fonts used to render content inside the node.
+ const searchRange = doc.createRange();
+ searchRange.selectNodeContents(node);
+
+ const fonts = InspectorUtils.getUsedFontFaces(searchRange, MAX_TEXT_RANGES);
+
+ // Find the ones we want, based on the provided option.
+ const matchingFonts = fonts.filter(
+ f => f.CSSFamilyName === options.CSSFamilyName && f.name === options.name
+ );
+ if (!matchingFonts.length) {
+ return;
+ }
+
+ // Load the stylesheet that will customize the color of the highlighter (using a
+ // ::selection rule).
+ loadSheet(this.env.window, STYLESHEET_URI);
+
+ // Create a multi-selection in the page to highlight the text runs.
+ const selection = doc.defaultView.getSelection();
+ selection.removeAllRanges();
+
+ for (const matchingFont of matchingFonts) {
+ for (const range of matchingFont.ranges) {
+ selection.addRange(range);
+ }
+ }
+ }
+
+ hide() {
+ // No node was highlighted before, don't need to continue any further.
+ if (!this.currentNode) {
+ return;
+ }
+
+ try {
+ removeSheet(this.env.window, STYLESHEET_URI);
+ } catch (e) {
+ // Silently fail here as we might not have inserted the stylesheet at all.
+ }
+
+ // Simply remove all current ranges in the seletion.
+ const doc = this.currentNodeDocument;
+ const selection = doc.defaultView.getSelection();
+ selection.removeAllRanges();
+ }
+}
+
+exports.FontsHighlighter = FontsHighlighter;
diff --git a/devtools/server/actors/highlighters/geometry-editor.js b/devtools/server/actors/highlighters/geometry-editor.js
new file mode 100644
index 0000000000..95eac514ca
--- /dev/null
+++ b/devtools/server/actors/highlighters/geometry-editor.js
@@ -0,0 +1,796 @@
+/* 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";
+
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const {
+ CanvasFrameAnonymousContentHelper,
+ getComputedStyle,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ setIgnoreLayoutChanges,
+ getAdjustedQuads,
+} = require("devtools/shared/layout/utils");
+const { getCSSStyleRules } = require("devtools/shared/inspector/css-logic");
+
+const GEOMETRY_LABEL_SIZE = 6;
+
+// List of all DOM Events subscribed directly to the document from the
+// Geometry Editor highlighter
+const DOM_EVENTS = ["mousemove", "mouseup", "pagehide"];
+
+const _dragging = Symbol("geometry/dragging");
+
+/**
+ * Element geometry properties helper that gives names of position and size
+ * properties.
+ */
+var GeoProp = {
+ SIDES: ["top", "right", "bottom", "left"],
+ SIZES: ["width", "height"],
+
+ allProps: function() {
+ return [...this.SIDES, ...this.SIZES];
+ },
+
+ isSide: function(name) {
+ return this.SIDES.includes(name);
+ },
+
+ isSize: function(name) {
+ return this.SIZES.includes(name);
+ },
+
+ containsSide: function(names) {
+ return names.some(name => this.SIDES.includes(name));
+ },
+
+ containsSize: function(names) {
+ return names.some(name => this.SIZES.includes(name));
+ },
+
+ isHorizontal: function(name) {
+ return name === "left" || name === "right" || name === "width";
+ },
+
+ isInverted: function(name) {
+ return name === "right" || name === "bottom";
+ },
+
+ mainAxisStart: function(name) {
+ return this.isHorizontal(name) ? "left" : "top";
+ },
+
+ crossAxisStart: function(name) {
+ return this.isHorizontal(name) ? "top" : "left";
+ },
+
+ mainAxisSize: function(name) {
+ return this.isHorizontal(name) ? "width" : "height";
+ },
+
+ crossAxisSize: function(name) {
+ return this.isHorizontal(name) ? "height" : "width";
+ },
+
+ axis: function(name) {
+ return this.isHorizontal(name) ? "x" : "y";
+ },
+
+ crossAxis: function(name) {
+ return this.isHorizontal(name) ? "y" : "x";
+ },
+};
+
+/**
+ * Get the provided node's offsetParent dimensions.
+ * Returns an object with the {parent, dimension} properties.
+ * Note that the returned parent will be null if the offsetParent is the
+ * default, non-positioned, body or html node.
+ *
+ * node.offsetParent returns the nearest positioned ancestor but if it is
+ * non-positioned itself, we just return null to let consumers know the node is
+ * actually positioned relative to the viewport.
+ *
+ * @return {Object}
+ */
+function getOffsetParent(node) {
+ const win = node.ownerGlobal;
+
+ let offsetParent = node.offsetParent;
+ if (offsetParent && getComputedStyle(offsetParent).position === "static") {
+ offsetParent = null;
+ }
+
+ let width, height;
+ if (!offsetParent) {
+ height = win.innerHeight;
+ width = win.innerWidth;
+ } else {
+ height = offsetParent.offsetHeight;
+ width = offsetParent.offsetWidth;
+ }
+
+ return {
+ element: offsetParent,
+ dimension: { width, height },
+ };
+}
+
+/**
+ * Get the list of geometry properties that are actually set on the provided
+ * node.
+ *
+ * @param {Node} node The node to analyze.
+ * @return {Map} A map indexed by property name and where the value is an
+ * object having the cssRule property.
+ */
+function getDefinedGeometryProperties(node) {
+ const props = new Map();
+ if (!node) {
+ return props;
+ }
+
+ // Get the list of css rules applying to the current node.
+ const cssRules = getCSSStyleRules(node);
+ for (let i = 0; i < cssRules.length; i++) {
+ const rule = cssRules[i];
+ for (const name of GeoProp.allProps()) {
+ const value = rule.style.getPropertyValue(name);
+ if (value && value !== "auto") {
+ // getCSSStyleRules returns rules ordered from least to most specific
+ // so just override any previous properties we have set.
+ props.set(name, {
+ cssRule: rule,
+ });
+ }
+ }
+ }
+
+ // Go through the inline styles last, only if the node supports inline style
+ // (e.g. pseudo elements don't have a style property)
+ if (node.style) {
+ for (const name of GeoProp.allProps()) {
+ const value = node.style.getPropertyValue(name);
+ if (value && value !== "auto") {
+ props.set(name, {
+ // There's no cssRule to store here, so store the node instead since
+ // node.style exists.
+ cssRule: node,
+ });
+ }
+ }
+ }
+
+ // Post-process the list for invalid properties. This is done after the fact
+ // because of cases like relative positioning with both top and bottom where
+ // only top will actually be used, but both exists in css rules and computed
+ // styles.
+ const { position } = getComputedStyle(node);
+ for (const [name] of props) {
+ // Top/left/bottom/right on static positioned elements have no effect.
+ if (position === "static" && GeoProp.SIDES.includes(name)) {
+ props.delete(name);
+ }
+
+ // Bottom/right on relative positioned elements are only used if top/left
+ // are not defined.
+ const hasRightAndLeft = name === "right" && props.has("left");
+ const hasBottomAndTop = name === "bottom" && props.has("top");
+ if (position === "relative" && (hasRightAndLeft || hasBottomAndTop)) {
+ props.delete(name);
+ }
+ }
+
+ return props;
+}
+exports.getDefinedGeometryProperties = getDefinedGeometryProperties;
+
+/**
+ * The GeometryEditor highlights an elements's top, left, bottom, right, width
+ * and height dimensions, when they are set.
+ *
+ * To determine if an element has a set size and position, the highlighter lists
+ * the CSS rules that apply to the element and checks for the top, left, bottom,
+ * right, width and height properties.
+ * The highlighter won't be shown if the element doesn't have any of these
+ * properties set, but will be shown when at least 1 property is defined.
+ *
+ * The highlighter displays lines and labels for each of the defined properties
+ * in and around the element (relative to the offset parent when one exists).
+ * The highlighter also highlights the element itself and its offset parent if
+ * there is one.
+ *
+ * Note that the class name contains the word Editor because the aim is for the
+ * handles to be draggable in content to make the geometry editable.
+ */
+class GeometryEditorHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+
+ this.ID_CLASS_PREFIX = "geometry-editor-";
+
+ // The list of element geometry properties that can be set.
+ this.definedProperties = new Map();
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.initialize();
+
+ const { pageListenerTarget } = this.highlighterEnv;
+
+ // Register the geometry editor instance to all events we're interested in.
+ DOM_EVENTS.forEach(type => pageListenerTarget.addEventListener(type, this));
+
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ this.highlighterEnv.on("will-navigate", this.onWillNavigate);
+ }
+
+ async initialize() {
+ await this.markup.initialize();
+ // Register the mousedown event for each Geometry Editor's handler.
+ // Those events are automatically removed when the markup is destroyed.
+ const onMouseDown = this.handleEvent.bind(this);
+
+ for (const side of GeoProp.SIDES) {
+ this.getElement("handler-" + side).addEventListener(
+ "mousedown",
+ onMouseDown
+ );
+ }
+ }
+
+ _buildMarkup() {
+ const container = this.markup.createNode({
+ attributes: { class: "highlighter-container" },
+ });
+
+ const root = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: root,
+ attributes: {
+ id: "elements",
+ width: "100%",
+ height: "100%",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Offset parent node highlighter.
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: svg,
+ attributes: {
+ class: "offset-parent",
+ id: "offset-parent",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Current node highlighter (margin box).
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: svg,
+ attributes: {
+ class: "current-node",
+ id: "current-node",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Build the 4 side arrows, handlers and labels.
+ for (const name of GeoProp.SIDES) {
+ this.markup.createSVGNode({
+ nodeType: "line",
+ parent: svg,
+ attributes: {
+ class: "arrow " + name,
+ id: "arrow-" + name,
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "circle",
+ parent: svg,
+ attributes: {
+ class: "handler-" + name,
+ id: "handler-" + name,
+ r: "4",
+ "data-side": name,
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Labels are positioned by using a translated <g>. This group contains
+ // a path and text that are themselves positioned using another translated
+ // <g>. This is so that the label arrow points at the 0,0 coordinates of
+ // parent <g>.
+ const labelG = this.markup.createSVGNode({
+ nodeType: "g",
+ parent: svg,
+ attributes: {
+ id: "label-" + name,
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const subG = this.markup.createSVGNode({
+ nodeType: "g",
+ parent: labelG,
+ attributes: {
+ transform: GeoProp.isHorizontal(name)
+ ? "translate(-30 -30)"
+ : "translate(5 -10)",
+ },
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: subG,
+ attributes: {
+ class: "label-bubble",
+ d: GeoProp.isHorizontal(name)
+ ? "M0 0 L60 0 L60 20 L35 20 L30 25 L25 20 L0 20z"
+ : "M5 0 L65 0 L65 20 L5 20 L5 15 L0 10 L5 5z",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "text",
+ parent: subG,
+ attributes: {
+ class: "label-text",
+ id: "label-text-" + name,
+ x: GeoProp.isHorizontal(name) ? "30" : "35",
+ y: "10",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+ }
+
+ return container;
+ }
+
+ destroy() {
+ // Avoiding exceptions if `destroy` is called multiple times; and / or the
+ // highlighter environment was already destroyed.
+ if (!this.highlighterEnv) {
+ return;
+ }
+
+ const { pageListenerTarget } = this.highlighterEnv;
+
+ if (pageListenerTarget) {
+ DOM_EVENTS.forEach(type =>
+ pageListenerTarget.removeEventListener(type, this)
+ );
+ }
+
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+
+ this.markup.destroy();
+ this.definedProperties.clear();
+ this.definedProperties = null;
+ this.offsetParent = null;
+ }
+
+ handleEvent(event, id) {
+ // No event handling if the highlighter is hidden
+ if (this.getElement("root").hasAttribute("hidden")) {
+ return;
+ }
+
+ const { target, type, pageX, pageY } = event;
+
+ switch (type) {
+ case "pagehide":
+ // If a page hide event is triggered for current window's highlighter, hide the
+ // highlighter.
+ if (target.defaultView === this.win) {
+ this.destroy();
+ }
+
+ break;
+ case "mousedown":
+ // The mousedown event is intended only for the handler
+ if (!id) {
+ return;
+ }
+
+ const handlerSide = this.markup
+ .getElement(id)
+ .getAttribute("data-side");
+
+ if (handlerSide) {
+ const side = handlerSide;
+ const sideProp = this.definedProperties.get(side);
+
+ if (!sideProp) {
+ return;
+ }
+
+ let value = sideProp.cssRule.style.getPropertyValue(side);
+ const computedValue = this.computedStyle.getPropertyValue(side);
+
+ const [unit] = value.match(/[^\d]+$/) || [""];
+
+ value = parseFloat(value);
+
+ const ratio = value / parseFloat(computedValue) || 1;
+ const dir = GeoProp.isInverted(side) ? -1 : 1;
+
+ // Store all the initial values needed for drag & drop
+ this[_dragging] = {
+ side,
+ value,
+ unit,
+ x: pageX,
+ y: pageY,
+ inc: ratio * dir,
+ };
+
+ this.getElement("handler-" + side).classList.add("dragging");
+ }
+
+ this.getElement("root").setAttribute("dragging", "true");
+ break;
+ case "mouseup":
+ // If we're dragging, drop it.
+ if (this[_dragging]) {
+ const { side } = this[_dragging];
+ this.getElement("root").removeAttribute("dragging");
+ this.getElement("handler-" + side).classList.remove("dragging");
+ this[_dragging] = null;
+ }
+ break;
+ case "mousemove":
+ if (!this[_dragging]) {
+ return;
+ }
+
+ const { side, x, y, value, unit, inc } = this[_dragging];
+ const sideProps = this.definedProperties.get(side);
+
+ if (!sideProps) {
+ return;
+ }
+
+ const delta =
+ (GeoProp.isHorizontal(side) ? pageX - x : pageY - y) * inc;
+
+ // The inline style has usually the priority over any other CSS rule
+ // set in stylesheets. However, if a rule has `!important` keyword,
+ // it will override the inline style too. To ensure Geometry Editor
+ // will always update the element, we have to add `!important` as
+ // well.
+ this.currentNode.style.setProperty(
+ side,
+ value + delta + unit,
+ "important"
+ );
+
+ break;
+ }
+ }
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ _show() {
+ this.computedStyle = getComputedStyle(this.currentNode);
+ const pos = this.computedStyle.position;
+ // XXX: sticky positioning is ignored for now. To be implemented next.
+ if (pos === "sticky") {
+ this.hide();
+ return false;
+ }
+
+ const hasUpdated = this._update();
+ if (!hasUpdated) {
+ this.hide();
+ return false;
+ }
+
+ this.getElement("root").removeAttribute("hidden");
+
+ return true;
+ }
+
+ _update() {
+ // At each update, the position or/and size may have changed, so get the
+ // list of defined properties, and re-position the arrows and highlighters.
+ this.definedProperties = getDefinedGeometryProperties(this.currentNode);
+
+ if (!this.definedProperties.size) {
+ console.warn("The element does not have editable geometry properties");
+ return false;
+ }
+
+ setIgnoreLayoutChanges(true);
+
+ // Update the highlighters and arrows.
+ this.updateOffsetParent();
+ this.updateCurrentNode();
+ this.updateArrows();
+
+ // Avoid zooming the arrows when content is zoomed.
+ const node = this.currentNode;
+ this.markup.scaleRootElement(node, this.ID_CLASS_PREFIX + "root");
+
+ setIgnoreLayoutChanges(false, this.highlighterEnv.document.documentElement);
+ return true;
+ }
+
+ /**
+ * Update the offset parent rectangle.
+ * There are 3 different cases covered here:
+ * - the node is absolutely/fixed positioned, and an offsetParent is defined
+ * (i.e. it's not just positioned in the viewport): the offsetParent node
+ * is highlighted (i.e. the rectangle is shown),
+ * - the node is relatively positioned: the rectangle is shown where the node
+ * would originally have been (because that's where the relative positioning
+ * is calculated from),
+ * - the node has no offset parent at all: the offsetParent rectangle is
+ * hidden.
+ */
+ updateOffsetParent() {
+ // Get the offsetParent, if any.
+ this.offsetParent = getOffsetParent(this.currentNode);
+ // And the offsetParent quads.
+ this.parentQuads = getAdjustedQuads(
+ this.win,
+ this.offsetParent.element,
+ "padding"
+ );
+
+ const el = this.getElement("offset-parent");
+
+ const isPositioned =
+ this.computedStyle.position === "absolute" ||
+ this.computedStyle.position === "fixed";
+ const isRelative = this.computedStyle.position === "relative";
+ let isHighlighted = false;
+
+ if (this.offsetParent.element && isPositioned) {
+ const { p1, p2, p3, p4 } = this.parentQuads[0];
+ const points =
+ p1.x +
+ "," +
+ p1.y +
+ " " +
+ p2.x +
+ "," +
+ p2.y +
+ " " +
+ p3.x +
+ "," +
+ p3.y +
+ " " +
+ p4.x +
+ "," +
+ p4.y;
+ el.setAttribute("points", points);
+ isHighlighted = true;
+ } else if (isRelative) {
+ const xDelta = parseFloat(this.computedStyle.left);
+ const yDelta = parseFloat(this.computedStyle.top);
+ if (xDelta || yDelta) {
+ const { p1, p2, p3, p4 } = this.currentQuads.margin[0];
+ const points =
+ p1.x -
+ xDelta +
+ "," +
+ (p1.y - yDelta) +
+ " " +
+ (p2.x - xDelta) +
+ "," +
+ (p2.y - yDelta) +
+ " " +
+ (p3.x - xDelta) +
+ "," +
+ (p3.y - yDelta) +
+ " " +
+ (p4.x - xDelta) +
+ "," +
+ (p4.y - yDelta);
+ el.setAttribute("points", points);
+ isHighlighted = true;
+ }
+ }
+
+ if (isHighlighted) {
+ el.removeAttribute("hidden");
+ } else {
+ el.setAttribute("hidden", "true");
+ }
+ }
+
+ updateCurrentNode() {
+ const box = this.getElement("current-node");
+ const { p1, p2, p3, p4 } = this.currentQuads.margin[0];
+ const attr =
+ p1.x +
+ "," +
+ p1.y +
+ " " +
+ p2.x +
+ "," +
+ p2.y +
+ " " +
+ p3.x +
+ "," +
+ p3.y +
+ " " +
+ p4.x +
+ "," +
+ p4.y;
+ box.setAttribute("points", attr);
+ box.removeAttribute("hidden");
+ }
+
+ _hide() {
+ setIgnoreLayoutChanges(true);
+
+ this.getElement("root").setAttribute("hidden", "true");
+ this.getElement("current-node").setAttribute("hidden", "true");
+ this.getElement("offset-parent").setAttribute("hidden", "true");
+ this.hideArrows();
+
+ this.definedProperties.clear();
+
+ setIgnoreLayoutChanges(false, this.highlighterEnv.document.documentElement);
+ }
+
+ hideArrows() {
+ for (const side of GeoProp.SIDES) {
+ this.getElement("arrow-" + side).setAttribute("hidden", "true");
+ this.getElement("label-" + side).setAttribute("hidden", "true");
+ this.getElement("handler-" + side).setAttribute("hidden", "true");
+ }
+ }
+
+ updateArrows() {
+ this.hideArrows();
+
+ // Position arrows always end at the node's margin box.
+ const marginBox = this.currentQuads.margin[0].bounds;
+
+ // Position the side arrows which need to be visible.
+ // Arrows always start at the offsetParent edge, and end at the middle
+ // position of the node's margin edge.
+ // Note that for relative positioning, the offsetParent is considered to be
+ // the node itself, where it would have been originally.
+ // +------------------+----------------+
+ // | offsetparent | top |
+ // | or viewport | |
+ // | +--------+--------+ |
+ // | | node | |
+ // +---------+ +-------+
+ // | left | | right |
+ // | +--------+--------+ |
+ // | | bottom |
+ // +------------------+----------------+
+ const getSideArrowStartPos = side => {
+ // In case an offsetParent exists and is highlighted.
+ if (this.parentQuads && this.parentQuads.length) {
+ return this.parentQuads[0].bounds[side];
+ }
+
+ // In case of relative positioning.
+ if (this.computedStyle.position === "relative") {
+ if (GeoProp.isInverted(side)) {
+ return marginBox[side] + parseFloat(this.computedStyle[side]);
+ }
+ return marginBox[side] - parseFloat(this.computedStyle[side]);
+ }
+
+ // In case the element is positioned in the viewport.
+ if (GeoProp.isInverted(side)) {
+ return this.offsetParent.dimension[GeoProp.mainAxisSize(side)];
+ }
+ return (
+ -1 *
+ this.currentNode.ownerGlobal[
+ "scroll" + GeoProp.axis(side).toUpperCase()
+ ]
+ );
+ };
+
+ for (const side of GeoProp.SIDES) {
+ const sideProp = this.definedProperties.get(side);
+ if (!sideProp) {
+ continue;
+ }
+
+ const mainAxisStartPos = getSideArrowStartPos(side);
+ const mainAxisEndPos = marginBox[side];
+ const crossAxisPos =
+ marginBox[GeoProp.crossAxisStart(side)] +
+ marginBox[GeoProp.crossAxisSize(side)] / 2;
+
+ this.updateArrow(
+ side,
+ mainAxisStartPos,
+ mainAxisEndPos,
+ crossAxisPos,
+ sideProp.cssRule.style.getPropertyValue(side)
+ );
+ }
+ }
+
+ updateArrow(side, mainStart, mainEnd, crossPos, labelValue) {
+ const arrowEl = this.getElement("arrow-" + side);
+ const labelEl = this.getElement("label-" + side);
+ const labelTextEl = this.getElement("label-text-" + side);
+ const handlerEl = this.getElement("handler-" + side);
+
+ // Position the arrow <line>.
+ arrowEl.setAttribute(GeoProp.axis(side) + "1", mainStart);
+ arrowEl.setAttribute(GeoProp.crossAxis(side) + "1", crossPos);
+ arrowEl.setAttribute(GeoProp.axis(side) + "2", mainEnd);
+ arrowEl.setAttribute(GeoProp.crossAxis(side) + "2", crossPos);
+ arrowEl.removeAttribute("hidden");
+
+ handlerEl.setAttribute("c" + GeoProp.axis(side), mainEnd);
+ handlerEl.setAttribute("c" + GeoProp.crossAxis(side), crossPos);
+ handlerEl.removeAttribute("hidden");
+
+ // Position the label <text> in the middle of the arrow (making sure it's
+ // not hidden below the fold).
+ const capitalize = str => str[0].toUpperCase() + str.substring(1);
+ const winMain = this.win["inner" + capitalize(GeoProp.mainAxisSize(side))];
+ let labelMain = mainStart + (mainEnd - mainStart) / 2;
+ if (
+ (mainStart > 0 && mainStart < winMain) ||
+ (mainEnd > 0 && mainEnd < winMain)
+ ) {
+ if (labelMain < GEOMETRY_LABEL_SIZE) {
+ labelMain = GEOMETRY_LABEL_SIZE;
+ } else if (labelMain > winMain - GEOMETRY_LABEL_SIZE) {
+ labelMain = winMain - GEOMETRY_LABEL_SIZE;
+ }
+ }
+ const labelCross = crossPos;
+ labelEl.setAttribute(
+ "transform",
+ GeoProp.isHorizontal(side)
+ ? "translate(" + labelMain + " " + labelCross + ")"
+ : "translate(" + labelCross + " " + labelMain + ")"
+ );
+ labelEl.removeAttribute("hidden");
+ labelTextEl.setTextContent(labelValue);
+ }
+
+ onWillNavigate({ isTopLevel }) {
+ if (isTopLevel) {
+ this.hide();
+ }
+ }
+}
+
+exports.GeometryEditorHighlighter = GeometryEditorHighlighter;
diff --git a/devtools/server/actors/highlighters/measuring-tool.js b/devtools/server/actors/highlighters/measuring-tool.js
new file mode 100644
index 0000000000..c9de633a83
--- /dev/null
+++ b/devtools/server/actors/highlighters/measuring-tool.js
@@ -0,0 +1,763 @@
+/* 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";
+
+const EventEmitter = require("devtools/shared/event-emitter");
+const {
+ getCurrentZoom,
+ getWindowDimensions,
+ setIgnoreLayoutChanges,
+} = require("devtools/shared/layout/utils");
+const {
+ CanvasFrameAnonymousContentHelper,
+} = require("devtools/server/actors/highlighters/utils/markup");
+
+// Hard coded value about the size of measuring tool label, in order to
+// position and flip it when is needed.
+const LABEL_SIZE_MARGIN = 8;
+const LABEL_SIZE_WIDTH = 80;
+const LABEL_SIZE_HEIGHT = 52;
+const LABEL_POS_MARGIN = 4;
+const LABEL_POS_WIDTH = 40;
+const LABEL_POS_HEIGHT = 34;
+
+// List of all DOM Events subscribed directly to the document from the
+// Measuring Tool highlighter
+const DOM_EVENTS = [
+ "mousedown",
+ "mousemove",
+ "mouseup",
+ "mouseleave",
+ "scroll",
+ "pagehide",
+];
+
+const SIDES = ["top", "right", "bottom", "left"];
+const HANDLERS = [...SIDES, "topleft", "topright", "bottomleft", "bottomright"];
+const HANDLER_SIZE = 6;
+
+/**
+ * The MeasuringToolHighlighter is used to measure distances in a content page.
+ * It allows users to click and drag with their mouse to draw an area whose
+ * dimensions will be displayed in a tooltip next to it.
+ * This allows users to measure distances between elements on a page.
+ */
+function MeasuringToolHighlighter(highlighterEnv) {
+ this.env = highlighterEnv;
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ this.coords = {
+ x: 0,
+ y: 0,
+ };
+
+ const { pageListenerTarget } = highlighterEnv;
+
+ // Register the measuring tool instance to all events we're interested in.
+ DOM_EVENTS.forEach(type => pageListenerTarget.addEventListener(type, this));
+}
+
+MeasuringToolHighlighter.prototype = {
+ ID_CLASS_PREFIX: "measuring-tool-",
+
+ _buildMarkup() {
+ const prefix = this.ID_CLASS_PREFIX;
+
+ const container = this.markup.createNode({
+ attributes: { class: "highlighter-container" },
+ });
+
+ const root = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ hidden: "true",
+ },
+ prefix,
+ });
+
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: root,
+ attributes: {
+ id: "elements",
+ class: "elements",
+ width: "100%",
+ height: "100%",
+ },
+ prefix,
+ });
+
+ for (const side of SIDES) {
+ this.markup.createSVGNode({
+ nodeType: "line",
+ parent: svg,
+ attributes: {
+ class: `guide-${side}`,
+ id: `guide-${side}`,
+ hidden: "true",
+ },
+ prefix,
+ });
+ }
+
+ this.markup.createNode({
+ nodeType: "label",
+ attributes: {
+ id: "label-size",
+ class: "label-size",
+ hidden: "true",
+ },
+ parent: root,
+ prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "label",
+ attributes: {
+ id: "label-position",
+ class: "label-position",
+ hidden: "true",
+ },
+ parent: root,
+ prefix,
+ });
+
+ // Creating a <g> element in order to group all the paths below, that
+ // together represent the measuring tool; so that would be easier move them
+ // around
+ const g = this.markup.createSVGNode({
+ nodeType: "g",
+ attributes: {
+ id: "tool",
+ },
+ parent: svg,
+ prefix,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ attributes: {
+ id: "box-path",
+ class: "box-path",
+ },
+ parent: g,
+ prefix,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ attributes: {
+ id: "diagonal-path",
+ class: "diagonal-path",
+ },
+ parent: g,
+ prefix,
+ });
+
+ for (const handler of HANDLERS) {
+ this.markup.createSVGNode({
+ nodeType: "circle",
+ parent: g,
+ attributes: {
+ class: `handler-${handler}`,
+ id: `handler-${handler}`,
+ r: HANDLER_SIZE,
+ hidden: "true",
+ },
+ prefix,
+ });
+ }
+
+ return container;
+ },
+
+ _update() {
+ const { window } = this.env;
+
+ setIgnoreLayoutChanges(true);
+
+ const zoom = getCurrentZoom(window);
+
+ const { width, height } = getWindowDimensions(window);
+
+ const { coords } = this;
+
+ const isZoomChanged = zoom !== coords.zoom;
+
+ if (isZoomChanged) {
+ coords.zoom = zoom;
+ this.updateLabel();
+ }
+
+ const isDocumentSizeChanged =
+ width !== coords.documentWidth || height !== coords.documentHeight;
+
+ if (isDocumentSizeChanged) {
+ coords.documentWidth = width;
+ coords.documentHeight = height;
+ }
+
+ // If either the document's size or the zoom is changed since the last
+ // repaint, we update the tool's size as well.
+ if (isZoomChanged || isDocumentSizeChanged) {
+ this.updateViewport();
+ }
+
+ setIgnoreLayoutChanges(false, window.document.documentElement);
+
+ this._rafID = window.requestAnimationFrame(() => this._update());
+ },
+
+ _cancelUpdate() {
+ if (this._rafID) {
+ this.env.window.cancelAnimationFrame(this._rafID);
+ this._rafID = 0;
+ }
+ },
+
+ destroy() {
+ this.hide();
+
+ this._cancelUpdate();
+
+ const { pageListenerTarget } = this.env;
+
+ if (pageListenerTarget) {
+ DOM_EVENTS.forEach(type =>
+ pageListenerTarget.removeEventListener(type, this)
+ );
+ }
+
+ this.markup.destroy();
+
+ EventEmitter.emit(this, "destroy");
+ },
+
+ show() {
+ setIgnoreLayoutChanges(true);
+
+ this.getElement("root").removeAttribute("hidden");
+
+ this._update();
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ },
+
+ hide() {
+ setIgnoreLayoutChanges(true);
+
+ this.hideLabel("size");
+ this.hideLabel("position");
+
+ this.getElement("root").setAttribute("hidden", "true");
+
+ this._cancelUpdate();
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ },
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ },
+
+ setSize(w, h) {
+ this.setCoords(undefined, undefined, w, h);
+ },
+
+ setCoords(x, y, w, h) {
+ const { coords } = this;
+
+ if (typeof x !== "undefined") {
+ coords.x = x;
+ }
+
+ if (typeof y !== "undefined") {
+ coords.y = y;
+ }
+
+ if (typeof w !== "undefined") {
+ coords.w = w;
+ }
+
+ if (typeof h !== "undefined") {
+ coords.h = h;
+ }
+
+ setIgnoreLayoutChanges(true);
+
+ if (this._dragging) {
+ this.updatePaths();
+ this.updateHandlers();
+ }
+
+ this.updateLabel();
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ },
+
+ updatePaths() {
+ const { x, y, w, h } = this.coords;
+ const dir = `M0 0 L${w} 0 L${w} ${h} L0 ${h}z`;
+
+ // Adding correction to the line path, otherwise some pixels are drawn
+ // outside the main rectangle area.
+ const x1 = w > 0 ? 0.5 : 0;
+ const y1 = w < 0 && h < 0 ? -0.5 : 0;
+ const w1 = w + (h < 0 && w < 0 ? 0.5 : 0);
+ const h1 = h + (h > 0 && w > 0 ? -0.5 : 0);
+
+ const linedir = `M${x1} ${y1} L${w1} ${h1}`;
+
+ this.getElement("box-path").setAttribute("d", dir);
+ this.getElement("diagonal-path").setAttribute("d", linedir);
+ this.getElement("tool").setAttribute("transform", `translate(${x},${y})`);
+ },
+
+ updateLabel(type) {
+ type = type || (this._dragging ? "size" : "position");
+
+ const isSizeLabel = type === "size";
+
+ const label = this.getElement(`label-${type}`);
+
+ let origin = "top left";
+
+ const { innerWidth, innerHeight, scrollX, scrollY } = this.env.window;
+ let { x, y, w, h, zoom } = this.coords;
+ const scale = 1 / zoom;
+
+ w = w || 0;
+ h = h || 0;
+ x = x || 0;
+ y = y || 0;
+ if (type === "size") {
+ x += w;
+ y += h;
+ }
+
+ let labelMargin, labelHeight, labelWidth;
+
+ if (isSizeLabel) {
+ labelMargin = LABEL_SIZE_MARGIN;
+ labelWidth = LABEL_SIZE_WIDTH;
+ labelHeight = LABEL_SIZE_HEIGHT;
+
+ const d = Math.hypot(w, h).toFixed(2);
+
+ label.setTextContent(`W: ${Math.abs(w)} px
+ H: ${Math.abs(h)} px
+ ↘: ${d}px`);
+ } else {
+ labelMargin = LABEL_POS_MARGIN;
+ labelWidth = LABEL_POS_WIDTH;
+ labelHeight = LABEL_POS_HEIGHT;
+
+ label.setTextContent(`${x}
+ ${y}`);
+ }
+
+ // Size used to position properly the label
+ const labelBoxWidth = (labelWidth + labelMargin) * scale;
+ const labelBoxHeight = (labelHeight + labelMargin) * scale;
+
+ const isGoingLeft = w < scrollX;
+ const isSizeGoingLeft = isSizeLabel && isGoingLeft;
+ const isExceedingLeftMargin = x - labelBoxWidth < scrollX;
+ const isExceedingRightMargin = x + labelBoxWidth > innerWidth + scrollX;
+ const isExceedingTopMargin = y - labelBoxHeight < scrollY;
+ const isExceedingBottomMargin = y + labelBoxHeight > innerHeight + scrollY;
+
+ if ((isSizeGoingLeft && !isExceedingLeftMargin) || isExceedingRightMargin) {
+ x -= labelBoxWidth;
+ origin = "top right";
+ } else {
+ x += labelMargin * scale;
+ }
+
+ if (isSizeLabel) {
+ y += isExceedingTopMargin ? labelMargin * scale : -labelBoxHeight;
+ } else {
+ y += isExceedingBottomMargin ? -labelBoxHeight : labelMargin * scale;
+ }
+
+ label.setAttribute(
+ "style",
+ `
+ width: ${labelWidth}px;
+ height: ${labelHeight}px;
+ transform-origin: ${origin};
+ transform: translate(${x}px,${y}px) scale(${scale})
+ `
+ );
+
+ if (!isSizeLabel) {
+ const labelSize = this.getElement("label-size");
+ const style = labelSize.getAttribute("style");
+
+ if (style) {
+ labelSize.setAttribute(
+ "style",
+ style.replace(/scale[^)]+\)/, `scale(${scale})`)
+ );
+ }
+ }
+ },
+
+ updateViewport() {
+ const { devicePixelRatio } = this.env.window;
+ const { documentWidth, documentHeight, zoom } = this.coords;
+
+ // Because `devicePixelRatio` is affected by zoom (see bug 809788),
+ // in order to get the "real" device pixel ratio, we need divide by `zoom`
+ const pixelRatio = devicePixelRatio / zoom;
+
+ // The "real" device pixel ratio is used to calculate the max stroke
+ // width we can actually assign: on retina, for instance, it would be 0.5,
+ // where on non high dpi monitor would be 1.
+ const minWidth = 1 / pixelRatio;
+ const strokeWidth = minWidth / zoom;
+
+ this.getElement("root").setAttribute(
+ "style",
+ `stroke-width:${strokeWidth};
+ width:${documentWidth}px;
+ height:${documentHeight}px;`
+ );
+ },
+
+ updateGuides() {
+ const { x, y, w, h } = this.coords;
+
+ let guide = this.getElement("guide-top");
+
+ guide.setAttribute("x1", "0");
+ guide.setAttribute("y1", y);
+ guide.setAttribute("x2", "100%");
+ guide.setAttribute("y2", y);
+
+ guide = this.getElement("guide-right");
+
+ guide.setAttribute("x1", x + w);
+ guide.setAttribute("y1", 0);
+ guide.setAttribute("x2", x + w);
+ guide.setAttribute("y2", "100%");
+
+ guide = this.getElement("guide-bottom");
+
+ guide.setAttribute("x1", "0");
+ guide.setAttribute("y1", y + h);
+ guide.setAttribute("x2", "100%");
+ guide.setAttribute("y2", y + h);
+
+ guide = this.getElement("guide-left");
+
+ guide.setAttribute("x1", x);
+ guide.setAttribute("y1", 0);
+ guide.setAttribute("x2", x);
+ guide.setAttribute("y2", "100%");
+ },
+
+ setHandlerPosition(handler, x, y) {
+ const handlerElement = this.getElement(`handler-${handler}`);
+ handlerElement.setAttribute("cx", x);
+ handlerElement.setAttribute("cy", y);
+ },
+
+ updateHandlers() {
+ const { w, h } = this.coords;
+
+ this.setHandlerPosition("top", w / 2, 0);
+ this.setHandlerPosition("topright", w, 0);
+ this.setHandlerPosition("right", w, h / 2);
+ this.setHandlerPosition("bottomright", w, h);
+ this.setHandlerPosition("bottom", w / 2, h);
+ this.setHandlerPosition("bottomleft", 0, h);
+ this.setHandlerPosition("left", 0, h / 2);
+ this.setHandlerPosition("topleft", 0, 0);
+ },
+
+ showLabel(type) {
+ setIgnoreLayoutChanges(true);
+
+ this.getElement(`label-${type}`).removeAttribute("hidden");
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ },
+
+ hideLabel(type) {
+ setIgnoreLayoutChanges(true);
+
+ this.getElement(`label-${type}`).setAttribute("hidden", "true");
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ },
+
+ showGuides() {
+ const prefix = this.ID_CLASS_PREFIX + "guide-";
+
+ for (const side of SIDES) {
+ this.markup.removeAttributeForElement(`${prefix + side}`, "hidden");
+ }
+ },
+
+ hideGuides() {
+ const prefix = this.ID_CLASS_PREFIX + "guide-";
+
+ for (const side of SIDES) {
+ this.markup.setAttributeForElement(`${prefix + side}`, "hidden", "true");
+ }
+ },
+
+ showHandler(id) {
+ const prefix = this.ID_CLASS_PREFIX + "handler-";
+ this.markup.removeAttributeForElement(prefix + id, "hidden");
+ },
+
+ showHandlers() {
+ const prefix = this.ID_CLASS_PREFIX + "handler-";
+
+ for (const handler of HANDLERS) {
+ this.markup.removeAttributeForElement(prefix + handler, "hidden");
+ }
+ },
+
+ hideAll() {
+ this.hideLabel("position");
+ this.hideLabel("size");
+ this.hideGuides();
+ this.hideHandlers();
+ },
+
+ showGuidesAndHandlers() {
+ // Shows the guides and handlers only if an actual area is selected
+ if (this.coords.w !== 0 && this.coords.h !== 0) {
+ this.updateGuides();
+ this.showGuides();
+ this.updateHandlers();
+ this.showHandlers();
+ }
+ },
+
+ hideHandlers() {
+ const prefix = this.ID_CLASS_PREFIX + "handler-";
+
+ for (const handler of HANDLERS) {
+ this.markup.setAttributeForElement(prefix + handler, "hidden", "true");
+ }
+ },
+
+ handleEvent(event) {
+ const { target, type } = event;
+
+ switch (type) {
+ case "mousedown":
+ if (event.button || this._dragging) {
+ return;
+ }
+
+ const isHandler = event.originalTarget.id.includes("handler");
+ if (isHandler) {
+ this.handleResizingMouseDownEvent(event);
+ } else {
+ this.handleMouseDownEvent(event);
+ }
+ break;
+ case "mousemove":
+ if (this._dragging && this._dragging.handler) {
+ this.handleResizingMouseMoveEvent(event);
+ } else {
+ this.handleMouseMoveEvent(event);
+ }
+ break;
+ case "mouseup":
+ if (this._dragging) {
+ if (this._dragging.handler) {
+ this.handleResizingMouseUpEvent();
+ } else {
+ this.handleMouseUpEvent();
+ }
+ }
+ break;
+ case "mouseleave": {
+ if (!this._dragging) {
+ this.hideLabel("position");
+ }
+ break;
+ }
+ case "scroll": {
+ this.hideLabel("position");
+ break;
+ }
+ case "pagehide": {
+ // If a page hide event is triggered for current window's highlighter, hide the
+ // highlighter.
+ if (target.defaultView === this.env.window) {
+ this.destroy();
+ }
+ break;
+ }
+ }
+ },
+
+ handleMouseDownEvent(event) {
+ const { pageX, pageY } = event;
+ const { window } = this.env;
+ const elementId = `${this.ID_CLASS_PREFIX}tool`;
+
+ setIgnoreLayoutChanges(true);
+
+ this.markup.getElement(elementId).classList.add("dragging");
+
+ this.hideAll();
+
+ setIgnoreLayoutChanges(false, window.document.documentElement);
+
+ // Store all the initial values needed for drag & drop
+ this._dragging = {
+ handler: null,
+ x: pageX,
+ y: pageY,
+ };
+
+ this.setCoords(pageX, pageY, 0, 0);
+ },
+
+ handleMouseMoveEvent(event) {
+ const { pageX, pageY } = event;
+ const { coords } = this;
+ let { x, y, w, h } = coords;
+ let labelType;
+
+ if (this._dragging) {
+ w = pageX - coords.x;
+ h = pageY - coords.y;
+
+ this.setCoords(x, y, w, h);
+
+ labelType = "size";
+ } else {
+ labelType = "position";
+
+ this.setCoords(pageX, pageY);
+ }
+
+ this.showLabel(labelType);
+ },
+
+ handleMouseUpEvent() {
+ setIgnoreLayoutChanges(true);
+
+ this.getElement("tool").classList.remove("dragging");
+
+ this.showGuidesAndHandlers();
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ this._dragging = null;
+ },
+
+ handleResizingMouseDownEvent(event) {
+ const { originalTarget, pageX, pageY } = event;
+ const { window } = this.env;
+ const prefix = this.ID_CLASS_PREFIX + "handler-";
+ const handler = originalTarget.id.replace(prefix, "");
+
+ setIgnoreLayoutChanges(true);
+
+ this.markup.getElement(originalTarget.id).classList.add("dragging");
+
+ this.hideAll();
+ this.showHandler(handler);
+
+ // Set coordinates to the current measurement area's position
+ const [, x, y] = this.getElement("tool")
+ .getAttribute("transform")
+ .match(/(\d+),(\d+)/);
+ this.setCoords(Number(x), Number(y));
+
+ setIgnoreLayoutChanges(false, window.document.documentElement);
+
+ // Store all the initial values needed for drag & drop
+ this._dragging = {
+ handler,
+ x: pageX,
+ y: pageY,
+ };
+ },
+
+ handleResizingMouseMoveEvent(event) {
+ const { pageX, pageY } = event;
+ const { coords } = this;
+ let { x, y, w, h } = coords;
+
+ const { handler } = this._dragging;
+
+ switch (handler) {
+ case "top":
+ y = pageY;
+ h = coords.y + coords.h - pageY;
+ break;
+ case "topright":
+ y = pageY;
+ w = pageX - coords.x;
+ h = coords.y + coords.h - pageY;
+ break;
+ case "right":
+ w = pageX - coords.x;
+ break;
+ case "bottomright":
+ w = pageX - coords.x;
+ h = pageY - coords.y;
+ break;
+ case "bottom":
+ h = pageY - coords.y;
+ break;
+ case "bottomleft":
+ x = pageX;
+ w = coords.x + coords.w - pageX;
+ h = pageY - coords.y;
+ break;
+ case "left":
+ x = pageX;
+ w = coords.x + coords.w - pageX;
+ break;
+ case "topleft":
+ x = pageX;
+ y = pageY;
+ w = coords.x + coords.w - pageX;
+ h = coords.y + coords.h - pageY;
+ break;
+ }
+
+ this.setCoords(x, y, w, h);
+
+ // Changes the resizing cursors in case the measuring box is mirrored
+ const isMirrored =
+ (coords.w < 0 || coords.h < 0) && !(coords.w < 0 && coords.h < 0);
+ this.getElement("tool").classList.toggle("mirrored", isMirrored);
+
+ this.showLabel("size");
+ },
+
+ handleResizingMouseUpEvent() {
+ const { handler } = this._dragging;
+
+ setIgnoreLayoutChanges(true);
+
+ this.getElement(`handler-${handler}`).classList.remove("dragging");
+ this.showHandlers();
+
+ this.showGuidesAndHandlers();
+
+ setIgnoreLayoutChanges(false, this.env.window.document.documentElement);
+ this._dragging = null;
+ },
+};
+exports.MeasuringToolHighlighter = MeasuringToolHighlighter;
diff --git a/devtools/server/actors/highlighters/moz.build b/devtools/server/actors/highlighters/moz.build
new file mode 100644
index 0000000000..5423477f73
--- /dev/null
+++ b/devtools/server/actors/highlighters/moz.build
@@ -0,0 +1,28 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "utils",
+]
+
+DevToolsModules(
+ "accessible.js",
+ "auto-refresh.js",
+ "box-model.js",
+ "css-grid.js",
+ "css-transform.js",
+ "eye-dropper.js",
+ "flexbox.js",
+ "fonts.js",
+ "geometry-editor.js",
+ "measuring-tool.js",
+ "node-tabbing-order.js",
+ "paused-debugger.js",
+ "rulers.js",
+ "selector.js",
+ "shapes.js",
+ "tabbing-order.js",
+)
diff --git a/devtools/server/actors/highlighters/node-tabbing-order.js b/devtools/server/actors/highlighters/node-tabbing-order.js
new file mode 100644
index 0000000000..1e0e145ef1
--- /dev/null
+++ b/devtools/server/actors/highlighters/node-tabbing-order.js
@@ -0,0 +1,399 @@
+/* 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";
+
+loader.lazyRequireGetter(
+ this,
+ ["setIgnoreLayoutChanges", "getCurrentZoom"],
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "AutoRefreshHighlighter",
+ "devtools/server/actors/highlighters/auto-refresh",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["CanvasFrameAnonymousContentHelper"],
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+
+/**
+ * The NodeTabbingOrderHighlighter draws an outline around a node (based on its
+ * border bounds).
+ *
+ * Usage example:
+ *
+ * const h = new NodeTabbingOrderHighlighter(env);
+ * await h.isReady();
+ * h.show(node, options);
+ * h.hide();
+ * h.destroy();
+ *
+ * @param {Number} options.index
+ * Tabbing index value to be displayed in the highlighter info bar.
+ */
+class NodeTabbingOrderHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+
+ this._doNotStartRefreshLoop = true;
+ this.ID_CLASS_PREFIX = "tabbing-order-";
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+ }
+
+ _buildMarkup() {
+ const root = this.markup.createNode({
+ attributes: {
+ id: "root",
+ class: "root highlighter-container tabbing-order",
+ "aria-hidden": "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const container = this.markup.createNode({
+ parent: root,
+ attributes: {
+ id: "container",
+ width: "100%",
+ height: "100%",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Building the SVG element
+ this.markup.createNode({
+ parent: container,
+ attributes: {
+ class: "bounds",
+ id: "bounds",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Building the nodeinfo bar markup
+
+ const infobarContainer = this.markup.createNode({
+ parent: root,
+ attributes: {
+ class: "infobar-container",
+ id: "infobar-container",
+ position: "top",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const infobar = this.markup.createNode({
+ parent: infobarContainer,
+ attributes: {
+ class: "infobar",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createNode({
+ parent: infobar,
+ attributes: {
+ class: "infobar-text",
+ id: "infobar-text",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ return root;
+ }
+
+ /**
+ * Destroy the nodes. Remove listeners.
+ */
+ destroy() {
+ this.markup.destroy();
+
+ AutoRefreshHighlighter.prototype.destroy.call(this);
+ }
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ /**
+ * Update focused styling for a node tabbing index highlight.
+ *
+ * @param {Boolean} focused
+ * Indicates if the highlighted node needs to be focused.
+ */
+ updateFocus(focused) {
+ const root = this.getElement("root");
+ root.classList.toggle("focused", focused);
+ }
+
+ /**
+ * Show the highlighter on a given node
+ */
+ _show() {
+ return this._update();
+ }
+
+ /**
+ * Update the highlighter on the current highlighted node (the one that was
+ * passed as an argument to show(node)).
+ * Should be called whenever node size or attributes change
+ */
+ _update() {
+ let shown = false;
+ setIgnoreLayoutChanges(true);
+
+ if (this._updateTabbingOrder()) {
+ this._showInfobar();
+ this._showTabbingOrder();
+ shown = true;
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ } else {
+ // Nothing to highlight (0px rectangle like a <script> tag for instance)
+ this._hide();
+ }
+
+ return shown;
+ }
+
+ /**
+ * Hide the highlighter, the outline and the infobar.
+ */
+ _hide() {
+ setIgnoreLayoutChanges(true);
+
+ this._hideTabbingOrder();
+ this._hideInfobar();
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ /**
+ * Hide the infobar
+ */
+ _hideInfobar() {
+ this.getElement("infobar-container").setAttribute("hidden", "true");
+ }
+
+ /**
+ * Show the infobar
+ */
+ _showInfobar() {
+ if (!this.currentNode) {
+ return;
+ }
+
+ this.getElement("infobar-container").removeAttribute("hidden");
+ this.getElement("infobar-text").setTextContent(this.options.index);
+ const bounds = this._getBounds();
+ const container = this.getElement("infobar-container");
+
+ moveInfobar(container, bounds, this.win);
+ }
+
+ /**
+ * Hide the tabbing order highlighter
+ */
+ _hideTabbingOrder() {
+ this.getElement("container").setAttribute("hidden", "true");
+ }
+
+ /**
+ * Show the tabbing order highlighter
+ */
+ _showTabbingOrder() {
+ this.getElement("container").removeAttribute("hidden");
+ }
+
+ /**
+ * Calculate border bounds based on the quads returned by getAdjustedQuads.
+ * @return {Object} A bounds object {bottom,height,left,right,top,width,x,y}
+ */
+ _getBorderBounds() {
+ const quads = this.currentQuads.border;
+ if (!quads || !quads.length) {
+ return null;
+ }
+
+ const bounds = {
+ bottom: -Infinity,
+ height: 0,
+ left: Infinity,
+ right: -Infinity,
+ top: Infinity,
+ width: 0,
+ x: 0,
+ y: 0,
+ };
+
+ for (const q of quads) {
+ bounds.bottom = Math.max(bounds.bottom, q.bounds.bottom);
+ bounds.top = Math.min(bounds.top, q.bounds.top);
+ bounds.left = Math.min(bounds.left, q.bounds.left);
+ bounds.right = Math.max(bounds.right, q.bounds.right);
+ }
+ bounds.x = bounds.left;
+ bounds.y = bounds.top;
+ bounds.width = bounds.right - bounds.left;
+ bounds.height = bounds.bottom - bounds.top;
+
+ return bounds;
+ }
+
+ /**
+ * Update the tabbing order index as per the current node.
+ *
+ * @return {boolean}
+ * True if the current node has a tabbing order index to be
+ * highlighted
+ */
+ _updateTabbingOrder() {
+ if (!this._nodeNeedsHighlighting()) {
+ this._hideTabbingOrder();
+ return false;
+ }
+
+ const boundsEl = this.getElement("bounds");
+ const { left, top, width, height } = this._getBounds();
+ boundsEl.setAttribute(
+ "style",
+ `top: ${top}px; left: ${left}px; width: ${width}px; height: ${height}px;`
+ );
+
+ // Un-zoom the root wrapper if the page was zoomed.
+ const rootId = this.ID_CLASS_PREFIX + "container";
+ this.markup.scaleRootElement(this.currentNode, rootId);
+
+ return true;
+ }
+
+ /**
+ * Can the current node be highlighted? Does it have quads.
+ * @return {Boolean}
+ */
+ _nodeNeedsHighlighting() {
+ return (
+ this.currentQuads.margin.length ||
+ this.currentQuads.border.length ||
+ this.currentQuads.padding.length ||
+ this.currentQuads.content.length
+ );
+ }
+
+ _getBounds() {
+ const borderBounds = this._getBorderBounds();
+ let bounds = {
+ bottom: 0,
+ height: 0,
+ left: 0,
+ right: 0,
+ top: 0,
+ width: 0,
+ x: 0,
+ y: 0,
+ };
+
+ if (!borderBounds) {
+ // Invisible element such as a script tag.
+ return bounds;
+ }
+
+ const { bottom, height, left, right, top, width, x, y } = borderBounds;
+ if (width > 0 || height > 0) {
+ bounds = { bottom, height, left, right, top, width, x, y };
+ }
+
+ return bounds;
+ }
+}
+
+/**
+ * Move the infobar to the right place in the highlighter. The infobar is used
+ * to display element's tabbing order index.
+ *
+ * @param {DOMNode} container
+ * The container element which will be used to position the infobar.
+ * @param {Object} bounds
+ * The content bounds of the container element.
+ * @param {Window} win
+ * The window object.
+ */
+function moveInfobar(container, bounds, win) {
+ const zoom = getCurrentZoom(win);
+ const { computedStyle } = container;
+ const margin = 2;
+ const arrowSize =
+ parseFloat(
+ computedStyle.getPropertyValue("--highlighter-bubble-arrow-size")
+ ) - 2;
+ const containerHeight = parseFloat(computedStyle.getPropertyValue("height"));
+ const containerWidth = parseFloat(computedStyle.getPropertyValue("width"));
+
+ const topBoundary = margin;
+ const bottomBoundary =
+ win.document.scrollingElement.scrollHeight - containerHeight - margin - 1;
+ const leftBoundary = containerWidth / 2 + margin;
+
+ let top = bounds.y - containerHeight - arrowSize;
+ let left = bounds.x + bounds.width / 2;
+ const bottom = bounds.bottom + arrowSize;
+ let positionAttribute = "top";
+
+ const canBePlacedOnTop = top >= topBoundary;
+ const canBePlacedOnBottom = bottomBoundary - bottom > 0;
+
+ if (!canBePlacedOnTop && canBePlacedOnBottom) {
+ top = bottom;
+ positionAttribute = "bottom";
+ }
+
+ let hideArrow = false;
+ if (top < topBoundary) {
+ hideArrow = true;
+ top = topBoundary;
+ } else if (top > bottomBoundary) {
+ hideArrow = true;
+ top = bottomBoundary;
+ }
+
+ if (left < leftBoundary) {
+ hideArrow = true;
+ left = leftBoundary;
+ }
+
+ if (hideArrow) {
+ container.setAttribute("hide-arrow", "true");
+ } else {
+ container.removeAttribute("hide-arrow");
+ }
+
+ container.setAttribute(
+ "style",
+ `
+ position: absolute;
+ transform-origin: 0 0;
+ transform: scale(${1 / zoom}) translate(calc(${left}px - 50%), ${top}px)`
+ );
+
+ container.setAttribute("position", positionAttribute);
+}
+
+exports.NodeTabbingOrderHighlighter = NodeTabbingOrderHighlighter;
diff --git a/devtools/server/actors/highlighters/paused-debugger.js b/devtools/server/actors/highlighters/paused-debugger.js
new file mode 100644
index 0000000000..b281d6cb88
--- /dev/null
+++ b/devtools/server/actors/highlighters/paused-debugger.js
@@ -0,0 +1,255 @@
+/* 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";
+
+const {
+ CanvasFrameAnonymousContentHelper,
+} = require("devtools/server/actors/highlighters/utils/markup");
+
+loader.lazyGetter(this, "L10N", () => {
+ const { LocalizationHelper } = require("devtools/shared/l10n");
+ const STRINGS_URI = "devtools/client/locales/debugger.properties";
+ return new LocalizationHelper(STRINGS_URI);
+});
+
+/**
+ * The PausedDebuggerOverlay is a class that displays a semi-transparent mask on top of
+ * the whole page and a toolbar at the top of the page.
+ * This is used to signal to users that script execution is current paused.
+ * The toolbar is used to display the reason for the pause in script execution as well as
+ * buttons to resume or step through the program.
+ */
+function PausedDebuggerOverlay(highlighterEnv, options = {}) {
+ this.env = highlighterEnv;
+ this.resume = options.resume;
+ this.stepOver = options.stepOver;
+
+ this.lastTarget = null;
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+}
+
+PausedDebuggerOverlay.prototype = {
+ ID_CLASS_PREFIX: "paused-dbg-",
+
+ _buildMarkup() {
+ const prefix = this.ID_CLASS_PREFIX;
+
+ const container = this.markup.createNode({
+ attributes: { class: "highlighter-container" },
+ });
+
+ // Wrapper element.
+ const wrapper = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ hidden: "true",
+ overlay: "true",
+ },
+ prefix,
+ });
+
+ const toolbar = this.markup.createNode({
+ parent: wrapper,
+ attributes: {
+ id: "toolbar",
+ class: "toolbar",
+ },
+ prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: toolbar,
+ attributes: {
+ id: "reason",
+ class: "reason",
+ },
+ prefix,
+ });
+
+ this.markup.createNode({
+ parent: toolbar,
+ attributes: {
+ id: "divider",
+ class: "divider",
+ },
+ prefix,
+ });
+
+ const stepWrapper = this.markup.createNode({
+ parent: toolbar,
+ attributes: {
+ id: "step-button-wrapper",
+ class: "step-button-wrapper",
+ },
+ prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "button",
+ parent: stepWrapper,
+ attributes: {
+ id: "step-button",
+ class: "step-button",
+ },
+ prefix,
+ });
+
+ const resumeWrapper = this.markup.createNode({
+ parent: toolbar,
+ attributes: {
+ id: "resume-button-wrapper",
+ class: "resume-button-wrapper",
+ },
+ prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "button",
+ parent: resumeWrapper,
+ attributes: {
+ id: "resume-button",
+ class: "resume-button",
+ },
+ prefix,
+ });
+
+ return container;
+ },
+
+ destroy() {
+ this.hide();
+ this.markup.destroy();
+ this.env = null;
+ this.lastTarget = null;
+ },
+
+ onClick(target) {
+ const { id } = target;
+ if (!id) {
+ return;
+ }
+
+ if (id.includes("paused-dbg-step-button")) {
+ this.stepOver();
+ } else if (id.includes("paused-dbg-resume-button")) {
+ this.resume();
+ }
+ },
+
+ onMouseMove(target) {
+ // Not an element we care about
+ if (!target || !target.id) {
+ return;
+ }
+
+ // If the user didn't change targets, do nothing
+ if (this.lastTarget && this.lastTarget.id === target.id) {
+ return;
+ }
+
+ if (
+ target.id.includes("step-button") ||
+ target.id.includes("resume-button")
+ ) {
+ // The hover should be applied to the wrapper (icon's parent node)
+ const newTarget = target.parentNode.id.includes("wrapper")
+ ? target.parentNode
+ : target;
+
+ // Remove the hover class if the user has changed buttons
+ if (this.lastTarget && this.lastTarget != newTarget) {
+ this.lastTarget.classList.remove("hover");
+ }
+ newTarget.classList.add("hover");
+ this.lastTarget = newTarget;
+ } else if (this.lastTarget) {
+ // Remove the hover class if the user isn't on a button
+ this.lastTarget.classList.remove("hover");
+ }
+ },
+
+ handleEvent(e) {
+ switch (e.type) {
+ case "mousedown":
+ this.onClick(e.target);
+ break;
+ case "DOMMouseScroll":
+ // Prevent scrolling. That's because we only took a screenshot of the viewport, so
+ // scrolling out of the viewport wouldn't draw the expected things. In the future
+ // we can take the screenshot again on scroll, but for now it doesn't seem
+ // important.
+ e.preventDefault();
+ break;
+
+ case "mousemove":
+ this.onMouseMove(e.target);
+ break;
+ }
+ },
+
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ },
+
+ show(reason) {
+ if (this.env.isXUL || !reason) {
+ return false;
+ }
+
+ try {
+ reason = L10N.getStr(`whyPaused.${reason}`);
+ } catch (e) {
+ // This is a temporary workaround (See Bug 1591025).
+ // This actors relies on a client side properties file. This file will not
+ // be available when debugging Firefox for Android / Gecko View.
+ // The highlighter also shows buttons that use client only images and are
+ // therefore invisible when remote debugging a mobile Firefox.
+ return false;
+ }
+
+ // Only track mouse movement when the the overlay is shown
+ // Prevents mouse tracking when the user isn't paused
+ const { pageListenerTarget } = this.env;
+ pageListenerTarget.addEventListener("mousemove", this);
+
+ // Show the highlighter's root element.
+ const root = this.getElement("root");
+ root.removeAttribute("hidden");
+ root.setAttribute("overlay", "true");
+
+ // Set the text to appear in the toolbar.
+ const toolbar = this.getElement("toolbar");
+ this.getElement("reason").setTextContent(reason);
+ toolbar.removeAttribute("hidden");
+
+ // When the debugger pauses execution in a page, events will not be delivered
+ // to any handlers added to elements on that page. So here we use the
+ // document's setSuppressedEventListener interface to still be able to act on mouse
+ // events (they'll be handled by the `handleEvent` method)
+ this.env.window.document.setSuppressedEventListener(this);
+ return true;
+ },
+
+ hide() {
+ if (this.env.isXUL) {
+ return;
+ }
+
+ const { pageListenerTarget } = this.env;
+ pageListenerTarget.removeEventListener("mousemove", this);
+
+ // Hide the overlay.
+ this.getElement("root").setAttribute("hidden", "true");
+ },
+};
+exports.PausedDebuggerOverlay = PausedDebuggerOverlay;
diff --git a/devtools/server/actors/highlighters/rulers.js b/devtools/server/actors/highlighters/rulers.js
new file mode 100644
index 0000000000..fc5c66c6b7
--- /dev/null
+++ b/devtools/server/actors/highlighters/rulers.js
@@ -0,0 +1,341 @@
+/* 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";
+
+const EventEmitter = require("devtools/shared/event-emitter");
+const {
+ getCurrentZoom,
+ setIgnoreLayoutChanges,
+} = require("devtools/shared/layout/utils");
+const {
+ CanvasFrameAnonymousContentHelper,
+} = require("devtools/server/actors/highlighters/utils/markup");
+
+// Maximum size, in pixel, for the horizontal ruler and vertical ruler
+// used by RulersHighlighter
+const RULERS_MAX_X_AXIS = 10000;
+const RULERS_MAX_Y_AXIS = 15000;
+// Number of steps after we add a graduation, marker and text in
+// RulersHighliter; currently the unit is in pixel.
+const RULERS_GRADUATION_STEP = 5;
+const RULERS_MARKER_STEP = 50;
+const RULERS_TEXT_STEP = 100;
+
+/**
+ * The RulersHighlighter is a class that displays both horizontal and
+ * vertical rules on the page, along the top and left edges, with pixel
+ * graduations, useful for users to quickly check distances
+ */
+function RulersHighlighter(highlighterEnv) {
+ this.env = highlighterEnv;
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+
+ const { pageListenerTarget } = highlighterEnv;
+ pageListenerTarget.addEventListener("scroll", this);
+ pageListenerTarget.addEventListener("pagehide", this);
+}
+
+RulersHighlighter.prototype = {
+ ID_CLASS_PREFIX: "rulers-highlighter-",
+
+ _buildMarkup: function() {
+ const prefix = this.ID_CLASS_PREFIX;
+
+ const createRuler = (axis, size) => {
+ let width, height;
+ let isHorizontal = true;
+
+ if (axis === "x") {
+ width = size;
+ height = 16;
+ } else if (axis === "y") {
+ width = 16;
+ height = size;
+ isHorizontal = false;
+ } else {
+ throw new Error(
+ `Invalid type of axis given; expected "x" or "y" but got "${axis}"`
+ );
+ }
+
+ const g = this.markup.createSVGNode({
+ nodeType: "g",
+ attributes: {
+ id: `${axis}-axis`,
+ },
+ parent: svg,
+ prefix,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "rect",
+ attributes: {
+ y: isHorizontal ? 0 : 16,
+ width,
+ height,
+ },
+ parent: g,
+ });
+
+ const gRule = this.markup.createSVGNode({
+ nodeType: "g",
+ attributes: {
+ id: `${axis}-axis-ruler`,
+ },
+ parent: g,
+ prefix,
+ });
+
+ const pathGraduations = this.markup.createSVGNode({
+ nodeType: "path",
+ attributes: {
+ class: "ruler-graduations",
+ width,
+ height,
+ },
+ parent: gRule,
+ prefix,
+ });
+
+ const pathMarkers = this.markup.createSVGNode({
+ nodeType: "path",
+ attributes: {
+ class: "ruler-markers",
+ width,
+ height,
+ },
+ parent: gRule,
+ prefix,
+ });
+
+ const gText = this.markup.createSVGNode({
+ nodeType: "g",
+ attributes: {
+ id: `${axis}-axis-text`,
+ class: (isHorizontal ? "horizontal" : "vertical") + "-labels",
+ },
+ parent: g,
+ prefix,
+ });
+
+ let dGraduations = "";
+ let dMarkers = "";
+ let graduationLength;
+
+ for (let i = 0; i < size; i += RULERS_GRADUATION_STEP) {
+ if (i === 0) {
+ continue;
+ }
+
+ graduationLength = i % 2 === 0 ? 6 : 4;
+
+ if (i % RULERS_TEXT_STEP === 0) {
+ graduationLength = 8;
+ this.markup.createSVGNode({
+ nodeType: "text",
+ parent: gText,
+ attributes: {
+ x: isHorizontal ? 2 + i : -i - 1,
+ y: 5,
+ },
+ }).textContent = i;
+ }
+
+ if (isHorizontal) {
+ if (i % RULERS_MARKER_STEP === 0) {
+ dMarkers += `M${i} 0 L${i} ${graduationLength}`;
+ } else {
+ dGraduations += `M${i} 0 L${i} ${graduationLength} `;
+ }
+ } else if (i % 50 === 0) {
+ dMarkers += `M0 ${i} L${graduationLength} ${i}`;
+ } else {
+ dGraduations += `M0 ${i} L${graduationLength} ${i}`;
+ }
+ }
+
+ pathGraduations.setAttribute("d", dGraduations);
+ pathMarkers.setAttribute("d", dMarkers);
+
+ return g;
+ };
+
+ const container = this.markup.createNode({
+ attributes: { class: "highlighter-container" },
+ });
+
+ const root = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ },
+ prefix,
+ });
+
+ const svg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: root,
+ attributes: {
+ id: "elements",
+ class: "elements",
+ width: "100%",
+ height: "100%",
+ hidden: "true",
+ },
+ prefix,
+ });
+
+ createRuler("x", RULERS_MAX_X_AXIS);
+ createRuler("y", RULERS_MAX_Y_AXIS);
+
+ this.markup.createNode({
+ parent: container,
+ attributes: {
+ class: "viewport-infobar-container",
+ id: "viewport-infobar-container",
+ position: "top",
+ },
+ prefix,
+ });
+
+ return container;
+ },
+
+ handleEvent: function(event) {
+ switch (event.type) {
+ case "scroll":
+ this._onScroll(event);
+ break;
+ case "pagehide":
+ // If a page hide event is triggered for current window's highlighter, hide the
+ // highlighter.
+ if (event.target.defaultView === this.env.window) {
+ this.destroy();
+ }
+ break;
+ }
+ },
+
+ _onScroll: function(event) {
+ const prefix = this.ID_CLASS_PREFIX;
+ const { scrollX, scrollY } = event.view;
+
+ this.markup
+ .getElement(`${prefix}x-axis-ruler`)
+ .setAttribute("transform", `translate(${-scrollX})`);
+ this.markup
+ .getElement(`${prefix}x-axis-text`)
+ .setAttribute("transform", `translate(${-scrollX})`);
+ this.markup
+ .getElement(`${prefix}y-axis-ruler`)
+ .setAttribute("transform", `translate(0, ${-scrollY})`);
+ this.markup
+ .getElement(`${prefix}y-axis-text`)
+ .setAttribute("transform", `translate(0, ${-scrollY})`);
+ },
+
+ _update: function() {
+ const { window } = this.env;
+
+ setIgnoreLayoutChanges(true);
+
+ const zoom = getCurrentZoom(window);
+ const isZoomChanged = zoom !== this._zoom;
+
+ if (isZoomChanged) {
+ this._zoom = zoom;
+ this.updateViewport();
+ }
+
+ this.updateViewportInfobar();
+
+ setIgnoreLayoutChanges(false, window.document.documentElement);
+
+ this._rafID = window.requestAnimationFrame(() => this._update());
+ },
+
+ _cancelUpdate: function() {
+ if (this._rafID) {
+ this.env.window.cancelAnimationFrame(this._rafID);
+ this._rafID = 0;
+ }
+ },
+ updateViewport: function() {
+ const { devicePixelRatio } = this.env.window;
+
+ // Because `devicePixelRatio` is affected by zoom (see bug 809788),
+ // in order to get the "real" device pixel ratio, we need divide by `zoom`
+ const pixelRatio = devicePixelRatio / this._zoom;
+
+ // The "real" device pixel ratio is used to calculate the max stroke
+ // width we can actually assign: on retina, for instance, it would be 0.5,
+ // where on non high dpi monitor would be 1.
+ const minWidth = 1 / pixelRatio;
+ const strokeWidth = Math.min(minWidth, minWidth / this._zoom);
+
+ this.markup
+ .getElement(this.ID_CLASS_PREFIX + "root")
+ .setAttribute("style", `stroke-width:${strokeWidth};`);
+ },
+
+ updateViewportInfobar: function() {
+ const { window } = this.env;
+ const { innerHeight, innerWidth } = window;
+ const infobarId = this.ID_CLASS_PREFIX + "viewport-infobar-container";
+ const textContent = innerWidth + "px \u00D7 " + innerHeight + "px";
+ this.markup.getElement(infobarId).setTextContent(textContent);
+ },
+
+ destroy: function() {
+ this.hide();
+
+ const { pageListenerTarget } = this.env;
+
+ if (pageListenerTarget) {
+ pageListenerTarget.removeEventListener("scroll", this);
+ pageListenerTarget.removeEventListener("pagehide", this);
+ }
+
+ this.markup.destroy();
+
+ EventEmitter.emit(this, "destroy");
+ },
+
+ show: function() {
+ this.markup.removeAttributeForElement(
+ this.ID_CLASS_PREFIX + "elements",
+ "hidden"
+ );
+ this.markup.removeAttributeForElement(
+ this.ID_CLASS_PREFIX + "viewport-infobar-container",
+ "hidden"
+ );
+
+ this._update();
+
+ return true;
+ },
+
+ hide: function() {
+ this.markup.setAttributeForElement(
+ this.ID_CLASS_PREFIX + "elements",
+ "hidden",
+ "true"
+ );
+ this.markup.setAttributeForElement(
+ this.ID_CLASS_PREFIX + "viewport-infobar-container",
+ "hidden",
+ "true"
+ );
+
+ this._cancelUpdate();
+ },
+};
+exports.RulersHighlighter = RulersHighlighter;
diff --git a/devtools/server/actors/highlighters/selector.js b/devtools/server/actors/highlighters/selector.js
new file mode 100644
index 0000000000..c09b963320
--- /dev/null
+++ b/devtools/server/actors/highlighters/selector.js
@@ -0,0 +1,97 @@
+/* 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";
+
+const {
+ isNodeValid,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ BoxModelHighlighter,
+} = require("devtools/server/actors/highlighters/box-model");
+
+// How many maximum nodes can be highlighted at the same time by the SelectorHighlighter
+const MAX_HIGHLIGHTED_ELEMENTS = 100;
+
+/**
+ * The SelectorHighlighter runs a given selector through querySelectorAll on the
+ * document of the provided context node and then uses the BoxModelHighlighter
+ * to highlight the matching nodes
+ */
+function SelectorHighlighter(highlighterEnv) {
+ this.highlighterEnv = highlighterEnv;
+ this._highlighters = [];
+}
+
+SelectorHighlighter.prototype = {
+ /**
+ * Show a BoxModelHighlighter on each node that matches a given selector.
+ *
+ * @param {DOMNode} node
+ * A context node used to get the document element on which to run
+ * querySelectorAll(). This node will not be highlighted.
+ * @param {Object} options
+ * Configuration options for SelectorHighlighter.
+ * All of the options for BoxModelHighlighter.show() are also valid here.
+ * @param {String} options.selector
+ * Required. CSS selector used with querySelectorAll() to find matching elements.
+ */
+ show: async function(node, options = {}) {
+ this.hide();
+
+ if (!isNodeValid(node) || !options.selector) {
+ return false;
+ }
+
+ let nodes = [];
+ try {
+ nodes = [...node.ownerDocument.querySelectorAll(options.selector)];
+ } catch (e) {
+ // It's fine if the provided selector is invalid, `nodes` will be an empty array.
+ }
+
+ // Prevent passing the `selector` option to BoxModelHighlighter
+ delete options.selector;
+
+ const promises = [];
+ for (let i = 0; i < Math.min(nodes.length, MAX_HIGHLIGHTED_ELEMENTS); i++) {
+ promises.push(this._showHighlighter(nodes[i], options));
+ }
+
+ await Promise.all(promises);
+ return true;
+ },
+
+ /**
+ * Create an instance of BoxModelHighlighter, wait for it to be ready
+ * (see CanvasFrameAnonymousContentHelper.initialize()),
+ * then show the highlighter on the given node with the given configuration options.
+ *
+ * @param {DOMNode} node
+ * Node to be highlighted
+ * @param {Object} options
+ * Configuration options for the BoxModelHighlighter
+ * @return {Promise} Promise that resolves when the BoxModelHighlighter is ready
+ */
+ _showHighlighter: async function(node, options) {
+ const highlighter = new BoxModelHighlighter(this.highlighterEnv);
+ await highlighter.isReady;
+
+ highlighter.show(node, options);
+ this._highlighters.push(highlighter);
+ },
+
+ hide: function() {
+ for (const highlighter of this._highlighters) {
+ highlighter.destroy();
+ }
+ this._highlighters = [];
+ },
+
+ destroy: function() {
+ this.hide();
+ this.highlighterEnv = null;
+ },
+};
+exports.SelectorHighlighter = SelectorHighlighter;
diff --git a/devtools/server/actors/highlighters/shapes.js b/devtools/server/actors/highlighters/shapes.js
new file mode 100644
index 0000000000..bad75f5ca8
--- /dev/null
+++ b/devtools/server/actors/highlighters/shapes.js
@@ -0,0 +1,3259 @@
+/* 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";
+
+const {
+ CanvasFrameAnonymousContentHelper,
+ getComputedStyle,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const {
+ setIgnoreLayoutChanges,
+ getCurrentZoom,
+ getAdjustedQuads,
+ getFrameOffsets,
+} = require("devtools/shared/layout/utils");
+const {
+ AutoRefreshHighlighter,
+} = require("devtools/server/actors/highlighters/auto-refresh");
+const {
+ getDistance,
+ clickedOnEllipseEdge,
+ distanceToLine,
+ projection,
+ clickedOnPoint,
+} = require("devtools/server/actors/utils/shapes-utils");
+const {
+ identity,
+ apply,
+ translate,
+ multiply,
+ scale,
+ rotate,
+ changeMatrixBase,
+ getBasis,
+} = require("devtools/shared/layout/dom-matrix-2d");
+const EventEmitter = require("devtools/shared/event-emitter");
+const { getCSSStyleRules } = require("devtools/shared/inspector/css-logic");
+
+const BASE_MARKER_SIZE = 5;
+// the width of the area around highlighter lines that can be clicked, in px
+const LINE_CLICK_WIDTH = 5;
+const ROTATE_LINE_LENGTH = 50;
+const DOM_EVENTS = ["mousedown", "mousemove", "mouseup", "dblclick"];
+const _dragging = Symbol("shapes/dragging");
+
+/**
+ * The ShapesHighlighter draws an outline shapes in the page.
+ * The idea is to have something that is able to wrap complex shapes for css properties
+ * such as shape-outside/inside, clip-path but also SVG elements.
+ *
+ * Notes on shape transformation:
+ *
+ * When using transform mode to translate, scale, and rotate shapes, a transformation
+ * matrix keeps track of the transformations done to the original shape. When the
+ * highlighter is toggled on/off or between transform mode and point editing mode,
+ * the transformations applied to the shape become permanent.
+ *
+ * While transformations are being performed on a shape, there is an "original" and
+ * a "transformed" coordinate system. This is used when scaling or rotating a rotated
+ * shape.
+ *
+ * The "original" coordinate system is the one where (0,0) is at the top left corner
+ * of the page, the x axis is horizontal, and the y axis is vertical.
+ *
+ * The "transformed" coordinate system is the one where (0,0) is at the top left
+ * corner of the current shape. The x axis follows the north edge of the shape
+ * (from the northwest corner to the northeast corner) and the y axis follows
+ * the west edge of the shape (from the northwest corner to the southwest corner).
+ *
+ * Because of rotation, the "north" and "west" edges might not actually be at the
+ * top and left of the transformed shape. Imagine that the compass directions are
+ * also rotated along with the shape.
+ *
+ * A refresher for coordinates and change of basis that may be helpful:
+ * https://www.math.ubc.ca/~behrend/math221/Coords.pdf
+ *
+ * @param {String} options.hoverPoint
+ * The point to highlight.
+ * @param {Boolean} options.transformMode
+ * Whether to show the highlighter in transforms mode.
+ * @param {} options.mode
+ */
+class ShapesHighlighter extends AutoRefreshHighlighter {
+ constructor(highlighterEnv) {
+ super(highlighterEnv);
+ EventEmitter.decorate(this);
+
+ this.ID_CLASS_PREFIX = "shapes-";
+
+ this.referenceBox = "border";
+ this.useStrokeBox = false;
+ this.geometryBox = "";
+ this.hoveredPoint = null;
+ this.fillRule = "";
+ this.numInsetPoints = 0;
+ this.transformMode = false;
+ this.viewport = {};
+
+ this.markup = new CanvasFrameAnonymousContentHelper(
+ this.highlighterEnv,
+ this._buildMarkup.bind(this)
+ );
+ this.isReady = this.markup.initialize();
+ this.onPageHide = this.onPageHide.bind(this);
+
+ const { pageListenerTarget } = this.highlighterEnv;
+ DOM_EVENTS.forEach(event =>
+ pageListenerTarget.addEventListener(event, this)
+ );
+ pageListenerTarget.addEventListener("pagehide", this.onPageHide);
+ }
+
+ _buildMarkup() {
+ const container = this.markup.createNode({
+ attributes: {
+ class: "highlighter-container",
+ },
+ });
+
+ // The root wrapper is used to unzoom the highlighter when needed.
+ const rootWrapper = this.markup.createNode({
+ parent: container,
+ attributes: {
+ id: "root",
+ class: "root",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const mainSvg = this.markup.createSVGNode({
+ nodeType: "svg",
+ parent: rootWrapper,
+ attributes: {
+ id: "shape-container",
+ class: "shape-container",
+ viewBox: "0 0 100 100",
+ preserveAspectRatio: "none",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // This clipPath and its children make sure the element quad outline
+ // is only shown when the shape extends past the element quads.
+ const clipSvg = this.markup.createSVGNode({
+ nodeType: "clipPath",
+ parent: mainSvg,
+ attributes: {
+ id: "clip-path",
+ class: "clip-path",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: clipSvg,
+ attributes: {
+ id: "clip-polygon",
+ class: "clip-polygon",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "ellipse",
+ parent: clipSvg,
+ attributes: {
+ id: "clip-ellipse",
+ class: "clip-ellipse",
+ hidden: true,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "rect",
+ parent: clipSvg,
+ attributes: {
+ id: "clip-rect",
+ class: "clip-rect",
+ hidden: true,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Rectangle that displays the element quads. Only shown for shape-outside.
+ // Only the parts of the rectangle's outline that overlap with the shape is shown.
+ this.markup.createSVGNode({
+ nodeType: "rect",
+ parent: mainSvg,
+ attributes: {
+ id: "quad",
+ class: "quad",
+ hidden: "true",
+ "clip-path": "url(#shapes-clip-path)",
+ x: 0,
+ y: 0,
+ width: 100,
+ height: 100,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // clipPath that corresponds to the element's quads. Only applied for shape-outside.
+ // This ensures only the parts of the shape that are within the element's quads are
+ // outlined by a solid line.
+ const shapeClipSvg = this.markup.createSVGNode({
+ nodeType: "clipPath",
+ parent: mainSvg,
+ attributes: {
+ id: "quad-clip-path",
+ class: "quad-clip-path",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "rect",
+ parent: shapeClipSvg,
+ attributes: {
+ id: "quad-clip",
+ class: "quad-clip",
+ x: -1,
+ y: -1,
+ width: 102,
+ height: 102,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ const mainGroup = this.markup.createSVGNode({
+ nodeType: "g",
+ parent: mainSvg,
+ attributes: {
+ id: "group",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Append a polygon for polygon shapes.
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: mainGroup,
+ attributes: {
+ id: "polygon",
+ class: "polygon",
+ hidden: "true",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Append an ellipse for circle/ellipse shapes.
+ this.markup.createSVGNode({
+ nodeType: "ellipse",
+ parent: mainGroup,
+ attributes: {
+ id: "ellipse",
+ class: "ellipse",
+ hidden: true,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Append a rect for inset().
+ this.markup.createSVGNode({
+ nodeType: "rect",
+ parent: mainGroup,
+ attributes: {
+ id: "rect",
+ class: "rect",
+ hidden: true,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Dashed versions of each shape. Only shown for the parts of the shape
+ // that extends past the element's quads.
+ this.markup.createSVGNode({
+ nodeType: "polygon",
+ parent: mainGroup,
+ attributes: {
+ id: "dashed-polygon",
+ class: "polygon",
+ hidden: "true",
+ "stroke-dasharray": "5, 5",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "ellipse",
+ parent: mainGroup,
+ attributes: {
+ id: "dashed-ellipse",
+ class: "ellipse",
+ hidden: "true",
+ "stroke-dasharray": "5, 5",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "rect",
+ parent: mainGroup,
+ attributes: {
+ id: "dashed-rect",
+ class: "rect",
+ hidden: "true",
+ "stroke-dasharray": "5, 5",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: mainGroup,
+ attributes: {
+ id: "bounding-box",
+ class: "bounding-box",
+ "stroke-dasharray": "5, 5",
+ hidden: true,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: mainGroup,
+ attributes: {
+ id: "rotate-line",
+ class: "rotate-line",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ // Append a path to display the markers for the shape.
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: mainGroup,
+ attributes: {
+ id: "markers-outline",
+ class: "markers-outline",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: mainGroup,
+ attributes: {
+ id: "markers",
+ class: "markers",
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ this.markup.createSVGNode({
+ nodeType: "path",
+ parent: mainGroup,
+ attributes: {
+ id: "marker-hover",
+ class: "marker-hover",
+ hidden: true,
+ },
+ prefix: this.ID_CLASS_PREFIX,
+ });
+
+ return container;
+ }
+
+ get currentDimensions() {
+ let dims = this.currentQuads[this.referenceBox][0].bounds;
+ const zoom = getCurrentZoom(this.win);
+
+ // If an SVG element has a stroke, currentQuads will return the stroke bounding box.
+ // However, clip-path always uses the object bounding box unless "stroke-box" is
+ // specified. So, we must calculate the object bounding box if there is a stroke
+ // and "stroke-box" is not specified. stroke only applies to SVG elements, so use
+ // getBBox, which only exists for SVG, to check if currentNode is an SVG element.
+ if (
+ this.currentNode.getBBox &&
+ getComputedStyle(this.currentNode).stroke !== "none" &&
+ !this.useStrokeBox
+ ) {
+ dims = getObjectBoundingBox(
+ dims.top,
+ dims.left,
+ dims.width,
+ dims.height,
+ this.currentNode
+ );
+ }
+
+ return {
+ top: dims.top / zoom,
+ left: dims.left / zoom,
+ width: dims.width / zoom,
+ height: dims.height / zoom,
+ };
+ }
+
+ get frameDimensions() {
+ // In an iframe, we get the node's quads relative to the frame, instead of the parent
+ // document.
+ let dims =
+ this.highlighterEnv.window.document === this.currentNode.ownerDocument
+ ? this.currentQuads[this.referenceBox][0].bounds
+ : getAdjustedQuads(
+ this.currentNode.ownerGlobal,
+ this.currentNode,
+ this.referenceBox
+ )[0].bounds;
+ const zoom = getCurrentZoom(this.win);
+
+ // If an SVG element has a stroke, currentQuads will return the stroke bounding box.
+ // However, clip-path always uses the object bounding box unless "stroke-box" is
+ // specified. So, we must calculate the object bounding box if there is a stroke
+ // and "stroke-box" is not specified. stroke only applies to SVG elements, so use
+ // getBBox, which only exists for SVG, to check if currentNode is an SVG element.
+ if (
+ this.currentNode.getBBox &&
+ getComputedStyle(this.currentNode).stroke !== "none" &&
+ !this.useStrokeBox
+ ) {
+ dims = getObjectBoundingBox(
+ dims.top,
+ dims.left,
+ dims.width,
+ dims.height,
+ this.currentNode
+ );
+ }
+
+ return {
+ top: dims.top / zoom,
+ left: dims.left / zoom,
+ width: dims.width / zoom,
+ height: dims.height / zoom,
+ };
+ }
+
+ /**
+ * Changes the appearance of the mouse cursor on the highlighter.
+ *
+ * Because we can't attach event handlers to individual elements in the
+ * highlighter, we determine if the mouse is hovering over a point by seeing if
+ * it's within 5 pixels of it. This creates a square hitbox that doesn't match
+ * perfectly with the circular markers. So if we were to use the :hover
+ * pseudo-class to apply changes to the mouse cursor, the cursor change would not
+ * always accurately reflect whether you can interact with the point. This is
+ * also the reason we have the hidden marker-hover element instead of using CSS
+ * to fill in the marker.
+ *
+ * In addition, the cursor CSS property is applied to .shapes-root because if
+ * it were attached to .shapes-marker, the cursor change no longer applies if
+ * you are for example resizing the shape and your mouse goes off the point.
+ * Also, if you are dragging a polygon point, the marker plays catch up to your
+ * mouse position, resulting in an undesirable visual effect where the cursor
+ * rapidly flickers between "grab" and "auto".
+ *
+ * @param {String} cursorType the name of the cursor to display
+ */
+ setCursor(cursorType) {
+ const container = this.getElement("root");
+ let style = container.getAttribute("style");
+ // remove existing cursor definitions in the style
+ style = style.replace(/cursor:.*?;/g, "");
+ style = style.replace(/pointer-events:.*?;/g, "");
+ const pointerEvents = cursorType === "auto" ? "none" : "auto";
+ container.setAttribute(
+ "style",
+ `${style}pointer-events:${pointerEvents};cursor:${cursorType};`
+ );
+ }
+
+ /**
+ * Set the absolute pixel offsets which define the current viewport in relation to
+ * the full page size.
+ *
+ * If a padding value is given, inset the viewport by this value. This is used to define
+ * a virtual viewport which ensures some element remains visible even when at the edges
+ * of the actual viewport.
+ *
+ * @param {Number} padding
+ * Optional. Amount by which to inset the viewport in all directions.
+ */
+ setViewport(padding = 0) {
+ let xOffset = 0;
+ let yOffset = 0;
+
+ // If the node exists within an iframe, get offsets for the virtual viewport so that
+ // points can be dragged to the extent of the global window, outside of the iframe
+ // window.
+ if (this.currentNode.ownerGlobal !== this.win) {
+ const win = this.win;
+ const nodeWin = this.currentNode.ownerGlobal;
+ // Get bounding box of iframe document relative to global document.
+ const bounds = nodeWin.document
+ .getBoxQuads({
+ relativeTo: win.document,
+ createFramesForSuppressedWhitespace: false,
+ })[0]
+ .getBounds();
+ xOffset = bounds.left - nodeWin.scrollX + win.scrollX;
+ yOffset = bounds.top - nodeWin.scrollY + win.scrollY;
+ }
+
+ const { pageXOffset, pageYOffset } = this.win;
+ const { clientHeight, clientWidth } = this.win.document.documentElement;
+ const left = pageXOffset + padding - xOffset;
+ const right = clientWidth + pageXOffset - padding - xOffset;
+ const top = pageYOffset + padding - yOffset;
+ const bottom = clientHeight + pageYOffset - padding - yOffset;
+ this.viewport = { left, right, top, bottom, padding };
+ }
+
+ // eslint-disable-next-line complexity
+ handleEvent(event, id) {
+ // No event handling if the highlighter is hidden
+ if (this.areShapesHidden()) {
+ return;
+ }
+
+ let { target, type, pageX, pageY } = event;
+
+ // For events on highlighted nodes in an iframe, when the event takes place
+ // outside the iframe. Check if event target belongs to the iframe. If it doesn't,
+ // adjust pageX/pageY to be relative to the iframe rather than the parent.
+ const nodeDocument = this.currentNode.ownerDocument;
+ if (target !== nodeDocument && target.ownerDocument !== nodeDocument) {
+ const [xOffset, yOffset] = getFrameOffsets(
+ target.ownerGlobal,
+ this.currentNode
+ );
+ const zoom = getCurrentZoom(this.win);
+ // xOffset/yOffset are relative to the viewport, so first find the top/left
+ // edges of the viewport relative to the page.
+ const viewportLeft = pageX - event.clientX;
+ const viewportTop = pageY - event.clientY;
+ // Also adjust for scrolling in the iframe.
+ const { scrollTop, scrollLeft } = nodeDocument.documentElement;
+ pageX -= viewportLeft + xOffset / zoom - scrollLeft;
+ pageY -= viewportTop + yOffset / zoom - scrollTop;
+ }
+
+ switch (type) {
+ case "pagehide":
+ // If a page hide event is triggered for current window's highlighter, hide the
+ // highlighter.
+ if (target.defaultView === this.win) {
+ this.destroy();
+ }
+
+ break;
+ case "mousedown":
+ if (this.transformMode) {
+ this._handleTransformClick(pageX, pageY);
+ } else if (this.shapeType === "polygon") {
+ this._handlePolygonClick(pageX, pageY);
+ } else if (this.shapeType === "circle") {
+ this._handleCircleClick(pageX, pageY);
+ } else if (this.shapeType === "ellipse") {
+ this._handleEllipseClick(pageX, pageY);
+ } else if (this.shapeType === "inset") {
+ this._handleInsetClick(pageX, pageY);
+ }
+ event.stopPropagation();
+ event.preventDefault();
+
+ // Calculate constraints for a virtual viewport which ensures that a dragged
+ // marker remains visible even at the edges of the actual viewport.
+ this.setViewport(BASE_MARKER_SIZE);
+ break;
+ case "mouseup":
+ if (this[_dragging]) {
+ this[_dragging] = null;
+ this._handleMarkerHover(this.hoveredPoint);
+ }
+ break;
+ case "mousemove":
+ if (!this[_dragging]) {
+ this._handleMouseMoveNotDragging(pageX, pageY);
+ return;
+ }
+ event.stopPropagation();
+ event.preventDefault();
+
+ // Set constraints for mouse position to ensure dragged marker stays in viewport.
+ const { left, right, top, bottom } = this.viewport;
+ pageX = Math.min(Math.max(left, pageX), right);
+ pageY = Math.min(Math.max(top, pageY), bottom);
+
+ const { point } = this[_dragging];
+ if (this.transformMode) {
+ this._handleTransformMove(pageX, pageY);
+ } else if (this.shapeType === "polygon") {
+ this._handlePolygonMove(pageX, pageY);
+ } else if (this.shapeType === "circle") {
+ this._handleCircleMove(point, pageX, pageY);
+ } else if (this.shapeType === "ellipse") {
+ this._handleEllipseMove(point, pageX, pageY);
+ } else if (this.shapeType === "inset") {
+ this._handleInsetMove(point, pageX, pageY);
+ }
+ break;
+ case "dblclick":
+ if (this.shapeType === "polygon" && !this.transformMode) {
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const index = this.getPolygonPointAt(percentX, percentY);
+ if (index === -1) {
+ this.getPolygonClickedLine(percentX, percentY);
+ return;
+ }
+
+ this._deletePolygonPoint(index);
+ }
+ break;
+ }
+ }
+
+ /**
+ * Handle a mouse click in transform mode.
+ * @param {Number} pageX the x coordinate of the mouse
+ * @param {Number} pageY the y coordinate of the mouse
+ */
+ _handleTransformClick(pageX, pageY) {
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const type = this.getTransformPointAt(percentX, percentY);
+ if (!type) {
+ return;
+ }
+
+ if (this.shapeType === "polygon") {
+ this._handlePolygonTransformClick(pageX, pageY, type);
+ } else if (this.shapeType === "circle") {
+ this._handleCircleTransformClick(pageX, pageY, type);
+ } else if (this.shapeType === "ellipse") {
+ this._handleEllipseTransformClick(pageX, pageY, type);
+ } else if (this.shapeType === "inset") {
+ this._handleInsetTransformClick(pageX, pageY, type);
+ }
+ }
+
+ /**
+ * Handle a click in transform mode while highlighting a polygon.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ * @param {String} type the type of transform handle that was clicked.
+ */
+ _handlePolygonTransformClick(pageX, pageY, type) {
+ const { width, height } = this.currentDimensions;
+ const pointsInfo = this.origCoordUnits.map(([x, y], i) => {
+ const xComputed = (this.origCoordinates[i][0] / 100) * width;
+ const yComputed = (this.origCoordinates[i][1] / 100) * height;
+ const unitX = getUnit(x);
+ const unitY = getUnit(y);
+ const valueX = isUnitless(x) ? xComputed : parseFloat(x);
+ const valueY = isUnitless(y) ? yComputed : parseFloat(y);
+
+ const ratioX = this.getUnitToPixelRatio(unitX, width);
+ const ratioY = this.getUnitToPixelRatio(unitY, height);
+ return { unitX, unitY, valueX, valueY, ratioX, ratioY };
+ });
+ this[_dragging] = {
+ type,
+ pointsInfo,
+ x: pageX,
+ y: pageY,
+ bb: this.boundingBox,
+ matrix: this.transformMatrix,
+ transformedBB: this.transformedBoundingBox,
+ };
+ this._handleMarkerHover(this.hoveredPoint);
+ }
+
+ /**
+ * Handle a click in transform mode while highlighting a circle.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ * @param {String} type the type of transform handle that was clicked.
+ */
+ _handleCircleTransformClick(pageX, pageY, type) {
+ const { width, height } = this.currentDimensions;
+ const { cx, cy } = this.origCoordUnits;
+ const cxComputed = (this.origCoordinates.cx / 100) * width;
+ const cyComputed = (this.origCoordinates.cy / 100) * height;
+ const unitX = getUnit(cx);
+ const unitY = getUnit(cy);
+ const valueX = isUnitless(cx) ? cxComputed : parseFloat(cx);
+ const valueY = isUnitless(cy) ? cyComputed : parseFloat(cy);
+
+ const ratioX = this.getUnitToPixelRatio(unitX, width);
+ const ratioY = this.getUnitToPixelRatio(unitY, height);
+
+ let { radius } = this.origCoordinates;
+ const computedSize = Math.sqrt(width ** 2 + height ** 2) / Math.sqrt(2);
+ radius = (radius / 100) * computedSize;
+ let valueRad = this.origCoordUnits.radius;
+ const unitRad = getUnit(valueRad);
+ valueRad = isUnitless(valueRad) ? radius : parseFloat(valueRad);
+ const ratioRad = this.getUnitToPixelRatio(unitRad, computedSize);
+
+ this[_dragging] = {
+ type,
+ unitX,
+ unitY,
+ unitRad,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ ratioRad,
+ x: pageX,
+ y: pageY,
+ bb: this.boundingBox,
+ matrix: this.transformMatrix,
+ transformedBB: this.transformedBoundingBox,
+ };
+ }
+
+ /**
+ * Handle a click in transform mode while highlighting an ellipse.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ * @param {String} type the type of transform handle that was clicked.
+ */
+ _handleEllipseTransformClick(pageX, pageY, type) {
+ const { width, height } = this.currentDimensions;
+ const { cx, cy } = this.origCoordUnits;
+ const cxComputed = (this.origCoordinates.cx / 100) * width;
+ const cyComputed = (this.origCoordinates.cy / 100) * height;
+ const unitX = getUnit(cx);
+ const unitY = getUnit(cy);
+ const valueX = isUnitless(cx) ? cxComputed : parseFloat(cx);
+ const valueY = isUnitless(cy) ? cyComputed : parseFloat(cy);
+
+ const ratioX = this.getUnitToPixelRatio(unitX, width);
+ const ratioY = this.getUnitToPixelRatio(unitY, height);
+
+ let { rx, ry } = this.origCoordinates;
+ rx = (rx / 100) * width;
+ let valueRX = this.origCoordUnits.rx;
+ const unitRX = getUnit(valueRX);
+ valueRX = isUnitless(valueRX) ? rx : parseFloat(valueRX);
+ const ratioRX = valueRX / rx || 1;
+ ry = (ry / 100) * height;
+ let valueRY = this.origCoordUnits.ry;
+ const unitRY = getUnit(valueRY);
+ valueRY = isUnitless(valueRY) ? ry : parseFloat(valueRY);
+ const ratioRY = valueRY / ry || 1;
+
+ this[_dragging] = {
+ type,
+ unitX,
+ unitY,
+ unitRX,
+ unitRY,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ ratioRX,
+ ratioRY,
+ x: pageX,
+ y: pageY,
+ bb: this.boundingBox,
+ matrix: this.transformMatrix,
+ transformedBB: this.transformedBoundingBox,
+ };
+ }
+
+ /**
+ * Handle a click in transform mode while highlighting an inset.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ * @param {String} type the type of transform handle that was clicked.
+ */
+ _handleInsetTransformClick(pageX, pageY, type) {
+ const { width, height } = this.currentDimensions;
+ const pointsInfo = {};
+ ["top", "right", "bottom", "left"].forEach(point => {
+ let value = this.origCoordUnits[point];
+ const size = point === "left" || point === "right" ? width : height;
+ const computedValue = (this.origCoordinates[point] / 100) * size;
+ const unit = getUnit(value);
+ value = isUnitless(value) ? computedValue : parseFloat(value);
+ const ratio = this.getUnitToPixelRatio(unit, size);
+
+ pointsInfo[point] = { value, unit, ratio };
+ });
+ this[_dragging] = {
+ type,
+ pointsInfo,
+ x: pageX,
+ y: pageY,
+ bb: this.boundingBox,
+ matrix: this.transformMatrix,
+ transformedBB: this.transformedBoundingBox,
+ };
+ }
+
+ /**
+ * Handle mouse movement after a click on a handle in transform mode.
+ * @param {Number} pageX the x coordinate of the mouse
+ * @param {Number} pageY the y coordinate of the mouse
+ */
+ _handleTransformMove(pageX, pageY) {
+ const { type } = this[_dragging];
+ if (type === "translate") {
+ this._translateShape(pageX, pageY);
+ } else if (type.includes("scale")) {
+ this._scaleShape(pageX, pageY);
+ } else if (type === "rotate" && this.shapeType === "polygon") {
+ this._rotateShape(pageX, pageY);
+ }
+
+ this.transformedBoundingBox = this.calculateTransformedBoundingBox();
+ }
+
+ /**
+ * Translates a shape based on the current mouse position.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ */
+ _translateShape(pageX, pageY) {
+ const { x, y, matrix } = this[_dragging];
+ const deltaX = pageX - x;
+ const deltaY = pageY - y;
+ this.transformMatrix = multiply(translate(deltaX, deltaY), matrix);
+
+ if (this.shapeType === "polygon") {
+ this._transformPolygon();
+ } else if (this.shapeType === "circle") {
+ this._transformCircle();
+ } else if (this.shapeType === "ellipse") {
+ this._transformEllipse();
+ } else if (this.shapeType === "inset") {
+ this._transformInset();
+ }
+ }
+
+ /**
+ * Scales a shape according to the current mouse position.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ */
+ _scaleShape(pageX, pageY) {
+ /**
+ * To scale a shape:
+ * 1) Get the change of basis matrix corresponding to the current transformation
+ * matrix of the shape.
+ * 2) Convert the mouse x/y deltas to the "transformed" coordinate system, using
+ * the change of base matrix.
+ * 3) Calculate the proportion to which the shape should be scaled to, using the
+ * mouse x/y deltas and the width/height of the transformed shape.
+ * 4) Translate the shape such that the anchor (the point opposite to the one
+ * being dragged) is at the top left of the element.
+ * 5) Scale each point by multiplying by the scaling proportion.
+ * 6) Translate the shape back such that the anchor is in its original position.
+ */
+ const { type, x, y, matrix } = this[_dragging];
+ const { width, height } = this.currentDimensions;
+ // The point opposite to the one being dragged
+ const anchor = getAnchorPoint(type);
+
+ const { ne, nw, sw } = this[_dragging].transformedBB;
+ // u/v are the basis vectors of the transformed coordinate system.
+ const u = [
+ ((ne[0] - nw[0]) / 100) * width,
+ ((ne[1] - nw[1]) / 100) * height,
+ ];
+ const v = [
+ ((sw[0] - nw[0]) / 100) * width,
+ ((sw[1] - nw[1]) / 100) * height,
+ ];
+ // uLength/vLength represent the width/height of the shape in the
+ // transformed coordinate system.
+ const { basis, invertedBasis, uLength, vLength } = getBasis(u, v);
+
+ // How much points on each axis should be translated before scaling
+ const transX = (this[_dragging].transformedBB[anchor][0] / 100) * width;
+ const transY = (this[_dragging].transformedBB[anchor][1] / 100) * height;
+
+ // Distance from original click to current mouse position
+ const distanceX = pageX - x;
+ const distanceY = pageY - y;
+ // Convert from original coordinate system to transformed coordinate system
+ const tDistanceX =
+ invertedBasis[0] * distanceX + invertedBasis[1] * distanceY;
+ const tDistanceY =
+ invertedBasis[3] * distanceX + invertedBasis[4] * distanceY;
+
+ // Proportion of distance to bounding box width/height of shape
+ const proportionX = tDistanceX / uLength;
+ const proportionY = tDistanceY / vLength;
+ // proportionX is positive for size reductions dragging on w/nw/sw,
+ // negative for e/ne/se.
+ const scaleX = type.includes("w") ? 1 - proportionX : 1 + proportionX;
+ // proportionT is positive for size reductions dragging on n/nw/ne,
+ // negative for s/sw/se.
+ const scaleY = type.includes("n") ? 1 - proportionY : 1 + proportionY;
+ // Take the average of scaleX/scaleY for scaling on two axes
+ const scaleXY = (scaleX + scaleY) / 2;
+
+ const translateMatrix = translate(-transX, -transY);
+ let scaleMatrix = identity();
+ // The scale matrices are in the transformed coordinate system. We must convert
+ // them to the original coordinate system before applying it to the transformation
+ // matrix.
+ if (type === "scale-e" || type === "scale-w") {
+ scaleMatrix = changeMatrixBase(scale(scaleX, 1), invertedBasis, basis);
+ } else if (type === "scale-n" || type === "scale-s") {
+ scaleMatrix = changeMatrixBase(scale(1, scaleY), invertedBasis, basis);
+ } else {
+ scaleMatrix = changeMatrixBase(
+ scale(scaleXY, scaleXY),
+ invertedBasis,
+ basis
+ );
+ }
+ const translateBackMatrix = translate(transX, transY);
+ this.transformMatrix = multiply(
+ translateBackMatrix,
+ multiply(scaleMatrix, multiply(translateMatrix, matrix))
+ );
+
+ if (this.shapeType === "polygon") {
+ this._transformPolygon();
+ } else if (this.shapeType === "circle") {
+ this._transformCircle(transX);
+ } else if (this.shapeType === "ellipse") {
+ this._transformEllipse(transX, transY);
+ } else if (this.shapeType === "inset") {
+ this._transformInset();
+ }
+ }
+
+ /**
+ * Rotates a polygon based on the current mouse position.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ */
+ _rotateShape(pageX, pageY) {
+ const { matrix } = this[_dragging];
+ const { center, ne, nw, sw } = this[_dragging].transformedBB;
+ const { width, height } = this.currentDimensions;
+ const centerX = (center[0] / 100) * width;
+ const centerY = (center[1] / 100) * height;
+ const { x: pageCenterX, y: pageCenterY } = this.convertPercentToPageCoords(
+ ...center
+ );
+
+ const dx = pageCenterX - pageX;
+ const dy = pageCenterY - pageY;
+
+ const u = [
+ ((ne[0] - nw[0]) / 100) * width,
+ ((ne[1] - nw[1]) / 100) * height,
+ ];
+ const v = [
+ ((sw[0] - nw[0]) / 100) * width,
+ ((sw[1] - nw[1]) / 100) * height,
+ ];
+ const { invertedBasis } = getBasis(u, v);
+
+ const tdx = invertedBasis[0] * dx + invertedBasis[1] * dy;
+ const tdy = invertedBasis[3] * dx + invertedBasis[4] * dy;
+ const angle = Math.atan2(tdx, tdy);
+ const translateMatrix = translate(-centerX, -centerY);
+ const rotateMatrix = rotate(angle);
+ const translateBackMatrix = translate(centerX, centerY);
+ this.transformMatrix = multiply(
+ translateBackMatrix,
+ multiply(rotateMatrix, multiply(translateMatrix, matrix))
+ );
+
+ this._transformPolygon();
+ }
+
+ /**
+ * Transform a polygon depending on the current transformation matrix.
+ */
+ _transformPolygon() {
+ const { pointsInfo } = this[_dragging];
+
+ let polygonDef = this.fillRule ? `${this.fillRule}, ` : "";
+ polygonDef += pointsInfo
+ .map(point => {
+ const { unitX, unitY, valueX, valueY, ratioX, ratioY } = point;
+ const vector = [valueX / ratioX, valueY / ratioY];
+ let [newX, newY] = apply(this.transformMatrix, vector);
+ newX = round(newX * ratioX, unitX);
+ newY = round(newY * ratioY, unitY);
+
+ return `${newX}${unitX} ${newY}${unitY}`;
+ })
+ .join(", ");
+ polygonDef = `polygon(${polygonDef}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", { type: "shape-change", value: polygonDef });
+ }
+
+ /**
+ * Transform a circle depending on the current transformation matrix.
+ * @param {Number} transX the number of pixels the shape is translated on the x axis
+ * before scaling
+ */
+ _transformCircle(transX = null) {
+ const {
+ unitX,
+ unitY,
+ unitRad,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ ratioRad,
+ } = this[_dragging];
+ let { radius } = this.coordUnits;
+
+ let [newCx, newCy] = apply(this.transformMatrix, [
+ valueX / ratioX,
+ valueY / ratioY,
+ ]);
+ if (transX !== null) {
+ // As part of scaling, the shape is translated to be tangent to the line y=0.
+ // To get the new radius, we translate the new cx back to that point and get
+ // the distance to the line y=0.
+ radius = round(Math.abs((newCx - transX) * ratioRad), unitRad);
+ radius = `${radius}${unitRad}`;
+ }
+
+ newCx = round(newCx * ratioX, unitX);
+ newCy = round(newCy * ratioY, unitY);
+ const circleDef =
+ `circle(${radius} at ${newCx}${unitX} ${newCy}${unitY})` +
+ ` ${this.geometryBox}`.trim();
+ this.emit("highlighter-event", { type: "shape-change", value: circleDef });
+ }
+
+ /**
+ * Transform an ellipse depending on the current transformation matrix.
+ * @param {Number} transX the number of pixels the shape is translated on the x axis
+ * before scaling
+ * @param {Number} transY the number of pixels the shape is translated on the y axis
+ * before scaling
+ */
+ _transformEllipse(transX = null, transY = null) {
+ const {
+ unitX,
+ unitY,
+ unitRX,
+ unitRY,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ ratioRX,
+ ratioRY,
+ } = this[_dragging];
+ let { rx, ry } = this.coordUnits;
+
+ let [newCx, newCy] = apply(this.transformMatrix, [
+ valueX / ratioX,
+ valueY / ratioY,
+ ]);
+ if (transX !== null && transY !== null) {
+ // As part of scaling, the shape is translated to be tangent to the lines y=0 & x=0.
+ // To get the new radii, we translate the new center back to that point and get the
+ // distances to the line x=0 and y=0.
+ rx = round(Math.abs((newCx - transX) * ratioRX), unitRX);
+ rx = `${rx}${unitRX}`;
+ ry = round(Math.abs((newCy - transY) * ratioRY), unitRY);
+ ry = `${ry}${unitRY}`;
+ }
+
+ newCx = round(newCx * ratioX, unitX);
+ newCy = round(newCy * ratioY, unitY);
+
+ const centerStr = `${newCx}${unitX} ${newCy}${unitY}`;
+ const ellipseDef = `ellipse(${rx} ${ry} at ${centerStr}) ${this.geometryBox}`.trim();
+ this.emit("highlighter-event", { type: "shape-change", value: ellipseDef });
+ }
+
+ /**
+ * Transform an inset depending on the current transformation matrix.
+ */
+ _transformInset() {
+ const { top, left, right, bottom } = this[_dragging].pointsInfo;
+ const { width, height } = this.currentDimensions;
+
+ const topLeft = [left.value / left.ratio, top.value / top.ratio];
+ let [newLeft, newTop] = apply(this.transformMatrix, topLeft);
+ newLeft = round(newLeft * left.ratio, left.unit);
+ newLeft = `${newLeft}${left.unit}`;
+ newTop = round(newTop * top.ratio, top.unit);
+ newTop = `${newTop}${top.unit}`;
+
+ // Right and bottom values are relative to the right and bottom edges of the
+ // element, so convert to the value relative to the left/top edges before scaling
+ // and convert back.
+ const bottomRight = [
+ width - right.value / right.ratio,
+ height - bottom.value / bottom.ratio,
+ ];
+ let [newRight, newBottom] = apply(this.transformMatrix, bottomRight);
+ newRight = round((width - newRight) * right.ratio, right.unit);
+ newRight = `${newRight}${right.unit}`;
+ newBottom = round((height - newBottom) * bottom.ratio, bottom.unit);
+ newBottom = `${newBottom}${bottom.unit}`;
+
+ let insetDef = this.insetRound
+ ? `inset(${newTop} ${newRight} ${newBottom} ${newLeft} round ${this.insetRound})`
+ : `inset(${newTop} ${newRight} ${newBottom} ${newLeft})`;
+ insetDef += this.geometryBox ? this.geometryBox : "";
+
+ this.emit("highlighter-event", { type: "shape-change", value: insetDef });
+ }
+
+ /**
+ * Handle a click when highlighting a polygon.
+ * @param {Number} pageX the x coordinate of the click
+ * @param {Number} pageY the y coordinate of the click
+ */
+ _handlePolygonClick(pageX, pageY) {
+ const { width, height } = this.currentDimensions;
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const point = this.getPolygonPointAt(percentX, percentY);
+ if (point === -1) {
+ return;
+ }
+
+ const [x, y] = this.coordUnits[point];
+ const xComputed = (this.coordinates[point][0] / 100) * width;
+ const yComputed = (this.coordinates[point][1] / 100) * height;
+ const unitX = getUnit(x);
+ const unitY = getUnit(y);
+ const valueX = isUnitless(x) ? xComputed : parseFloat(x);
+ const valueY = isUnitless(y) ? yComputed : parseFloat(y);
+
+ const ratioX = this.getUnitToPixelRatio(unitX, width);
+ const ratioY = this.getUnitToPixelRatio(unitY, height);
+
+ this.setCursor("grabbing");
+ this[_dragging] = {
+ point,
+ unitX,
+ unitY,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ x: pageX,
+ y: pageY,
+ };
+ }
+
+ /**
+ * Update the dragged polygon point with the given x/y coords and update
+ * the element style.
+ * @param {Number} pageX the new x coordinate of the point
+ * @param {Number} pageY the new y coordinate of the point
+ */
+ _handlePolygonMove(pageX, pageY) {
+ const { point, unitX, unitY, valueX, valueY, ratioX, ratioY, x, y } = this[
+ _dragging
+ ];
+ const deltaX = (pageX - x) * ratioX;
+ const deltaY = (pageY - y) * ratioY;
+ const newX = round(valueX + deltaX, unitX);
+ const newY = round(valueY + deltaY, unitY);
+
+ let polygonDef = this.fillRule ? `${this.fillRule}, ` : "";
+ polygonDef += this.coordUnits
+ .map((coords, i) => {
+ return i === point
+ ? `${newX}${unitX} ${newY}${unitY}`
+ : `${coords[0]} ${coords[1]}`;
+ })
+ .join(", ");
+ polygonDef = `polygon(${polygonDef}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", { type: "shape-change", value: polygonDef });
+ }
+
+ /**
+ * Add new point to the polygon defintion and update element style.
+ * TODO: Bug 1436054 - Do not default to percentage unit when inserting new point.
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=1436054
+ *
+ * @param {Number} after the index of the point that the new point should be added after
+ * @param {Number} x the x coordinate of the new point
+ * @param {Number} y the y coordinate of the new point
+ */
+ _addPolygonPoint(after, x, y) {
+ let polygonDef = this.fillRule ? `${this.fillRule}, ` : "";
+ polygonDef += this.coordUnits
+ .map((coords, i) => {
+ return i === after
+ ? `${coords[0]} ${coords[1]}, ${x}% ${y}%`
+ : `${coords[0]} ${coords[1]}`;
+ })
+ .join(", ");
+ polygonDef = `polygon(${polygonDef}) ${this.geometryBox}`.trim();
+
+ this.hoveredPoint = after + 1;
+ this._emitHoverEvent(this.hoveredPoint);
+ this.emit("highlighter-event", { type: "shape-change", value: polygonDef });
+ }
+
+ /**
+ * Remove point from polygon defintion and update the element style.
+ * @param {Number} point the index of the point to delete
+ */
+ _deletePolygonPoint(point) {
+ const coordinates = this.coordUnits.slice();
+ coordinates.splice(point, 1);
+ let polygonDef = this.fillRule ? `${this.fillRule}, ` : "";
+ polygonDef += coordinates
+ .map((coords, i) => {
+ return `${coords[0]} ${coords[1]}`;
+ })
+ .join(", ");
+ polygonDef = `polygon(${polygonDef}) ${this.geometryBox}`.trim();
+
+ this.hoveredPoint = null;
+ this._emitHoverEvent(this.hoveredPoint);
+ this.emit("highlighter-event", { type: "shape-change", value: polygonDef });
+ }
+ /**
+ * Handle a click when highlighting a circle.
+ * @param {Number} pageX the x coordinate of the click
+ * @param {Number} pageY the y coordinate of the click
+ */
+ _handleCircleClick(pageX, pageY) {
+ const { width, height } = this.currentDimensions;
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const point = this.getCirclePointAt(percentX, percentY);
+ if (!point) {
+ return;
+ }
+
+ this.setCursor("grabbing");
+ if (point === "center") {
+ const { cx, cy } = this.coordUnits;
+ const cxComputed = (this.coordinates.cx / 100) * width;
+ const cyComputed = (this.coordinates.cy / 100) * height;
+ const unitX = getUnit(cx);
+ const unitY = getUnit(cy);
+ const valueX = isUnitless(cx) ? cxComputed : parseFloat(cx);
+ const valueY = isUnitless(cy) ? cyComputed : parseFloat(cy);
+
+ const ratioX = this.getUnitToPixelRatio(unitX, width);
+ const ratioY = this.getUnitToPixelRatio(unitY, height);
+
+ this[_dragging] = {
+ point,
+ unitX,
+ unitY,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ x: pageX,
+ y: pageY,
+ };
+ } else if (point === "radius") {
+ let { radius } = this.coordinates;
+ const computedSize = Math.sqrt(width ** 2 + height ** 2) / Math.sqrt(2);
+ radius = (radius / 100) * computedSize;
+ let value = this.coordUnits.radius;
+ const unit = getUnit(value);
+ value = isUnitless(value) ? radius : parseFloat(value);
+ const ratio = this.getUnitToPixelRatio(unit, computedSize);
+
+ this[_dragging] = { point, value, origRadius: radius, unit, ratio };
+ }
+ }
+
+ /**
+ * Set the center/radius of the circle according to the mouse position and
+ * update the element style.
+ * @param {String} point either "center" or "radius"
+ * @param {Number} pageX the x coordinate of the mouse position, in terms of %
+ * relative to the element
+ * @param {Number} pageY the y coordinate of the mouse position, in terms of %
+ * relative to the element
+ */
+ _handleCircleMove(point, pageX, pageY) {
+ const { radius, cx, cy } = this.coordUnits;
+
+ if (point === "center") {
+ const { unitX, unitY, valueX, valueY, ratioX, ratioY, x, y } = this[
+ _dragging
+ ];
+ const deltaX = (pageX - x) * ratioX;
+ const deltaY = (pageY - y) * ratioY;
+ const newCx = `${round(valueX + deltaX, unitX)}${unitX}`;
+ const newCy = `${round(valueY + deltaY, unitY)}${unitY}`;
+ // if not defined by the user, geometryBox will be an empty string; trim() cleans up
+ const circleDef = `circle(${radius} at ${newCx} ${newCy}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", {
+ type: "shape-change",
+ value: circleDef,
+ });
+ } else if (point === "radius") {
+ const { value, unit, origRadius, ratio } = this[_dragging];
+ // convert center point to px, then get distance between center and mouse.
+ const { x: pageCx, y: pageCy } = this.convertPercentToPageCoords(
+ this.coordinates.cx,
+ this.coordinates.cy
+ );
+ const newRadiusPx = getDistance(pageCx, pageCy, pageX, pageY);
+
+ const delta = (newRadiusPx - origRadius) * ratio;
+ const newRadius = `${round(value + delta, unit)}${unit}`;
+
+ const circleDef = `circle(${newRadius} at ${cx} ${cy}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", {
+ type: "shape-change",
+ value: circleDef,
+ });
+ }
+ }
+
+ /**
+ * Handle a click when highlighting an ellipse.
+ * @param {Number} pageX the x coordinate of the click
+ * @param {Number} pageY the y coordinate of the click
+ */
+ _handleEllipseClick(pageX, pageY) {
+ const { width, height } = this.currentDimensions;
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const point = this.getEllipsePointAt(percentX, percentY);
+ if (!point) {
+ return;
+ }
+
+ this.setCursor("grabbing");
+ if (point === "center") {
+ const { cx, cy } = this.coordUnits;
+ const cxComputed = (this.coordinates.cx / 100) * width;
+ const cyComputed = (this.coordinates.cy / 100) * height;
+ const unitX = getUnit(cx);
+ const unitY = getUnit(cy);
+ const valueX = isUnitless(cx) ? cxComputed : parseFloat(cx);
+ const valueY = isUnitless(cy) ? cyComputed : parseFloat(cy);
+
+ const ratioX = this.getUnitToPixelRatio(unitX, width);
+ const ratioY = this.getUnitToPixelRatio(unitY, height);
+
+ this[_dragging] = {
+ point,
+ unitX,
+ unitY,
+ valueX,
+ valueY,
+ ratioX,
+ ratioY,
+ x: pageX,
+ y: pageY,
+ };
+ } else if (point === "rx") {
+ let { rx } = this.coordinates;
+ rx = (rx / 100) * width;
+ let value = this.coordUnits.rx;
+ const unit = getUnit(value);
+ value = isUnitless(value) ? rx : parseFloat(value);
+ const ratio = this.getUnitToPixelRatio(unit, width);
+
+ this[_dragging] = { point, value, origRadius: rx, unit, ratio };
+ } else if (point === "ry") {
+ let { ry } = this.coordinates;
+ ry = (ry / 100) * height;
+ let value = this.coordUnits.ry;
+ const unit = getUnit(value);
+ value = isUnitless(value) ? ry : parseFloat(value);
+ const ratio = this.getUnitToPixelRatio(unit, height);
+
+ this[_dragging] = { point, value, origRadius: ry, unit, ratio };
+ }
+ }
+
+ /**
+ * Set center/rx/ry of the ellispe according to the mouse position and update the
+ * element style.
+ * @param {String} point "center", "rx", or "ry"
+ * @param {Number} pageX the x coordinate of the mouse position, in terms of %
+ * relative to the element
+ * @param {Number} pageY the y coordinate of the mouse position, in terms of %
+ * relative to the element
+ */
+ _handleEllipseMove(point, pageX, pageY) {
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const { rx, ry, cx, cy } = this.coordUnits;
+
+ if (point === "center") {
+ const { unitX, unitY, valueX, valueY, ratioX, ratioY, x, y } = this[
+ _dragging
+ ];
+ const deltaX = (pageX - x) * ratioX;
+ const deltaY = (pageY - y) * ratioY;
+ const newCx = `${round(valueX + deltaX, unitX)}${unitX}`;
+ const newCy = `${round(valueY + deltaY, unitY)}${unitY}`;
+ const ellipseDef = `ellipse(${rx} ${ry} at ${newCx} ${newCy}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", {
+ type: "shape-change",
+ value: ellipseDef,
+ });
+ } else if (point === "rx") {
+ const { value, unit, origRadius, ratio } = this[_dragging];
+ const newRadiusPercent = Math.abs(percentX - this.coordinates.cx);
+ const { width } = this.currentDimensions;
+ const delta = ((newRadiusPercent / 100) * width - origRadius) * ratio;
+ const newRadius = `${round(value + delta, unit)}${unit}`;
+
+ const ellipseDef = `ellipse(${newRadius} ${ry} at ${cx} ${cy}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", {
+ type: "shape-change",
+ value: ellipseDef,
+ });
+ } else if (point === "ry") {
+ const { value, unit, origRadius, ratio } = this[_dragging];
+ const newRadiusPercent = Math.abs(percentY - this.coordinates.cy);
+ const { height } = this.currentDimensions;
+ const delta = ((newRadiusPercent / 100) * height - origRadius) * ratio;
+ const newRadius = `${round(value + delta, unit)}${unit}`;
+
+ const ellipseDef = `ellipse(${rx} ${newRadius} at ${cx} ${cy}) ${this.geometryBox}`.trim();
+
+ this.emit("highlighter-event", {
+ type: "shape-change",
+ value: ellipseDef,
+ });
+ }
+ }
+
+ /**
+ * Handle a click when highlighting an inset.
+ * @param {Number} pageX the x coordinate of the click
+ * @param {Number} pageY the y coordinate of the click
+ */
+ _handleInsetClick(pageX, pageY) {
+ const { width, height } = this.currentDimensions;
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ const point = this.getInsetPointAt(percentX, percentY);
+ if (!point) {
+ return;
+ }
+
+ this.setCursor("grabbing");
+ let value = this.coordUnits[point];
+ const size = point === "left" || point === "right" ? width : height;
+ const computedValue = (this.coordinates[point] / 100) * size;
+ const unit = getUnit(value);
+ value = isUnitless(value) ? computedValue : parseFloat(value);
+ const ratio = this.getUnitToPixelRatio(unit, size);
+ const origValue = point === "left" || point === "right" ? pageX : pageY;
+
+ this[_dragging] = { point, value, origValue, unit, ratio };
+ }
+
+ /**
+ * Set the top/left/right/bottom of the inset shape according to the mouse position
+ * and update the element style.
+ * @param {String} point "top", "left", "right", or "bottom"
+ * @param {Number} pageX the x coordinate of the mouse position, in terms of %
+ * relative to the element
+ * @param {Number} pageY the y coordinate of the mouse position, in terms of %
+ * relative to the element
+ * @memberof ShapesHighlighter
+ */
+ _handleInsetMove(point, pageX, pageY) {
+ let { top, left, right, bottom } = this.coordUnits;
+ const { value, origValue, unit, ratio } = this[_dragging];
+
+ if (point === "left") {
+ const delta = (pageX - origValue) * ratio;
+ left = `${round(value + delta, unit)}${unit}`;
+ } else if (point === "right") {
+ const delta = (pageX - origValue) * ratio;
+ right = `${round(value - delta, unit)}${unit}`;
+ } else if (point === "top") {
+ const delta = (pageY - origValue) * ratio;
+ top = `${round(value + delta, unit)}${unit}`;
+ } else if (point === "bottom") {
+ const delta = (pageY - origValue) * ratio;
+ bottom = `${round(value - delta, unit)}${unit}`;
+ }
+
+ let insetDef = this.insetRound
+ ? `inset(${top} ${right} ${bottom} ${left} round ${this.insetRound})`
+ : `inset(${top} ${right} ${bottom} ${left})`;
+
+ insetDef += this.geometryBox ? this.geometryBox : "";
+
+ this.emit("highlighter-event", { type: "shape-change", value: insetDef });
+ }
+
+ _handleMouseMoveNotDragging(pageX, pageY) {
+ const { percentX, percentY } = this.convertPageCoordsToPercent(
+ pageX,
+ pageY
+ );
+ if (this.transformMode) {
+ const point = this.getTransformPointAt(percentX, percentY);
+ this.hoveredPoint = point;
+ this._handleMarkerHover(point);
+ } else if (this.shapeType === "polygon") {
+ const point = this.getPolygonPointAt(percentX, percentY);
+ const oldHoveredPoint = this.hoveredPoint;
+ this.hoveredPoint = point !== -1 ? point : null;
+ if (this.hoveredPoint !== oldHoveredPoint) {
+ this._emitHoverEvent(this.hoveredPoint);
+ }
+ this._handleMarkerHover(point);
+ } else if (this.shapeType === "circle") {
+ const point = this.getCirclePointAt(percentX, percentY);
+ const oldHoveredPoint = this.hoveredPoint;
+ this.hoveredPoint = point ? point : null;
+ if (this.hoveredPoint !== oldHoveredPoint) {
+ this._emitHoverEvent(this.hoveredPoint);
+ }
+ this._handleMarkerHover(point);
+ } else if (this.shapeType === "ellipse") {
+ const point = this.getEllipsePointAt(percentX, percentY);
+ const oldHoveredPoint = this.hoveredPoint;
+ this.hoveredPoint = point ? point : null;
+ if (this.hoveredPoint !== oldHoveredPoint) {
+ this._emitHoverEvent(this.hoveredPoint);
+ }
+ this._handleMarkerHover(point);
+ } else if (this.shapeType === "inset") {
+ const point = this.getInsetPointAt(percentX, percentY);
+ const oldHoveredPoint = this.hoveredPoint;
+ this.hoveredPoint = point ? point : null;
+ if (this.hoveredPoint !== oldHoveredPoint) {
+ this._emitHoverEvent(this.hoveredPoint);
+ }
+ this._handleMarkerHover(point);
+ }
+ }
+
+ /**
+ * Change the appearance of the given marker when the mouse hovers over it.
+ * @param {String|Number} point if the shape is a polygon, the integer index of the
+ * point being hovered. Otherwise, a string identifying the point being hovered.
+ * Integers < 0 and falsey values excluding 0 indicate no point is being hovered.
+ */
+ _handleMarkerHover(point) {
+ // Hide hover marker for now, will be shown if point is a valid hover target
+ this.getElement("marker-hover").setAttribute("hidden", true);
+ // Catch all falsey values except when point === 0, as that's a valid point
+ if (!point && point !== 0) {
+ this.setCursor("auto");
+ return;
+ }
+ const hoverCursor = this[_dragging] ? "grabbing" : "grab";
+
+ if (this.transformMode) {
+ if (!point) {
+ this.setCursor("auto");
+ return;
+ }
+ const {
+ nw,
+ ne,
+ sw,
+ se,
+ n,
+ w,
+ s,
+ e,
+ rotatePoint,
+ center,
+ } = this.transformedBoundingBox;
+
+ const points = [
+ {
+ pointName: "translate",
+ x: center[0],
+ y: center[1],
+ cursor: hoverCursor,
+ },
+ { pointName: "scale-se", x: se[0], y: se[1], anchor: "nw" },
+ { pointName: "scale-ne", x: ne[0], y: ne[1], anchor: "sw" },
+ { pointName: "scale-sw", x: sw[0], y: sw[1], anchor: "ne" },
+ { pointName: "scale-nw", x: nw[0], y: nw[1], anchor: "se" },
+ { pointName: "scale-n", x: n[0], y: n[1], anchor: "s" },
+ { pointName: "scale-s", x: s[0], y: s[1], anchor: "n" },
+ { pointName: "scale-e", x: e[0], y: e[1], anchor: "w" },
+ { pointName: "scale-w", x: w[0], y: w[1], anchor: "e" },
+ {
+ pointName: "rotate",
+ x: rotatePoint[0],
+ y: rotatePoint[1],
+ cursor: hoverCursor,
+ },
+ ];
+
+ for (const { pointName, x, y, cursor, anchor } of points) {
+ if (point === pointName) {
+ this._drawHoverMarker([[x, y]]);
+
+ // If the point is a scale handle, we will need to determine the direction
+ // of the resize cursor based on the position of the handle relative to its
+ // "anchor" (the handle opposite to it).
+ if (pointName.includes("scale")) {
+ const direction = this.getRoughDirection(pointName, anchor);
+ this.setCursor(`${direction}-resize`);
+ } else {
+ this.setCursor(cursor);
+ }
+ }
+ }
+ } else if (this.shapeType === "polygon") {
+ if (point === -1) {
+ this.setCursor("auto");
+ return;
+ }
+ this.setCursor(hoverCursor);
+ this._drawHoverMarker([this.coordinates[point]]);
+ } else if (this.shapeType === "circle") {
+ this.setCursor(hoverCursor);
+
+ const { cx, cy, rx } = this.coordinates;
+ if (point === "radius") {
+ this._drawHoverMarker([[cx + rx, cy]]);
+ } else if (point === "center") {
+ this._drawHoverMarker([[cx, cy]]);
+ }
+ } else if (this.shapeType === "ellipse") {
+ this.setCursor(hoverCursor);
+
+ if (point === "center") {
+ const { cx, cy } = this.coordinates;
+ this._drawHoverMarker([[cx, cy]]);
+ } else if (point === "rx") {
+ const { cx, cy, rx } = this.coordinates;
+ this._drawHoverMarker([[cx + rx, cy]]);
+ } else if (point === "ry") {
+ const { cx, cy, ry } = this.coordinates;
+ this._drawHoverMarker([[cx, cy + ry]]);
+ }
+ } else if (this.shapeType === "inset") {
+ this.setCursor(hoverCursor);
+
+ const { top, right, bottom, left } = this.coordinates;
+ const centerX = (left + (100 - right)) / 2;
+ const centerY = (top + (100 - bottom)) / 2;
+ const points = point.split(",");
+ const coords = points.map(side => {
+ if (side === "top") {
+ return [centerX, top];
+ } else if (side === "right") {
+ return [100 - right, centerY];
+ } else if (side === "bottom") {
+ return [centerX, 100 - bottom];
+ } else if (side === "left") {
+ return [left, centerY];
+ }
+ return null;
+ });
+
+ this._drawHoverMarker(coords);
+ }
+ }
+
+ _drawHoverMarker(points) {
+ const { width, height } = this.currentDimensions;
+ const zoom = getCurrentZoom(this.win);
+ const path = points
+ .map(([x, y]) => {
+ return getCirclePath(BASE_MARKER_SIZE, x, y, width, height, zoom);
+ })
+ .join(" ");
+
+ const markerHover = this.getElement("marker-hover");
+ markerHover.setAttribute("d", path);
+ markerHover.removeAttribute("hidden");
+ }
+
+ _emitHoverEvent(point) {
+ if (point === null || point === undefined) {
+ this.emit("highlighter-event", {
+ type: "shape-hover-off",
+ });
+ } else {
+ this.emit("highlighter-event", {
+ type: "shape-hover-on",
+ point: point.toString(),
+ });
+ }
+ }
+
+ /**
+ * Convert the given coordinates on the page to percentages relative to the current
+ * element.
+ * @param {Number} pageX the x coordinate on the page
+ * @param {Number} pageY the y coordinate on the page
+ * @returns {Object} object of form {percentX, percentY}, which are the x/y coords
+ * in percentages relative to the element.
+ */
+ convertPageCoordsToPercent(pageX, pageY) {
+ // If the current node is in an iframe, we get dimensions relative to the frame.
+ const dims = this.frameDimensions;
+ const { top, left, width, height } = dims;
+ pageX -= left;
+ pageY -= top;
+ const percentX = (pageX * 100) / width;
+ const percentY = (pageY * 100) / height;
+ return { percentX, percentY };
+ }
+
+ /**
+ * Convert the given x/y coordinates, in percentages relative to the current element,
+ * to pixel coordinates relative to the page
+ * @param {Number} x the x coordinate
+ * @param {Number} y the y coordinate
+ * @returns {Object} object of form {x, y}, which are the x/y coords in pixels
+ * relative to the page
+ *
+ * @memberof ShapesHighlighter
+ */
+ convertPercentToPageCoords(x, y) {
+ const dims = this.frameDimensions;
+ const { top, left, width, height } = dims;
+ x = (x * width) / 100;
+ y = (y * height) / 100;
+ x += left;
+ y += top;
+ return { x, y };
+ }
+
+ /**
+ * Get which transformation should be applied based on the mouse position.
+ * @param {Number} pageX the x coordinate of the mouse.
+ * @param {Number} pageY the y coordinate of the mouse.
+ * @returns {String} a string describing the transformation that should be applied
+ * to the shape.
+ */
+ getTransformPointAt(pageX, pageY) {
+ const {
+ nw,
+ ne,
+ sw,
+ se,
+ n,
+ w,
+ s,
+ e,
+ rotatePoint,
+ center,
+ } = this.transformedBoundingBox;
+ const { width, height } = this.currentDimensions;
+ const zoom = getCurrentZoom(this.win);
+ const clickRadiusX = ((BASE_MARKER_SIZE / zoom) * 100) / width;
+ const clickRadiusY = ((BASE_MARKER_SIZE / zoom) * 100) / height;
+
+ const points = [
+ { pointName: "translate", x: center[0], y: center[1] },
+ { pointName: "scale-se", x: se[0], y: se[1] },
+ { pointName: "scale-ne", x: ne[0], y: ne[1] },
+ { pointName: "scale-sw", x: sw[0], y: sw[1] },
+ { pointName: "scale-nw", x: nw[0], y: nw[1] },
+ ];
+
+ if (this.shapeType === "polygon" || this.shapeType === "ellipse") {
+ points.push(
+ { pointName: "scale-n", x: n[0], y: n[1] },
+ { pointName: "scale-s", x: s[0], y: s[1] },
+ { pointName: "scale-e", x: e[0], y: e[1] },
+ { pointName: "scale-w", x: w[0], y: w[1] }
+ );
+ }
+
+ if (this.shapeType === "polygon") {
+ const x = rotatePoint[0];
+ const y = rotatePoint[1];
+ if (
+ pageX >= x - clickRadiusX &&
+ pageX <= x + clickRadiusX &&
+ pageY >= y - clickRadiusY &&
+ pageY <= y + clickRadiusY
+ ) {
+ return "rotate";
+ }
+ }
+
+ for (const { pointName, x, y } of points) {
+ if (
+ pageX >= x - clickRadiusX &&
+ pageX <= x + clickRadiusX &&
+ pageY >= y - clickRadiusY &&
+ pageY <= y + clickRadiusY
+ ) {
+ return pointName;
+ }
+ }
+
+ return "";
+ }
+
+ /**
+ * Get the id of the point on the polygon highlighter at the given coordinate.
+ * @param {Number} pageX the x coordinate on the page, in % relative to the element
+ * @param {Number} pageY the y coordinate on the page, in % relative to the element
+ * @returns {Number} the index of the point that was clicked on in this.coordinates,
+ * or -1 if none of the points were clicked on.
+ */
+ getPolygonPointAt(pageX, pageY) {
+ const { coordinates } = this;
+ const { width, height } = this.currentDimensions;
+ const zoom = getCurrentZoom(this.win);
+ const clickRadiusX = ((BASE_MARKER_SIZE / zoom) * 100) / width;
+ const clickRadiusY = ((BASE_MARKER_SIZE / zoom) * 100) / height;
+
+ for (const [index, coord] of coordinates.entries()) {
+ const [x, y] = coord;
+ if (
+ pageX >= x - clickRadiusX &&
+ pageX <= x + clickRadiusX &&
+ pageY >= y - clickRadiusY &&
+ pageY <= y + clickRadiusY
+ ) {
+ return index;
+ }
+ }
+
+ return -1;
+ }
+
+ /**
+ * Check if the mouse clicked on a line of the polygon, and if so, add a point near
+ * the click.
+ * @param {Number} pageX the x coordinate on the page, in % relative to the element
+ * @param {Number} pageY the y coordinate on the page, in % relative to the element
+ */
+ getPolygonClickedLine(pageX, pageY) {
+ const { coordinates } = this;
+ const { width } = this.currentDimensions;
+ const clickWidth = (LINE_CLICK_WIDTH * 100) / width;
+
+ for (let i = 0; i < coordinates.length; i++) {
+ const [x1, y1] = coordinates[i];
+ const [x2, y2] =
+ i === coordinates.length - 1 ? coordinates[0] : coordinates[i + 1];
+ // Get the distance between clicked point and line drawn between points 1 and 2
+ // to check if the click was on the line between those two points.
+ const distance = distanceToLine(x1, y1, x2, y2, pageX, pageY);
+ if (
+ distance <= clickWidth &&
+ Math.min(x1, x2) - clickWidth <= pageX &&
+ pageX <= Math.max(x1, x2) + clickWidth &&
+ Math.min(y1, y2) - clickWidth <= pageY &&
+ pageY <= Math.max(y1, y2) + clickWidth
+ ) {
+ // Get the point on the line closest to the clicked point.
+ const [newX, newY] = projection(x1, y1, x2, y2, pageX, pageY);
+ // Default unit for new points is percentages
+ this._addPolygonPoint(i, round(newX, "%"), round(newY, "%"));
+ return;
+ }
+ }
+ }
+
+ /**
+ * Check if the center point or radius of the circle highlighter is at given coords
+ * @param {Number} pageX the x coordinate on the page, in % relative to the element
+ * @param {Number} pageY the y coordinate on the page, in % relative to the element
+ * @returns {String} "center" if the center point was clicked, "radius" if the radius
+ * was clicked, "" if neither was clicked.
+ */
+ getCirclePointAt(pageX, pageY) {
+ const { cx, cy, rx, ry } = this.coordinates;
+ const { width, height } = this.currentDimensions;
+ const zoom = getCurrentZoom(this.win);
+ const clickRadiusX = ((BASE_MARKER_SIZE / zoom) * 100) / width;
+ const clickRadiusY = ((BASE_MARKER_SIZE / zoom) * 100) / height;
+
+ if (clickedOnPoint(pageX, pageY, cx, cy, clickRadiusX, clickRadiusY)) {
+ return "center";
+ }
+
+ const clickWidthX = (LINE_CLICK_WIDTH * 100) / width;
+ const clickWidthY = (LINE_CLICK_WIDTH * 100) / height;
+ if (
+ clickedOnEllipseEdge(
+ pageX,
+ pageY,
+ cx,
+ cy,
+ rx,
+ ry,
+ clickWidthX,
+ clickWidthY
+ ) ||
+ clickedOnPoint(pageX, pageY, cx + rx, cy, clickRadiusX, clickRadiusY)
+ ) {
+ return "radius";
+ }
+
+ return "";
+ }
+
+ /**
+ * Check if the center or rx/ry points of the ellipse highlighter is at given point
+ * @param {Number} pageX the x coordinate on the page, in % relative to the element
+ * @param {Number} pageY the y coordinate on the page, in % relative to the element
+ * @returns {String} "center" if the center point was clicked, "rx" if the x-radius
+ * point was clicked, "ry" if the y-radius point was clicked,
+ * "" if none was clicked.
+ */
+ getEllipsePointAt(pageX, pageY) {
+ const { cx, cy, rx, ry } = this.coordinates;
+ const { width, height } = this.currentDimensions;
+ const zoom = getCurrentZoom(this.win);
+ const clickRadiusX = ((BASE_MARKER_SIZE / zoom) * 100) / width;
+ const clickRadiusY = ((BASE_MARKER_SIZE / zoom) * 100) / height;
+
+ if (clickedOnPoint(pageX, pageY, cx, cy, clickRadiusX, clickRadiusY)) {
+ return "center";
+ }
+
+ if (clickedOnPoint(pageX, pageY, cx + rx, cy, clickRadiusX, clickRadiusY)) {
+ return "rx";
+ }
+
+ if (clickedOnPoint(pageX, pageY, cx, cy + ry, clickRadiusX, clickRadiusY)) {
+ return "ry";
+ }
+
+ return "";
+ }
+
+ /**
+ * Check if the edges of the inset highlighter is at given coords
+ * @param {Number} pageX the x coordinate on the page, in % relative to the element
+ * @param {Number} pageY the y coordinate on the page, in % relative to the element
+ * @returns {String} "top", "left", "right", or "bottom" if any of those edges were
+ * clicked. "" if none were clicked.
+ */
+ // eslint-disable-next-line complexity
+ getInsetPointAt(pageX, pageY) {
+ const { top, left, right, bottom } = this.coordinates;
+ const zoom = getCurrentZoom(this.win);
+ const { width, height } = this.currentDimensions;
+ const clickWidthX = (LINE_CLICK_WIDTH * 100) / width;
+ const clickWidthY = (LINE_CLICK_WIDTH * 100) / height;
+ const clickRadiusX = ((BASE_MARKER_SIZE / zoom) * 100) / width;
+ const clickRadiusY = ((BASE_MARKER_SIZE / zoom) * 100) / height;
+ const centerX = (left + (100 - right)) / 2;
+ const centerY = (top + (100 - bottom)) / 2;
+
+ if (
+ (pageX >= left - clickWidthX &&
+ pageX <= left + clickWidthX &&
+ pageY >= top &&
+ pageY <= 100 - bottom) ||
+ clickedOnPoint(pageX, pageY, left, centerY, clickRadiusX, clickRadiusY)
+ ) {
+ return "left";
+ }
+
+ if (
+ (pageX >= 100 - right - clickWidthX &&
+ pageX <= 100 - right + clickWidthX &&
+ pageY >= top &&
+ pageY <= 100 - bottom) ||
+ clickedOnPoint(
+ pageX,
+ pageY,
+ 100 - right,
+ centerY,
+ clickRadiusX,
+ clickRadiusY
+ )
+ ) {
+ return "right";
+ }
+
+ if (
+ (pageY >= top - clickWidthY &&
+ pageY <= top + clickWidthY &&
+ pageX >= left &&
+ pageX <= 100 - right) ||
+ clickedOnPoint(pageX, pageY, centerX, top, clickRadiusX, clickRadiusY)
+ ) {
+ return "top";
+ }
+
+ if (
+ (pageY >= 100 - bottom - clickWidthY &&
+ pageY <= 100 - bottom + clickWidthY &&
+ pageX >= left &&
+ pageX <= 100 - right) ||
+ clickedOnPoint(
+ pageX,
+ pageY,
+ centerX,
+ 100 - bottom,
+ clickRadiusX,
+ clickRadiusY
+ )
+ ) {
+ return "bottom";
+ }
+
+ return "";
+ }
+
+ /**
+ * Parses the CSS definition given and returns the shape type associated
+ * with the definition and the coordinates necessary to draw the shape.
+ * @param {String} definition the input CSS definition
+ * @returns {Object} null if the definition is not of a known shape type,
+ * or an object of the type { shapeType, coordinates }, where
+ * shapeType is the name of the shape and coordinates are an array
+ * or object of the coordinates needed to draw the shape.
+ */
+ _parseCSSShapeValue(definition) {
+ const shapeTypes = [
+ {
+ name: "polygon",
+ prefix: "polygon(",
+ coordParser: this.polygonPoints.bind(this),
+ },
+ {
+ name: "circle",
+ prefix: "circle(",
+ coordParser: this.circlePoints.bind(this),
+ },
+ {
+ name: "ellipse",
+ prefix: "ellipse(",
+ coordParser: this.ellipsePoints.bind(this),
+ },
+ {
+ name: "inset",
+ prefix: "inset(",
+ coordParser: this.insetPoints.bind(this),
+ },
+ ];
+ const geometryTypes = ["margin", "border", "padding", "content"];
+
+ // default to border for clip-path, and margin for shape-outside
+ let referenceBox = this.property === "clip-path" ? "border" : "margin";
+ for (const geometry of geometryTypes) {
+ if (definition.includes(geometry)) {
+ referenceBox = geometry;
+ }
+ }
+ this.referenceBox = referenceBox;
+
+ this.useStrokeBox = definition.includes("stroke-box");
+ this.geometryBox = definition
+ .substring(definition.lastIndexOf(")") + 1)
+ .trim();
+
+ for (const { name, prefix, coordParser } of shapeTypes) {
+ if (definition.includes(prefix)) {
+ // the closing paren of the shape function is always the last one in definition.
+ definition = definition.substring(
+ prefix.length,
+ definition.lastIndexOf(")")
+ );
+ return {
+ shapeType: name,
+ coordinates: coordParser(definition),
+ };
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Parses the definition of the CSS polygon() function and returns its points,
+ * converted to percentages.
+ * @param {String} definition the arguments of the polygon() function
+ * @returns {Array} an array of the points of the polygon, with all values
+ * evaluated and converted to percentages
+ */
+ polygonPoints(definition) {
+ this.coordUnits = this.polygonRawPoints();
+ if (!this.origCoordUnits) {
+ this.origCoordUnits = this.coordUnits;
+ }
+ const splitDef = definition.split(", ");
+ if (splitDef[0] === "evenodd" || splitDef[0] === "nonzero") {
+ splitDef.shift();
+ }
+ let minX = Number.MAX_SAFE_INTEGER;
+ let minY = Number.MAX_SAFE_INTEGER;
+ let maxX = Number.MIN_SAFE_INTEGER;
+ let maxY = Number.MIN_SAFE_INTEGER;
+ const coordinates = splitDef.map(coords => {
+ const [x, y] = splitCoords(coords).map(
+ this.convertCoordsToPercent.bind(this)
+ );
+ if (x < minX) {
+ minX = x;
+ }
+ if (y < minY) {
+ minY = y;
+ }
+ if (x > maxX) {
+ maxX = x;
+ }
+ if (y > maxY) {
+ maxY = y;
+ }
+ return [x, y];
+ });
+ this.boundingBox = { minX, minY, maxX, maxY };
+ if (!this.origBoundingBox) {
+ this.origBoundingBox = this.boundingBox;
+ }
+ return coordinates;
+ }
+
+ /**
+ * Parse the raw (non-computed) definition of the CSS polygon.
+ * @returns {Array} an array of the points of the polygon, with units preserved.
+ */
+ polygonRawPoints() {
+ let definition = getDefinedShapeProperties(this.currentNode, this.property);
+ if (definition === this.rawDefinition && this.coordUnits) {
+ return this.coordUnits;
+ }
+ this.rawDefinition = definition;
+ definition = definition.substring(8, definition.lastIndexOf(")"));
+ const splitDef = definition.split(", ");
+ if (splitDef[0].includes("evenodd") || splitDef[0].includes("nonzero")) {
+ this.fillRule = splitDef[0].trim();
+ splitDef.shift();
+ } else {
+ this.fillRule = "";
+ }
+ return splitDef.map(coords => {
+ return splitCoords(coords).map(coord => {
+ // Undo the insertion of &nbsp; that was done in splitCoords.
+ return coord.replace(/\u00a0/g, " ");
+ });
+ });
+ }
+
+ /**
+ * Parses the definition of the CSS circle() function and returns the x/y radiuses and
+ * center coordinates, converted to percentages.
+ * @param {String} definition the arguments of the circle() function
+ * @returns {Object} an object of the form { rx, ry, cx, cy }, where rx and ry are the
+ * radiuses for the x and y axes, and cx and cy are the x/y coordinates for the
+ * center of the circle. All values are evaluated and converted to percentages.
+ */
+ circlePoints(definition) {
+ this.coordUnits = this.circleRawPoints();
+ if (!this.origCoordUnits) {
+ this.origCoordUnits = this.coordUnits;
+ }
+
+ const values = definition.split("at");
+ let radius = values[0] ? values[0].trim() : "closest-side";
+ const { width, height } = this.currentDimensions;
+ const center = splitCoords(values[1]).map(
+ this.convertCoordsToPercent.bind(this)
+ );
+
+ // Percentage values for circle() are resolved from the
+ // used width and height of the reference box as sqrt(width^2+height^2)/sqrt(2).
+ const computedSize = Math.sqrt(width ** 2 + height ** 2) / Math.sqrt(2);
+
+ // Position coordinates for circle center in pixels.
+ const cxPx = (width * center[0]) / 100;
+ const cyPx = (height * center[1]) / 100;
+
+ if (radius === "closest-side") {
+ // radius is the distance from center to closest side of reference box
+ radius = Math.min(cxPx, cyPx, width - cxPx, height - cyPx);
+ radius = coordToPercent(`${radius}px`, computedSize);
+ } else if (radius === "farthest-side") {
+ // radius is the distance from center to farthest side of reference box
+ radius = Math.max(cxPx, cyPx, width - cxPx, height - cyPx);
+ radius = coordToPercent(`${radius}px`, computedSize);
+ } else if (radius.includes("calc(")) {
+ radius = evalCalcExpression(
+ radius.substring(5, radius.length - 1),
+ computedSize
+ );
+ } else {
+ radius = coordToPercent(radius, computedSize);
+ }
+
+ // Scale both radiusX and radiusY to match the radius computed
+ // using the above equation.
+ const ratioX = width / computedSize;
+ const ratioY = height / computedSize;
+ const radiusX = radius / ratioX;
+ const radiusY = radius / ratioY;
+
+ this.boundingBox = {
+ minX: center[0] - radiusX,
+ maxX: center[0] + radiusX,
+ minY: center[1] - radiusY,
+ maxY: center[1] + radiusY,
+ };
+ if (!this.origBoundingBox) {
+ this.origBoundingBox = this.boundingBox;
+ }
+ return { radius, rx: radiusX, ry: radiusY, cx: center[0], cy: center[1] };
+ }
+
+ /**
+ * Parse the raw (non-computed) definition of the CSS circle.
+ * @returns {Object} an object of the points of the circle (cx, cy, radius),
+ * with units preserved.
+ */
+ circleRawPoints() {
+ let definition = getDefinedShapeProperties(this.currentNode, this.property);
+ if (definition === this.rawDefinition && this.coordUnits) {
+ return this.coordUnits;
+ }
+ this.rawDefinition = definition;
+ definition = definition.substring(7, definition.lastIndexOf(")"));
+
+ const values = definition.split("at");
+ const [cx = "", cy = ""] = values[1]
+ ? splitCoords(values[1]).map(coord => {
+ // Undo the insertion of &nbsp; that was done in splitCoords.
+ return coord.replace(/\u00a0/g, " ");
+ })
+ : [];
+ const radius = values[0] ? values[0].trim() : "closest-side";
+ return { cx, cy, radius };
+ }
+
+ /**
+ * Parses the computed style definition of the CSS ellipse() function and returns the
+ * x/y radii and center coordinates, converted to percentages.
+ * @param {String} definition the arguments of the ellipse() function
+ * @returns {Object} an object of the form { rx, ry, cx, cy }, where rx and ry are the
+ * radiuses for the x and y axes, and cx and cy are the x/y coordinates for the
+ * center of the ellipse. All values are evaluated and converted to percentages
+ */
+ ellipsePoints(definition) {
+ this.coordUnits = this.ellipseRawPoints();
+ if (!this.origCoordUnits) {
+ this.origCoordUnits = this.coordUnits;
+ }
+
+ const values = definition.split("at");
+ const center = splitCoords(values[1]).map(
+ this.convertCoordsToPercent.bind(this)
+ );
+
+ let radii = values[0] ? values[0].trim() : "closest-side closest-side";
+ radii = splitCoords(radii).map((radius, i) => {
+ if (radius === "closest-side") {
+ // radius is the distance from center to closest x/y side of reference box
+ return i % 2 === 0
+ ? Math.min(center[0], 100 - center[0])
+ : Math.min(center[1], 100 - center[1]);
+ } else if (radius === "farthest-side") {
+ // radius is the distance from center to farthest x/y side of reference box
+ return i % 2 === 0
+ ? Math.max(center[0], 100 - center[0])
+ : Math.max(center[1], 100 - center[1]);
+ }
+ return this.convertCoordsToPercent(radius, i);
+ });
+
+ this.boundingBox = {
+ minX: center[0] - radii[0],
+ maxX: center[0] + radii[0],
+ minY: center[1] - radii[1],
+ maxY: center[1] + radii[1],
+ };
+ if (!this.origBoundingBox) {
+ this.origBoundingBox = this.boundingBox;
+ }
+ return { rx: radii[0], ry: radii[1], cx: center[0], cy: center[1] };
+ }
+
+ /**
+ * Parse the raw (non-computed) definition of the CSS ellipse.
+ * @returns {Object} an object of the points of the ellipse (cx, cy, rx, ry),
+ * with units preserved.
+ */
+ ellipseRawPoints() {
+ let definition = getDefinedShapeProperties(this.currentNode, this.property);
+ if (definition === this.rawDefinition && this.coordUnits) {
+ return this.coordUnits;
+ }
+ this.rawDefinition = definition;
+ definition = definition.substring(8, definition.lastIndexOf(")"));
+
+ const values = definition.split("at");
+ const [rx = "closest-side", ry = "closest-side"] = values[0]
+ ? splitCoords(values[0]).map(coord => {
+ // Undo the insertion of &nbsp; that was done in splitCoords.
+ return coord.replace(/\u00a0/g, " ");
+ })
+ : [];
+ const [cx = "", cy = ""] = values[1]
+ ? splitCoords(values[1]).map(coord => {
+ return coord.replace(/\u00a0/g, " ");
+ })
+ : [];
+ return { rx, ry, cx, cy };
+ }
+
+ /**
+ * Parses the definition of the CSS inset() function and returns the x/y offsets and
+ * width/height of the shape, converted to percentages. Border radiuses (given after
+ * "round" in the definition) are currently ignored.
+ * @param {String} definition the arguments of the inset() function
+ * @returns {Object} an object of the form { x, y, width, height }, which are the top/
+ * left positions and width/height of the shape.
+ */
+ insetPoints(definition) {
+ this.coordUnits = this.insetRawPoints();
+ if (!this.origCoordUnits) {
+ this.origCoordUnits = this.coordUnits;
+ }
+ const values = definition.split(" round ");
+ const offsets = splitCoords(values[0]).map(
+ this.convertCoordsToPercent.bind(this)
+ );
+
+ let top, left, right, bottom;
+ // The offsets, like margin/padding/border, are in order: top, right, bottom, left.
+ if (offsets.length === 1) {
+ top = left = right = bottom = offsets[0];
+ } else if (offsets.length === 2) {
+ top = bottom = offsets[0];
+ left = right = offsets[1];
+ } else if (offsets.length === 3) {
+ top = offsets[0];
+ left = right = offsets[1];
+ bottom = offsets[2];
+ } else if (offsets.length === 4) {
+ top = offsets[0];
+ right = offsets[1];
+ bottom = offsets[2];
+ left = offsets[3];
+ }
+
+ // maxX/maxY are found by subtracting the right/bottom edges from 100
+ // (the width/height of the element in %)
+ this.boundingBox = {
+ minX: left,
+ maxX: 100 - right,
+ minY: top,
+ maxY: 100 - bottom,
+ };
+ if (!this.origBoundingBox) {
+ this.origBoundingBox = this.boundingBox;
+ }
+ return { top, left, right, bottom };
+ }
+
+ /**
+ * Parse the raw (non-computed) definition of the CSS inset.
+ * @returns {Object} an object of the points of the inset (top, right, bottom, left),
+ * with units preserved.
+ */
+ insetRawPoints() {
+ let definition = getDefinedShapeProperties(this.currentNode, this.property);
+ if (definition === this.rawDefinition && this.coordUnits) {
+ return this.coordUnits;
+ }
+ this.rawDefinition = definition;
+ definition = definition.substring(6, definition.lastIndexOf(")"));
+
+ const values = definition.split(" round ");
+ this.insetRound = values[1];
+ const offsets = splitCoords(values[0]).map(coord => {
+ // Undo the insertion of &nbsp; that was done in splitCoords.
+ return coord.replace(/\u00a0/g, " ");
+ });
+
+ let top,
+ left,
+ right,
+ bottom = 0;
+
+ if (offsets.length === 1) {
+ top = left = right = bottom = offsets[0];
+ } else if (offsets.length === 2) {
+ top = bottom = offsets[0];
+ left = right = offsets[1];
+ } else if (offsets.length === 3) {
+ top = offsets[0];
+ left = right = offsets[1];
+ bottom = offsets[2];
+ } else if (offsets.length === 4) {
+ top = offsets[0];
+ right = offsets[1];
+ bottom = offsets[2];
+ left = offsets[3];
+ }
+
+ return { top, left, right, bottom };
+ }
+
+ convertCoordsToPercent(coord, i) {
+ const { width, height } = this.currentDimensions;
+ const size = i % 2 === 0 ? width : height;
+ if (coord.includes("calc(")) {
+ return evalCalcExpression(coord.substring(5, coord.length - 1), size);
+ }
+ return coordToPercent(coord, size);
+ }
+
+ /**
+ * Destroy the nodes. Remove listeners.
+ */
+ destroy() {
+ const { pageListenerTarget } = this.highlighterEnv;
+ if (pageListenerTarget) {
+ DOM_EVENTS.forEach(type =>
+ pageListenerTarget.removeEventListener(type, this)
+ );
+ }
+ super.destroy(this);
+ this.markup.destroy();
+ }
+
+ /**
+ * Get the element in the highlighter markup with the given id
+ * @param {String} id
+ * @returns {Object} the element with the given id
+ */
+ getElement(id) {
+ return this.markup.getElement(this.ID_CLASS_PREFIX + id);
+ }
+
+ /**
+ * Return whether all the elements used to draw shapes are hidden.
+ * @returns {Boolean}
+ */
+ areShapesHidden() {
+ return (
+ this.getElement("ellipse").hasAttribute("hidden") &&
+ this.getElement("polygon").hasAttribute("hidden") &&
+ this.getElement("rect").hasAttribute("hidden") &&
+ this.getElement("bounding-box").hasAttribute("hidden")
+ );
+ }
+
+ /**
+ * Show the highlighter on a given node
+ */
+ _show() {
+ this.hoveredPoint = this.options.hoverPoint;
+ this.transformMode = this.options.transformMode;
+ this.coordinates = null;
+ this.coordUnits = null;
+ this.origBoundingBox = null;
+ this.origCoordUnits = null;
+ this.origCoordinates = null;
+ this.transformedBoundingBox = null;
+ if (this.transformMode) {
+ this.transformMatrix = identity();
+ }
+ if (this._hasMoved() && this.transformMode) {
+ this.transformedBoundingBox = this.calculateTransformedBoundingBox();
+ }
+ return this._update();
+ }
+
+ /**
+ * The AutoRefreshHighlighter's _hasMoved method returns true only if the element's
+ * quads have changed. Override it so it also returns true if the element's shape has
+ * changed (which can happen when you change a CSS properties for instance).
+ */
+ _hasMoved() {
+ let hasMoved = AutoRefreshHighlighter.prototype._hasMoved.call(this);
+
+ if (hasMoved) {
+ this.origBoundingBox = null;
+ this.origCoordUnits = null;
+ this.origCoordinates = null;
+ if (this.transformMode) {
+ this.transformMatrix = identity();
+ }
+ }
+
+ const oldShapeCoordinates = JSON.stringify(this.coordinates);
+
+ // TODO: need other modes too.
+ if (this.options.mode.startsWith("css")) {
+ const property = shapeModeToCssPropertyName(this.options.mode);
+ // change camelCase to kebab-case
+ this.property = property.replace(/([a-z][A-Z])/g, g => {
+ return g[0] + "-" + g[1].toLowerCase();
+ });
+ const style = getComputedStyle(this.currentNode)[property];
+
+ if (!style || style === "none") {
+ this.coordinates = [];
+ this.shapeType = "none";
+ } else {
+ const { coordinates, shapeType } = this._parseCSSShapeValue(style);
+ this.coordinates = coordinates;
+ if (!this.origCoordinates) {
+ this.origCoordinates = coordinates;
+ }
+ this.shapeType = shapeType;
+ }
+ }
+
+ const newShapeCoordinates = JSON.stringify(this.coordinates);
+ hasMoved = hasMoved || oldShapeCoordinates !== newShapeCoordinates;
+ if (this.transformMode && hasMoved) {
+ this.transformedBoundingBox = this.calculateTransformedBoundingBox();
+ }
+
+ return hasMoved;
+ }
+
+ /**
+ * Hide all elements used to highlight CSS different shapes.
+ */
+ _hideShapes() {
+ this.getElement("ellipse").setAttribute("hidden", true);
+ this.getElement("polygon").setAttribute("hidden", true);
+ this.getElement("rect").setAttribute("hidden", true);
+ this.getElement("bounding-box").setAttribute("hidden", true);
+ this.getElement("markers").setAttribute("d", "");
+ this.getElement("markers-outline").setAttribute("d", "");
+ this.getElement("rotate-line").setAttribute("d", "");
+ this.getElement("quad").setAttribute("hidden", true);
+ this.getElement("clip-ellipse").setAttribute("hidden", true);
+ this.getElement("clip-polygon").setAttribute("hidden", true);
+ this.getElement("clip-rect").setAttribute("hidden", true);
+ this.getElement("dashed-polygon").setAttribute("hidden", true);
+ this.getElement("dashed-ellipse").setAttribute("hidden", true);
+ this.getElement("dashed-rect").setAttribute("hidden", true);
+ }
+
+ /**
+ * Update the highlighter for the current node. Called whenever the element's quads
+ * or CSS shape has changed.
+ * @returns {Boolean} whether the highlighter was successfully updated
+ */
+ _update() {
+ setIgnoreLayoutChanges(true);
+ this.getElement("group").setAttribute("transform", "");
+ const root = this.getElement("root");
+ root.setAttribute("hidden", true);
+
+ const { top, left, width, height } = this.currentDimensions;
+ const zoom = getCurrentZoom(this.win);
+
+ // Size the SVG like the current node.
+ this.getElement("shape-container").setAttribute(
+ "style",
+ `top:${top}px;left:${left}px;width:${width}px;height:${height}px;`
+ );
+
+ this._hideShapes();
+ this._updateShapes(width, height, zoom);
+
+ // For both shape-outside and clip-path the element's quads are displayed for the
+ // parts that overlap with the shape. The parts of the shape that extend past the
+ // element's quads are shown with a dashed line.
+ const quadRect = this.getElement("quad");
+ quadRect.removeAttribute("hidden");
+
+ this.getElement("polygon").setAttribute(
+ "clip-path",
+ "url(#shapes-quad-clip-path)"
+ );
+ this.getElement("ellipse").setAttribute(
+ "clip-path",
+ "url(#shapes-quad-clip-path)"
+ );
+ this.getElement("rect").setAttribute(
+ "clip-path",
+ "url(#shapes-quad-clip-path)"
+ );
+
+ const { width: winWidth, height: winHeight } = this._winDimensions;
+ root.removeAttribute("hidden");
+ root.setAttribute(
+ "style",
+ `position:absolute; width:${winWidth}px;height:${winHeight}px; overflow:hidden;`
+ );
+
+ this._handleMarkerHover(this.hoveredPoint);
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+
+ return true;
+ }
+
+ /**
+ * Update the SVGs to render the current CSS shape and add markers depending on shape
+ * type and transform mode.
+ * @param {Number} width the width of the element quads
+ * @param {Number} height the height of the element quads
+ * @param {Number} zoom the zoom level of the window
+ */
+ _updateShapes(width, height, zoom) {
+ if (this.transformMode && this.shapeType !== "none") {
+ this._updateTransformMode(width, height, zoom);
+ } else if (this.shapeType === "polygon") {
+ this._updatePolygonShape(width, height, zoom);
+ // Draw markers for each of the polygon's points.
+ this._drawMarkers(this.coordinates, width, height, zoom);
+ } else if (this.shapeType === "circle") {
+ const { rx, cx, cy } = this.coordinates;
+ // Shape renders for "circle()" and "ellipse()" use the same SVG nodes.
+ this._updateEllipseShape(width, height, zoom);
+ // Draw markers for center and radius points.
+ this._drawMarkers(
+ [
+ [cx, cy],
+ [cx + rx, cy],
+ ],
+ width,
+ height,
+ zoom
+ );
+ } else if (this.shapeType === "ellipse") {
+ const { rx, ry, cx, cy } = this.coordinates;
+ this._updateEllipseShape(width, height, zoom);
+ // Draw markers for center, horizontal radius and vertical radius points.
+ this._drawMarkers(
+ [
+ [cx, cy],
+ [cx + rx, cy],
+ [cx, cy + ry],
+ ],
+ width,
+ height,
+ zoom
+ );
+ } else if (this.shapeType === "inset") {
+ const { top, left, right, bottom } = this.coordinates;
+ const centerX = (left + (100 - right)) / 2;
+ const centerY = (top + (100 - bottom)) / 2;
+ const markerCoords = [
+ [centerX, top],
+ [100 - right, centerY],
+ [centerX, 100 - bottom],
+ [left, centerY],
+ ];
+ this._updateInsetShape(width, height, zoom);
+ // Draw markers for each of the inset's sides.
+ this._drawMarkers(markerCoords, width, height, zoom);
+ }
+ }
+
+ /**
+ * Update the SVGs for transform mode to fit the new shape.
+ * @param {Number} width the width of the element quads
+ * @param {Number} height the height of the element quads
+ * @param {Number} zoom the zoom level of the window
+ */
+ _updateTransformMode(width, height, zoom) {
+ const {
+ nw,
+ ne,
+ sw,
+ se,
+ n,
+ w,
+ s,
+ e,
+ rotatePoint,
+ center,
+ } = this.transformedBoundingBox;
+ const boundingBox = this.getElement("bounding-box");
+ const path = `M${nw.join(" ")} L${ne.join(" ")} L${se.join(" ")} L${sw.join(
+ " "
+ )} Z`;
+ boundingBox.setAttribute("d", path);
+ boundingBox.removeAttribute("hidden");
+
+ const markerPoints = [center, nw, ne, se, sw];
+ if (this.shapeType === "polygon" || this.shapeType === "ellipse") {
+ markerPoints.push(n, s, w, e);
+ }
+
+ if (this.shapeType === "polygon") {
+ this._updatePolygonShape(width, height, zoom);
+ markerPoints.push(rotatePoint);
+ const rotateLine = `M ${center.join(" ")} L ${rotatePoint.join(" ")}`;
+ this.getElement("rotate-line").setAttribute("d", rotateLine);
+ } else if (this.shapeType === "circle" || this.shapeType === "ellipse") {
+ // Shape renders for "circle()" and "ellipse()" use the same SVG nodes.
+ this._updateEllipseShape(width, height, zoom);
+ } else if (this.shapeType === "inset") {
+ this._updateInsetShape(width, height, zoom);
+ }
+
+ this._drawMarkers(markerPoints, width, height, zoom);
+ }
+
+ /**
+ * Update the SVG polygon to fit the CSS polygon.
+ * @param {Number} width the width of the element quads
+ * @param {Number} height the height of the element quads
+ * @param {Number} zoom the zoom level of the window
+ */
+ _updatePolygonShape(width, height, zoom) {
+ // Draw and show the polygon.
+ const points = this.coordinates.map(point => point.join(",")).join(" ");
+
+ const polygonEl = this.getElement("polygon");
+ polygonEl.setAttribute("points", points);
+ polygonEl.removeAttribute("hidden");
+
+ const clipPolygon = this.getElement("clip-polygon");
+ clipPolygon.setAttribute("points", points);
+ clipPolygon.removeAttribute("hidden");
+
+ const dashedPolygon = this.getElement("dashed-polygon");
+ dashedPolygon.setAttribute("points", points);
+ dashedPolygon.removeAttribute("hidden");
+ }
+
+ /**
+ * Update the SVG ellipse to fit the CSS circle or ellipse.
+ * @param {Number} width the width of the element quads
+ * @param {Number} height the height of the element quads
+ * @param {Number} zoom the zoom level of the window
+ */
+ _updateEllipseShape(width, height, zoom) {
+ const { rx, ry, cx, cy } = this.coordinates;
+ const ellipseEl = this.getElement("ellipse");
+ ellipseEl.setAttribute("rx", rx);
+ ellipseEl.setAttribute("ry", ry);
+ ellipseEl.setAttribute("cx", cx);
+ ellipseEl.setAttribute("cy", cy);
+ ellipseEl.removeAttribute("hidden");
+
+ const clipEllipse = this.getElement("clip-ellipse");
+ clipEllipse.setAttribute("rx", rx);
+ clipEllipse.setAttribute("ry", ry);
+ clipEllipse.setAttribute("cx", cx);
+ clipEllipse.setAttribute("cy", cy);
+ clipEllipse.removeAttribute("hidden");
+
+ const dashedEllipse = this.getElement("dashed-ellipse");
+ dashedEllipse.setAttribute("rx", rx);
+ dashedEllipse.setAttribute("ry", ry);
+ dashedEllipse.setAttribute("cx", cx);
+ dashedEllipse.setAttribute("cy", cy);
+ dashedEllipse.removeAttribute("hidden");
+ }
+
+ /**
+ * Update the SVG rect to fit the CSS inset.
+ * @param {Number} width the width of the element quads
+ * @param {Number} height the height of the element quads
+ * @param {Number} zoom the zoom level of the window
+ */
+ _updateInsetShape(width, height, zoom) {
+ const { top, left, right, bottom } = this.coordinates;
+ const rectEl = this.getElement("rect");
+ rectEl.setAttribute("x", left);
+ rectEl.setAttribute("y", top);
+ rectEl.setAttribute("width", 100 - left - right);
+ rectEl.setAttribute("height", 100 - top - bottom);
+ rectEl.removeAttribute("hidden");
+
+ const clipRect = this.getElement("clip-rect");
+ clipRect.setAttribute("x", left);
+ clipRect.setAttribute("y", top);
+ clipRect.setAttribute("width", 100 - left - right);
+ clipRect.setAttribute("height", 100 - top - bottom);
+ clipRect.removeAttribute("hidden");
+
+ const dashedRect = this.getElement("dashed-rect");
+ dashedRect.setAttribute("x", left);
+ dashedRect.setAttribute("y", top);
+ dashedRect.setAttribute("width", 100 - left - right);
+ dashedRect.setAttribute("height", 100 - top - bottom);
+ dashedRect.removeAttribute("hidden");
+ }
+
+ /**
+ * Draw markers for the given coordinates.
+ * @param {Array} coords an array of coordinate arrays, of form [[x, y] ...]
+ * @param {Number} width the width of the element markers are being drawn for
+ * @param {Number} height the height of the element markers are being drawn for
+ * @param {Number} zoom the zoom level of the window
+ */
+ _drawMarkers(coords, width, height, zoom) {
+ const markers = coords
+ .map(([x, y]) => {
+ return getCirclePath(BASE_MARKER_SIZE, x, y, width, height, zoom);
+ })
+ .join(" ");
+ const outline = coords
+ .map(([x, y]) => {
+ return getCirclePath(BASE_MARKER_SIZE + 2, x, y, width, height, zoom);
+ })
+ .join(" ");
+
+ this.getElement("markers").setAttribute("d", markers);
+ this.getElement("markers-outline").setAttribute("d", outline);
+ }
+
+ /**
+ * Calculate the bounding box of the shape after it is transformed according to
+ * the transformation matrix.
+ * @returns {Object} of form { nw, ne, sw, se, n, s, w, e, rotatePoint, center }.
+ * Each element in the object is an array of form [x,y], denoting the x/y
+ * coordinates of the given point.
+ */
+ calculateTransformedBoundingBox() {
+ const { minX, minY, maxX, maxY } = this.origBoundingBox;
+ const { width, height } = this.currentDimensions;
+ const toPixel = scale(width / 100, height / 100);
+ const toPercent = scale(100 / width, 100 / height);
+ const matrix = multiply(toPercent, multiply(this.transformMatrix, toPixel));
+ const centerX = (minX + maxX) / 2;
+ const centerY = (minY + maxY) / 2;
+ const nw = apply(matrix, [minX, minY]);
+ const ne = apply(matrix, [maxX, minY]);
+ const sw = apply(matrix, [minX, maxY]);
+ const se = apply(matrix, [maxX, maxY]);
+ const n = apply(matrix, [centerX, minY]);
+ const s = apply(matrix, [centerX, maxY]);
+ const w = apply(matrix, [minX, centerY]);
+ const e = apply(matrix, [maxX, centerY]);
+ const center = apply(matrix, [centerX, centerY]);
+
+ const u = [
+ ((ne[0] - nw[0]) / 100) * width,
+ ((ne[1] - nw[1]) / 100) * height,
+ ];
+ const v = [
+ ((sw[0] - nw[0]) / 100) * width,
+ ((sw[1] - nw[1]) / 100) * height,
+ ];
+ const { basis, invertedBasis } = getBasis(u, v);
+ let rotatePointMatrix = changeMatrixBase(
+ translate(0, -ROTATE_LINE_LENGTH),
+ invertedBasis,
+ basis
+ );
+ rotatePointMatrix = multiply(
+ toPercent,
+ multiply(rotatePointMatrix, multiply(this.transformMatrix, toPixel))
+ );
+ const rotatePoint = apply(rotatePointMatrix, [centerX, centerY]);
+ return { nw, ne, sw, se, n, s, w, e, rotatePoint, center };
+ }
+
+ /**
+ * Hide the highlighter, the outline and the infobar.
+ */
+ _hide() {
+ setIgnoreLayoutChanges(true);
+
+ this._hideShapes();
+ this.getElement("markers").setAttribute("d", "");
+ this.getElement("root").setAttribute("style", "");
+
+ setIgnoreLayoutChanges(
+ false,
+ this.highlighterEnv.window.document.documentElement
+ );
+ }
+
+ onPageHide({ target }) {
+ // If a page hide event is triggered for current window's highlighter, hide the
+ // highlighter.
+ if (target.defaultView === this.win) {
+ this.hide();
+ }
+ }
+
+ /**
+ * Get the rough direction of the point relative to the anchor.
+ * If the handle is roughly horizontal relative to the anchor, return "ew".
+ * If the handle is roughly vertical relative to the anchor, return "ns"
+ * If the handle is roughly above/right or below/left, return "nesw"
+ * If the handle is roughly above/left or below/right, return "nwse"
+ * @param {String} pointName the name of the point being hovered
+ * @param {String} anchor the name of the anchor point
+ * @returns {String} The rough direction of the point relative to the anchor
+ */
+ getRoughDirection(pointName, anchor) {
+ const scalePoint = pointName.split("-")[1];
+ const anchorPos = this.transformedBoundingBox[anchor];
+ const scalePos = this.transformedBoundingBox[scalePoint];
+ const { minX, minY, maxX, maxY } = this.boundingBox;
+ const width = maxX - minX;
+ const height = maxY - minY;
+ const dx = (scalePos[0] - anchorPos[0]) / width;
+ const dy = (scalePos[1] - anchorPos[1]) / height;
+ if (dx >= -0.33 && dx <= 0.33) {
+ return "ns";
+ } else if (dy >= -0.33 && dy <= 0.33) {
+ return "ew";
+ } else if ((dx > 0.33 && dy < -0.33) || (dx < -0.33 && dy > 0.33)) {
+ return "nesw";
+ }
+ return "nwse";
+ }
+
+ /**
+ * Given a unit type, get the ratio by which to multiply a pixel value in order to
+ * convert pixels to that unit.
+ *
+ * Percentage units (%) are relative to a size. This must be provided when requesting
+ * a ratio for converting from pixels to percentages.
+ *
+ * @param {String} unit
+ * One of: %, em, rem, vw, vh
+ * @param {Number} size
+ * Size to which percentage values are relative to.
+ * @return {Number}
+ */
+ getUnitToPixelRatio(unit, size) {
+ let ratio;
+ const windowHeight = this.currentNode.ownerGlobal.innerHeight;
+ const windowWidth = this.currentNode.ownerGlobal.innerWidth;
+ switch (unit) {
+ case "%":
+ ratio = 100 / size;
+ break;
+ case "em":
+ ratio = 1 / parseFloat(getComputedStyle(this.currentNode).fontSize);
+ break;
+ case "rem":
+ const root = this.currentNode.ownerDocument.documentElement;
+ ratio = 1 / parseFloat(getComputedStyle(root).fontSize);
+ break;
+ case "vw":
+ ratio = 100 / windowWidth;
+ break;
+ case "vh":
+ ratio = 100 / windowHeight;
+ break;
+ case "vmin":
+ ratio = 100 / Math.min(windowHeight, windowWidth);
+ break;
+ case "vmax":
+ ratio = 100 / Math.max(windowHeight, windowWidth);
+ break;
+ default:
+ // If unit is not recognized, peg ratio 1:1 to pixels.
+ ratio = 1;
+ }
+
+ return ratio;
+ }
+}
+
+/**
+ * Get the "raw" (i.e. non-computed) shape definition on the given node.
+ * @param {Node} node the node to analyze
+ * @param {String} property the CSS property for which a value should be retrieved.
+ * @returns {String} the value of the given CSS property on the given node.
+ */
+function getDefinedShapeProperties(node, property) {
+ let prop = "";
+ if (!node) {
+ return prop;
+ }
+
+ const cssRules = getCSSStyleRules(node);
+ for (let i = 0; i < cssRules.length; i++) {
+ const rule = cssRules[i];
+ const value = rule.style.getPropertyValue(property);
+ if (value && value !== "auto") {
+ prop = value;
+ }
+ }
+
+ if (node.style) {
+ const value = node.style.getPropertyValue(property);
+ if (value && value !== "auto") {
+ prop = value;
+ }
+ }
+
+ return prop.trim();
+}
+
+/**
+ * Split coordinate pairs separated by a space and return an array.
+ * @param {String} coords the coordinate pair, where each coord is separated by a space.
+ * @returns {Array} a 2 element array containing the coordinates.
+ */
+function splitCoords(coords) {
+ // All coordinate pairs are of the form "x y" where x and y are values or
+ // calc() expressions. calc() expressions have spaces around operators, so
+ // replace those spaces with \u00a0 (non-breaking space) so they will not be
+ // split later.
+ return coords
+ .trim()
+ .replace(/ [\+\-\*\/] /g, match => {
+ return `\u00a0${match.trim()}\u00a0`;
+ })
+ .split(" ");
+}
+exports.splitCoords = splitCoords;
+
+/**
+ * Convert a coordinate to a percentage value.
+ * @param {String} coord a single coordinate
+ * @param {Number} size the size of the element (width or height) that the percentages
+ * are relative to
+ * @returns {Number} the coordinate as a percentage value
+ */
+function coordToPercent(coord, size) {
+ if (coord.includes("%")) {
+ // Just remove the % sign, nothing else to do, we're in a viewBox that's 100%
+ // worth.
+ return parseFloat(coord.replace("%", ""));
+ } else if (coord.includes("px")) {
+ // Convert the px value to a % value.
+ const px = parseFloat(coord.replace("px", ""));
+ return (px * 100) / size;
+ }
+
+ // Unit-less value, so 0.
+ return 0;
+}
+exports.coordToPercent = coordToPercent;
+
+/**
+ * Evaluates a CSS calc() expression (only handles addition)
+ * @param {String} expression the arguments to the calc() function
+ * @param {Number} size the size of the element (width or height) that percentage values
+ * are relative to
+ * @returns {Number} the result of the expression as a percentage value
+ */
+function evalCalcExpression(expression, size) {
+ // the calc() values returned by getComputedStyle only have addition, as it
+ // computes calc() expressions as much as possible without resolving percentages,
+ // leaving only addition.
+ const values = expression.split("+").map(v => v.trim());
+
+ return values.reduce((prev, curr) => {
+ return prev + coordToPercent(curr, size);
+ }, 0);
+}
+exports.evalCalcExpression = evalCalcExpression;
+
+/**
+ * Converts a shape mode to the proper CSS property name.
+ * @param {String} mode the mode of the CSS shape
+ * @returns the equivalent CSS property name
+ */
+const shapeModeToCssPropertyName = mode => {
+ const property = mode.substring(3);
+ return property.substring(0, 1).toLowerCase() + property.substring(1);
+};
+exports.shapeModeToCssPropertyName = shapeModeToCssPropertyName;
+
+/**
+ * Get the SVG path definition for a circle with given attributes.
+ * @param {Number} size the radius of the circle in pixels
+ * @param {Number} cx the x coordinate of the centre of the circle
+ * @param {Number} cy the y coordinate of the centre of the circle
+ * @param {Number} width the width of the element the circle is being drawn for
+ * @param {Number} height the height of the element the circle is being drawn for
+ * @param {Number} zoom the zoom level of the window the circle is drawn in
+ * @returns {String} the definition of the circle in SVG path description format.
+ */
+const getCirclePath = (size, cx, cy, width, height, zoom) => {
+ // We use a viewBox of 100x100 for shape-container so it's easy to position things
+ // based on their percentage, but this makes it more difficult to create circles.
+ // Therefor, 100px is the base size of shape-container. In order to make the markers'
+ // size scale properly, we must adjust the radius based on zoom and the width/height of
+ // the element being highlighted, then calculate a radius for both x/y axes based
+ // on the aspect ratio of the element.
+ const radius = (size * (100 / Math.max(width, height))) / zoom;
+ const ratio = width / height;
+ const rx = ratio > 1 ? radius : radius / ratio;
+ const ry = ratio > 1 ? radius * ratio : radius;
+ // a circle is drawn as two arc lines, starting at the leftmost point of the circle.
+ return (
+ `M${cx - rx},${cy}a${rx},${ry} 0 1,0 ${rx * 2},0` +
+ `a${rx},${ry} 0 1,0 ${rx * -2},0`
+ );
+};
+exports.getCirclePath = getCirclePath;
+
+/**
+ * Calculates the object bounding box for a node given its stroke bounding box.
+ * @param {Number} top the y coord of the top edge of the stroke bounding box
+ * @param {Number} left the x coord of the left edge of the stroke bounding box
+ * @param {Number} width the width of the stroke bounding box
+ * @param {Number} height the height of the stroke bounding box
+ * @param {Object} node the node object
+ * @returns {Object} an object of the form { top, left, width, height }, which
+ * are the top/left/width/height of the object bounding box for the node.
+ */
+const getObjectBoundingBox = (top, left, width, height, node) => {
+ // See https://drafts.fxtf.org/css-masking-1/#stroke-bounding-box for details
+ // on this algorithm. Note that we intentionally do not check "stroke-linecap".
+ const strokeWidth = parseFloat(getComputedStyle(node).strokeWidth);
+ let delta = strokeWidth / 2;
+ const tagName = node.tagName;
+
+ if (
+ tagName !== "rect" &&
+ tagName !== "ellipse" &&
+ tagName !== "circle" &&
+ tagName !== "image"
+ ) {
+ if (getComputedStyle(node).strokeLinejoin === "miter") {
+ const miter = getComputedStyle(node).strokeMiterlimit;
+ if (miter < Math.SQRT2) {
+ delta *= Math.SQRT2;
+ } else {
+ delta *= miter;
+ }
+ } else {
+ delta *= Math.SQRT2;
+ }
+ }
+
+ return {
+ top: top + delta,
+ left: left + delta,
+ width: width - 2 * delta,
+ height: height - 2 * delta,
+ };
+};
+
+/**
+ * Get the unit (e.g. px, %, em) for the given point value.
+ * @param {any} point a point value for which a unit should be retrieved.
+ * @returns {String} the unit.
+ */
+const getUnit = point => {
+ // If the point has no unit, default to px.
+ if (isUnitless(point)) {
+ return "px";
+ }
+ const [unit] = point.match(/[^\d]+$/) || ["px"];
+ return unit;
+};
+exports.getUnit = getUnit;
+
+/**
+ * Check if the given point value has a unit.
+ * @param {any} point a point value.
+ * @returns {Boolean} whether the given value has a unit.
+ */
+const isUnitless = point => {
+ return (
+ !point ||
+ !point.match(/[^\d]+$/) ||
+ // If zero doesn't have a unit, its numeric and string forms should be equal.
+ (parseFloat(point) === 0 && parseFloat(point).toString() === point) ||
+ point.includes("(") ||
+ point === "center" ||
+ point === "closest-side" ||
+ point === "farthest-side"
+ );
+};
+
+/**
+ * Return the anchor corresponding to the given scale type.
+ * @param {String} type a scale type, of form "scale-[direction]"
+ * @returns {String} a string describing the anchor, one of the 8 cardinal directions.
+ */
+const getAnchorPoint = type => {
+ let anchor = type.split("-")[1];
+ if (anchor.includes("n")) {
+ anchor = anchor.replace("n", "s");
+ } else if (anchor.includes("s")) {
+ anchor = anchor.replace("s", "n");
+ }
+ if (anchor.includes("w")) {
+ anchor = anchor.replace("w", "e");
+ } else if (anchor.includes("e")) {
+ anchor = anchor.replace("e", "w");
+ }
+
+ if (anchor === "e" || anchor === "w") {
+ anchor = "n" + anchor;
+ } else if (anchor === "n" || anchor === "s") {
+ anchor = anchor + "w";
+ }
+
+ return anchor;
+};
+
+/**
+ * Get the decimal point precision for values depending on unit type.
+ * Only handle pixels and falsy values for now. Round them to the nearest integer value.
+ * All other unit types round to two decimal points.
+ *
+ * @param {String|undefined} unitType any one of the accepted CSS unit types for position.
+ * @return {Number} decimal precision when rounding a value
+ */
+function getDecimalPrecision(unitType) {
+ switch (unitType) {
+ case "px":
+ case "":
+ case undefined:
+ return 0;
+ default:
+ return 2;
+ }
+}
+exports.getDecimalPrecision = getDecimalPrecision;
+
+/**
+ * Round up a numeric value to a fixed number of decimals depending on CSS unit type.
+ * Used when generating output shape values when:
+ * - transforming shapes
+ * - inserting new points on a polygon.
+ *
+ * @param {Number} number
+ * Value to round up.
+ * @param {String} unitType
+ * CSS unit type, like "px", "%", "em", "vh", etc.
+ * @return {Number}
+ * Rounded value
+ */
+function round(number, unitType) {
+ return number.toFixed(getDecimalPrecision(unitType));
+}
+
+exports.ShapesHighlighter = ShapesHighlighter;
diff --git a/devtools/server/actors/highlighters/tabbing-order.js b/devtools/server/actors/highlighters/tabbing-order.js
new file mode 100644
index 0000000000..891325f669
--- /dev/null
+++ b/devtools/server/actors/highlighters/tabbing-order.js
@@ -0,0 +1,237 @@
+/* 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";
+
+const Services = require("Services");
+loader.lazyRequireGetter(
+ this,
+ "ContentDOMReference",
+ "resource://gre/modules/ContentDOMReference.jsm",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["isRemoteFrame", "isWindowIncluded"],
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "NodeTabbingOrderHighlighter",
+ "devtools/server/actors/highlighters/node-tabbing-order",
+ true
+);
+
+const DEFAULT_FOCUS_FLAGS = Services.focus.FLAG_NOSCROLL;
+
+/**
+ * The TabbingOrderHighlighter uses focus manager to traverse all focusable
+ * nodes on the page and then uses the NodeTabbingOrderHighlighter to highlight
+ * these nodes.
+ */
+class TabbingOrderHighlighter {
+ constructor(highlighterEnv) {
+ this.highlighterEnv = highlighterEnv;
+ this._highlighters = new Map();
+
+ this.onMutation = this.onMutation.bind(this);
+ this.onPageHide = this.onPageHide.bind(this);
+ this.onWillNavigate = this.onWillNavigate.bind(this);
+
+ this.highlighterEnv.on("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = highlighterEnv;
+ pageListenerTarget.addEventListener("pagehide", this.onPageHide);
+ }
+
+ /**
+ * Static getter that indicates that TabbingOrderHighlighter supports
+ * highlighting in XUL windows.
+ */
+ static get XULSupported() {
+ return true;
+ }
+
+ get win() {
+ return this.highlighterEnv.window;
+ }
+
+ get focusedElement() {
+ return Services.focus.getFocusedElementForWindow(this.win, true, {});
+ }
+
+ set focusedElement(element) {
+ Services.focus.setFocus(element, DEFAULT_FOCUS_FLAGS);
+ }
+
+ moveFocus(startElement) {
+ return Services.focus.moveFocus(
+ this.win,
+ startElement.nodeType === Node.DOCUMENT_NODE
+ ? startElement.documentElement
+ : startElement,
+ Services.focus.MOVEFOCUS_FORWARD,
+ DEFAULT_FOCUS_FLAGS
+ );
+ }
+
+ /**
+ * Show NodeTabbingOrderHighlighter on each node that belongs to the keyboard
+ * tabbing order.
+ *
+ * @param {DOMNode} startElm
+ * Starting element to calculate tabbing order from.
+ *
+ * @param {JSON} options
+ * - options.index
+ * Start index for the tabbing order. Starting index will be 0 at
+ * the start of the tabbing order highlighting; in remote frames
+ * starting index will, typically, be greater than 0 (unless there
+ * was nothing to focus in the top level content document prior to
+ * the remote frame).
+ */
+ async show(startElm, { index }) {
+ const focusableElements = [];
+ const originalFocusedElement = this.focusedElement;
+ let currentFocusedElement = this.moveFocus(startElm);
+ while (
+ currentFocusedElement &&
+ isWindowIncluded(this.win, currentFocusedElement.ownerGlobal)
+ ) {
+ focusableElements.push(currentFocusedElement);
+ currentFocusedElement = this.moveFocus(currentFocusedElement);
+ }
+
+ // Allow to flush pending notifications to ensure the PresShell and frames
+ // are updated.
+ await new Promise(resolve => Services.tm.dispatchToMainThread(resolve));
+ let endElm = this.focusedElement;
+ if (
+ currentFocusedElement &&
+ !isWindowIncluded(this.win, currentFocusedElement.ownerGlobal)
+ ) {
+ endElm = null;
+ }
+
+ if (
+ !endElm &&
+ focusableElements.length > 0 &&
+ isRemoteFrame(focusableElements[focusableElements.length - 1])
+ ) {
+ endElm = focusableElements[focusableElements.length - 1];
+ }
+
+ if (originalFocusedElement && originalFocusedElement !== endElm) {
+ this.focusedElement = originalFocusedElement;
+ }
+
+ const highlighters = [];
+ for (let i = 0; i < focusableElements.length; i++) {
+ highlighters.push(
+ this._accumulateHighlighter(focusableElements[i], index++)
+ );
+ }
+ await Promise.all(highlighters);
+
+ this._trackMutations();
+
+ return {
+ contentDOMReference: endElm && ContentDOMReference.get(endElm),
+ index,
+ };
+ }
+
+ async _accumulateHighlighter(node, index) {
+ const highlighter = new NodeTabbingOrderHighlighter(this.highlighterEnv);
+ await highlighter.isReady;
+
+ highlighter.show(node, { index: index + 1 });
+ this._highlighters.set(node, highlighter);
+ }
+
+ hide() {
+ this._untrackMutations();
+ for (const highlighter of this._highlighters.values()) {
+ highlighter.destroy();
+ }
+
+ this._highlighters.clear();
+ }
+
+ /**
+ * Track mutations in the top level document subtree so that the appropriate
+ * NodeTabbingOrderHighlighter infobar's could be updated to reflect the
+ * attribute mutations on relevant nodes.
+ */
+ _trackMutations() {
+ const { win } = this;
+ this.currentMutationObserver = new win.MutationObserver(this.onMutation);
+ this.currentMutationObserver.observe(win.document.documentElement, {
+ subtree: true,
+ attributes: true,
+ });
+ }
+
+ _untrackMutations() {
+ if (!this.currentMutationObserver) {
+ return;
+ }
+
+ this.currentMutationObserver.disconnect();
+ this.currentMutationObserver = null;
+ }
+
+ onMutation(mutationList) {
+ for (const { target } of mutationList) {
+ const highlighter = this._highlighters.get(target);
+ if (highlighter) {
+ highlighter.update();
+ }
+ }
+ }
+
+ /**
+ * Update NodeTabbingOrderHighlighter focus styling for a node that,
+ * potentially, belongs to the tabbing order.
+ * @param {Object} options
+ * Options specifying the node and its focused state.
+ */
+ updateFocus({ node, focused }) {
+ const highlighter = this._highlighters.get(node);
+ if (!highlighter) {
+ return;
+ }
+
+ highlighter.updateFocus(focused);
+ }
+
+ destroy() {
+ this.highlighterEnv.off("will-navigate", this.onWillNavigate);
+
+ const { pageListenerTarget } = this.highlighterEnv;
+ if (pageListenerTarget) {
+ pageListenerTarget.removeEventListener("pagehide", this.onPageHide);
+ }
+
+ this.hide();
+ this.highlighterEnv = null;
+ }
+
+ onPageHide({ target }) {
+ // If a pagehide event is triggered for current window's highlighter, hide
+ // the highlighter.
+ if (target.defaultView === this.win) {
+ this.hide();
+ }
+ }
+
+ onWillNavigate({ isTopLevel }) {
+ if (isTopLevel) {
+ this.hide();
+ }
+ }
+}
+
+exports.TabbingOrderHighlighter = TabbingOrderHighlighter;
diff --git a/devtools/server/actors/highlighters/utils/accessibility.js b/devtools/server/actors/highlighters/utils/accessibility.js
new file mode 100644
index 0000000000..18e4549a5f
--- /dev/null
+++ b/devtools/server/actors/highlighters/utils/accessibility.js
@@ -0,0 +1,769 @@
+/* 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";
+
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const { getCurrentZoom } = require("devtools/shared/layout/utils");
+const {
+ moveInfobar,
+} = require("devtools/server/actors/highlighters/utils/markup");
+const { truncateString } = require("devtools/shared/inspector/utils");
+
+const STRINGS_URI = "devtools/shared/locales/accessibility.properties";
+loader.lazyRequireGetter(
+ this,
+ "LocalizationHelper",
+ "devtools/shared/l10n",
+ true
+);
+DevToolsUtils.defineLazyGetter(
+ this,
+ "L10N",
+ () => new LocalizationHelper(STRINGS_URI)
+);
+
+const {
+ accessibility: {
+ AUDIT_TYPE,
+ ISSUE_TYPE: {
+ [AUDIT_TYPE.KEYBOARD]: {
+ FOCUSABLE_NO_SEMANTICS,
+ FOCUSABLE_POSITIVE_TABINDEX,
+ INTERACTIVE_NO_ACTION,
+ INTERACTIVE_NOT_FOCUSABLE,
+ MOUSE_INTERACTIVE_ONLY,
+ NO_FOCUS_VISIBLE,
+ },
+ [AUDIT_TYPE.TEXT_LABEL]: {
+ AREA_NO_NAME_FROM_ALT,
+ DIALOG_NO_NAME,
+ DOCUMENT_NO_TITLE,
+ EMBED_NO_NAME,
+ FIGURE_NO_NAME,
+ FORM_FIELDSET_NO_NAME,
+ FORM_FIELDSET_NO_NAME_FROM_LEGEND,
+ FORM_NO_NAME,
+ FORM_NO_VISIBLE_NAME,
+ FORM_OPTGROUP_NO_NAME_FROM_LABEL,
+ FRAME_NO_NAME,
+ HEADING_NO_CONTENT,
+ HEADING_NO_NAME,
+ IFRAME_NO_NAME_FROM_TITLE,
+ IMAGE_NO_NAME,
+ INTERACTIVE_NO_NAME,
+ MATHML_GLYPH_NO_NAME,
+ TOOLBAR_NO_NAME,
+ },
+ },
+ SCORES,
+ },
+} = require("devtools/shared/constants");
+
+// Max string length for truncating accessible name values.
+const MAX_STRING_LENGTH = 50;
+
+/**
+ * The AccessibleInfobar is a class responsible for creating the markup for the
+ * accessible highlighter. It is also reponsible for updating content within the
+ * infobar such as role and name values.
+ */
+class Infobar {
+ constructor(highlighter) {
+ this.highlighter = highlighter;
+ this.audit = new Audit(this);
+ }
+
+ get markup() {
+ return this.highlighter.markup;
+ }
+
+ get document() {
+ return this.highlighter.win.document;
+ }
+
+ get bounds() {
+ return this.highlighter._bounds;
+ }
+
+ get options() {
+ return this.highlighter.options;
+ }
+
+ get prefix() {
+ return this.highlighter.ID_CLASS_PREFIX;
+ }
+
+ get win() {
+ return this.highlighter.win;
+ }
+
+ /**
+ * Move the Infobar to the right place in the highlighter.
+ *
+ * @param {Element} container
+ * Container of infobar.
+ */
+ _moveInfobar(container) {
+ // Position the infobar using accessible's bounds
+ const { left: x, top: y, bottom, width } = this.bounds;
+ const infobarBounds = { x, y, bottom, width };
+
+ moveInfobar(container, infobarBounds, this.win);
+ }
+
+ /**
+ * Build markup for infobar.
+ *
+ * @param {Element} root
+ * Root element to build infobar with.
+ */
+ buildMarkup(root) {
+ const container = this.markup.createNode({
+ parent: root,
+ attributes: {
+ class: "infobar-container",
+ id: "infobar-container",
+ "aria-hidden": "true",
+ hidden: "true",
+ },
+ prefix: this.prefix,
+ });
+
+ const infobar = this.markup.createNode({
+ parent: container,
+ attributes: {
+ class: "infobar",
+ id: "infobar",
+ },
+ prefix: this.prefix,
+ });
+
+ const infobarText = this.markup.createNode({
+ parent: infobar,
+ attributes: {
+ class: "infobar-text",
+ id: "infobar-text",
+ },
+ prefix: this.prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: infobarText,
+ attributes: {
+ class: "infobar-role",
+ id: "infobar-role",
+ },
+ prefix: this.prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: infobarText,
+ attributes: {
+ class: "infobar-name",
+ id: "infobar-name",
+ },
+ prefix: this.prefix,
+ });
+
+ this.audit.buildMarkup(infobarText);
+ }
+
+ /**
+ * Destroy the Infobar's highlighter.
+ */
+ destroy() {
+ this.highlighter = null;
+ this.audit.destroy();
+ this.audit = null;
+ }
+
+ /**
+ * Gets the element with the specified ID.
+ *
+ * @param {String} id
+ * Element ID.
+ * @return {Element} The element with specified ID.
+ */
+ getElement(id) {
+ return this.highlighter.getElement(id);
+ }
+
+ /**
+ * Gets the text content of element.
+ *
+ * @param {String} id
+ * Element ID to retrieve text content from.
+ * @return {String} The text content of the element.
+ */
+ getTextContent(id) {
+ const anonymousContent = this.markup.content;
+ return anonymousContent.getTextContentForElement(`${this.prefix}${id}`);
+ }
+
+ /**
+ * Hide the accessible infobar.
+ */
+ hide() {
+ const container = this.getElement("infobar-container");
+ container.setAttribute("hidden", "true");
+ }
+
+ /**
+ * Show the accessible infobar highlighter.
+ */
+ show() {
+ const container = this.getElement("infobar-container");
+
+ // Remove accessible's infobar "hidden" attribute. We do this first to get the
+ // computed styles of the infobar container.
+ container.removeAttribute("hidden");
+
+ // Update the infobar's position and content.
+ this.update(container);
+ }
+
+ /**
+ * Update content of the infobar.
+ */
+ update(container) {
+ const { audit, name, role } = this.options;
+
+ this.updateRole(role, this.getElement("infobar-role"));
+ this.updateName(name, this.getElement("infobar-name"));
+ this.audit.update(audit);
+
+ // Position the infobar.
+ this._moveInfobar(container);
+ }
+
+ /**
+ * Sets the text content of the specified element.
+ *
+ * @param {Element} el
+ * Element to set text content on.
+ * @param {String} text
+ * Text for content.
+ */
+ setTextContent(el, text) {
+ el.setTextContent(text);
+ }
+
+ /**
+ * Show the accessible's name message.
+ *
+ * @param {String} name
+ * Accessible's name value.
+ * @param {Element} el
+ * Element to set text content on.
+ */
+ updateName(name, el) {
+ const nameText = name ? `"${truncateString(name, MAX_STRING_LENGTH)}"` : "";
+ this.setTextContent(el, nameText);
+ }
+
+ /**
+ * Show the accessible's role.
+ *
+ * @param {String} role
+ * Accessible's role value.
+ * @param {Element} el
+ * Element to set text content on.
+ */
+ updateRole(role, el) {
+ this.setTextContent(el, role);
+ }
+}
+
+/**
+ * Audit component used within the accessible highlighter infobar. This component is
+ * responsible for rendering and updating its containing AuditReport components that
+ * display various audit information such as contrast ratio score.
+ */
+class Audit {
+ constructor(infobar) {
+ this.infobar = infobar;
+
+ // A list of audit reports to be shown on the fly when highlighting an accessible
+ // object.
+ this.reports = {
+ [AUDIT_TYPE.CONTRAST]: new ContrastRatio(this),
+ [AUDIT_TYPE.KEYBOARD]: new Keyboard(this),
+ [AUDIT_TYPE.TEXT_LABEL]: new TextLabel(this),
+ };
+ }
+
+ get prefix() {
+ return this.infobar.prefix;
+ }
+
+ get markup() {
+ return this.infobar.markup;
+ }
+
+ buildMarkup(root) {
+ const audit = this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "infobar-audit",
+ id: "infobar-audit",
+ },
+ prefix: this.prefix,
+ });
+
+ Object.values(this.reports).forEach(report => report.buildMarkup(audit));
+ }
+
+ update(audit = {}) {
+ const el = this.getElement("infobar-audit");
+ el.setAttribute("hidden", true);
+
+ let updated = false;
+ Object.values(this.reports).forEach(report => {
+ if (report.update(audit)) {
+ updated = true;
+ }
+ });
+
+ if (updated) {
+ el.removeAttribute("hidden");
+ }
+ }
+
+ getElement(id) {
+ return this.infobar.getElement(id);
+ }
+
+ setTextContent(el, text) {
+ return this.infobar.setTextContent(el, text);
+ }
+
+ destroy() {
+ this.infobar = null;
+ Object.values(this.reports).forEach(report => report.destroy());
+ this.reports = null;
+ }
+}
+
+/**
+ * A common interface between audit report components used to render accessibility audit
+ * information for the currently highlighted accessible object.
+ */
+class AuditReport {
+ constructor(audit) {
+ this.audit = audit;
+ }
+
+ get prefix() {
+ return this.audit.prefix;
+ }
+
+ get markup() {
+ return this.audit.markup;
+ }
+
+ getElement(id) {
+ return this.audit.getElement(id);
+ }
+
+ setTextContent(el, text) {
+ return this.audit.setTextContent(el, text);
+ }
+
+ destroy() {
+ this.audit = null;
+ }
+}
+
+/**
+ * Contrast ratio audit report that is used to display contrast ratio score as part of the
+ * inforbar,
+ */
+class ContrastRatio extends AuditReport {
+ buildMarkup(root) {
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "contrast-ratio-label",
+ id: "contrast-ratio-label",
+ },
+ prefix: this.prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "contrast-ratio-error",
+ id: "contrast-ratio-error",
+ },
+ prefix: this.prefix,
+ text: L10N.getStr("accessibility.contrast.ratio.error"),
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "contrast-ratio",
+ id: "contrast-ratio-min",
+ },
+ prefix: this.prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "contrast-ratio-separator",
+ id: "contrast-ratio-separator",
+ },
+ prefix: this.prefix,
+ });
+
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "contrast-ratio",
+ id: "contrast-ratio-max",
+ },
+ prefix: this.prefix,
+ });
+ }
+
+ _fillAndStyleContrastValue(el, { value, className, color, backgroundColor }) {
+ value = value.toFixed(2);
+ this.setTextContent(el, value);
+ el.classList.add(className);
+ el.setAttribute(
+ "style",
+ `--accessibility-highlighter-contrast-ratio-color: rgba(${color});` +
+ `--accessibility-highlighter-contrast-ratio-bg: rgba(${backgroundColor});`
+ );
+ el.removeAttribute("hidden");
+ }
+
+ /**
+ * Update contrast ratio score infobar markup.
+ * @param {Object}
+ * Audit report for a given highlighted accessible.
+ * @return {Boolean}
+ * True if the contrast ratio markup was updated correctly and infobar audit
+ * block should be visible.
+ */
+ update(audit) {
+ const els = {};
+ for (const key of ["label", "min", "max", "error", "separator"]) {
+ const el = (els[key] = this.getElement(`contrast-ratio-${key}`));
+ if (["min", "max"].includes(key)) {
+ Object.values(SCORES).forEach(className =>
+ el.classList.remove(className)
+ );
+ this.setTextContent(el, "");
+ }
+
+ el.setAttribute("hidden", true);
+ el.removeAttribute("style");
+ }
+
+ if (!audit) {
+ return false;
+ }
+
+ const contrastRatio = audit[AUDIT_TYPE.CONTRAST];
+ if (!contrastRatio) {
+ return false;
+ }
+
+ const { isLargeText, error } = contrastRatio;
+ this.setTextContent(
+ els.label,
+ L10N.getStr(
+ `accessibility.contrast.ratio.label${isLargeText ? ".large" : ""}`
+ )
+ );
+ els.label.removeAttribute("hidden");
+ if (error) {
+ els.error.removeAttribute("hidden");
+ return true;
+ }
+
+ if (contrastRatio.value) {
+ const { value, color, score, backgroundColor } = contrastRatio;
+ this._fillAndStyleContrastValue(els.min, {
+ value,
+ className: score,
+ color,
+ backgroundColor,
+ });
+ return true;
+ }
+
+ const {
+ min,
+ max,
+ color,
+ backgroundColorMin,
+ backgroundColorMax,
+ scoreMin,
+ scoreMax,
+ } = contrastRatio;
+ this._fillAndStyleContrastValue(els.min, {
+ value: min,
+ className: scoreMin,
+ color,
+ backgroundColor: backgroundColorMin,
+ });
+ els.separator.removeAttribute("hidden");
+ this._fillAndStyleContrastValue(els.max, {
+ value: max,
+ className: scoreMax,
+ color,
+ backgroundColor: backgroundColorMax,
+ });
+
+ return true;
+ }
+}
+
+/**
+ * Keyboard audit report that is used to display a problem with keyboard
+ * accessibility as part of the inforbar.
+ */
+class Keyboard extends AuditReport {
+ /**
+ * A map from keyboard issues to annotation component properties.
+ */
+ static get ISSUE_TO_INFOBAR_LABEL_MAP() {
+ return {
+ [FOCUSABLE_NO_SEMANTICS]: "accessibility.keyboard.issue.semantics",
+ [FOCUSABLE_POSITIVE_TABINDEX]: "accessibility.keyboard.issue.tabindex",
+ [INTERACTIVE_NO_ACTION]: "accessibility.keyboard.issue.action",
+ [INTERACTIVE_NOT_FOCUSABLE]: "accessibility.keyboard.issue.focusable",
+ [MOUSE_INTERACTIVE_ONLY]: "accessibility.keyboard.issue.mouse.only",
+ [NO_FOCUS_VISIBLE]: "accessibility.keyboard.issue.focus.visible",
+ };
+ }
+
+ buildMarkup(root) {
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "audit",
+ id: "keyboard",
+ },
+ prefix: this.prefix,
+ });
+ }
+
+ /**
+ * Update keyboard audit infobar markup.
+ * @param {Object}
+ * Audit report for a given highlighted accessible.
+ * @return {Boolean}
+ * True if the keyboard markup was updated correctly and infobar audit
+ * block should be visible.
+ */
+ update(audit) {
+ const el = this.getElement("keyboard");
+ el.setAttribute("hidden", true);
+ Object.values(SCORES).forEach(className => el.classList.remove(className));
+
+ if (!audit) {
+ return false;
+ }
+
+ const keyboardAudit = audit[AUDIT_TYPE.KEYBOARD];
+ if (!keyboardAudit) {
+ return false;
+ }
+
+ const { issue, score } = keyboardAudit;
+ this.setTextContent(
+ el,
+ L10N.getStr(Keyboard.ISSUE_TO_INFOBAR_LABEL_MAP[issue])
+ );
+ el.classList.add(score);
+ el.removeAttribute("hidden");
+
+ return true;
+ }
+}
+
+/**
+ * Text label audit report that is used to display a problem with text alternatives
+ * as part of the inforbar.
+ */
+class TextLabel extends AuditReport {
+ /**
+ * A map from text label issues to annotation component properties.
+ */
+ static get ISSUE_TO_INFOBAR_LABEL_MAP() {
+ return {
+ [AREA_NO_NAME_FROM_ALT]: "accessibility.text.label.issue.area",
+ [DIALOG_NO_NAME]: "accessibility.text.label.issue.dialog",
+ [DOCUMENT_NO_TITLE]: "accessibility.text.label.issue.document.title",
+ [EMBED_NO_NAME]: "accessibility.text.label.issue.embed",
+ [FIGURE_NO_NAME]: "accessibility.text.label.issue.figure",
+ [FORM_FIELDSET_NO_NAME]: "accessibility.text.label.issue.fieldset",
+ [FORM_FIELDSET_NO_NAME_FROM_LEGEND]:
+ "accessibility.text.label.issue.fieldset.legend2",
+ [FORM_NO_NAME]: "accessibility.text.label.issue.form",
+ [FORM_NO_VISIBLE_NAME]: "accessibility.text.label.issue.form.visible",
+ [FORM_OPTGROUP_NO_NAME_FROM_LABEL]:
+ "accessibility.text.label.issue.optgroup.label2",
+ [FRAME_NO_NAME]: "accessibility.text.label.issue.frame",
+ [HEADING_NO_CONTENT]: "accessibility.text.label.issue.heading.content",
+ [HEADING_NO_NAME]: "accessibility.text.label.issue.heading",
+ [IFRAME_NO_NAME_FROM_TITLE]: "accessibility.text.label.issue.iframe",
+ [IMAGE_NO_NAME]: "accessibility.text.label.issue.image",
+ [INTERACTIVE_NO_NAME]: "accessibility.text.label.issue.interactive",
+ [MATHML_GLYPH_NO_NAME]: "accessibility.text.label.issue.glyph",
+ [TOOLBAR_NO_NAME]: "accessibility.text.label.issue.toolbar",
+ };
+ }
+
+ buildMarkup(root) {
+ this.markup.createNode({
+ nodeType: "span",
+ parent: root,
+ attributes: {
+ class: "audit",
+ id: "text-label",
+ },
+ prefix: this.prefix,
+ });
+ }
+
+ /**
+ * Update text label audit infobar markup.
+ * @param {Object}
+ * Audit report for a given highlighted accessible.
+ * @return {Boolean}
+ * True if the text label markup was updated correctly and infobar
+ * audit block should be visible.
+ */
+ update(audit) {
+ const el = this.getElement("text-label");
+ el.setAttribute("hidden", true);
+ Object.values(SCORES).forEach(className => el.classList.remove(className));
+
+ if (!audit) {
+ return false;
+ }
+
+ const textLabelAudit = audit[AUDIT_TYPE.TEXT_LABEL];
+ if (!textLabelAudit) {
+ return false;
+ }
+
+ const { issue, score } = textLabelAudit;
+ this.setTextContent(
+ el,
+ L10N.getStr(TextLabel.ISSUE_TO_INFOBAR_LABEL_MAP[issue])
+ );
+ el.classList.add(score);
+ el.removeAttribute("hidden");
+
+ return true;
+ }
+}
+
+/**
+ * A helper function that calculate accessible object bounds and positioning to
+ * be used for highlighting.
+ *
+ * @param {Object} win
+ * window that contains accessible object.
+ * @param {Object} options
+ * Object used for passing options:
+ * - {Number} x
+ * x coordinate of the top left corner of the accessible object
+ * - {Number} y
+ * y coordinate of the top left corner of the accessible object
+ * - {Number} w
+ * width of the the accessible object
+ * - {Number} h
+ * height of the the accessible object
+ * @return {Object|null} Returns, if available, positioning and bounds information for
+ * the accessible object.
+ */
+function getBounds(win, { x, y, w, h }) {
+ const { mozInnerScreenX, mozInnerScreenY, scrollX, scrollY } = win;
+ const zoom = getCurrentZoom(win);
+ let left = x;
+ let right = x + w;
+ let top = y;
+ let bottom = y + h;
+
+ left -= mozInnerScreenX - scrollX;
+ right -= mozInnerScreenX - scrollX;
+ top -= mozInnerScreenY - scrollY;
+ bottom -= mozInnerScreenY - scrollY;
+
+ left *= zoom;
+ right *= zoom;
+ top *= zoom;
+ bottom *= zoom;
+
+ const width = right - left;
+ const height = bottom - top;
+
+ return { left, right, top, bottom, width, height };
+}
+
+/**
+ * A helper function that calculate accessible object bounds and positioning to
+ * be used for highlighting in browser toolbox.
+ *
+ * @param {Object} win
+ * window that contains accessible object.
+ * @param {Object} options
+ * Object used for passing options:
+ * - {Number} x
+ * x coordinate of the top left corner of the accessible object
+ * - {Number} y
+ * y coordinate of the top left corner of the accessible object
+ * - {Number} w
+ * width of the the accessible object
+ * - {Number} h
+ * height of the the accessible object
+ * - {Number} zoom
+ * zoom level of the accessible object's parent window
+ * @return {Object|null} Returns, if available, positioning and bounds information for
+ * the accessible object.
+ */
+function getBoundsXUL(win, { x, y, w, h, zoom }) {
+ const { mozInnerScreenX, mozInnerScreenY } = win;
+ let left = x;
+ let right = x + w;
+ let top = y;
+ let bottom = y + h;
+
+ left *= zoom;
+ right *= zoom;
+ top *= zoom;
+ bottom *= zoom;
+
+ left -= mozInnerScreenX;
+ right -= mozInnerScreenX;
+ top -= mozInnerScreenY;
+ bottom -= mozInnerScreenY;
+
+ const width = right - left;
+ const height = bottom - top;
+
+ return { left, right, top, bottom, width, height };
+}
+
+exports.MAX_STRING_LENGTH = MAX_STRING_LENGTH;
+exports.getBounds = getBounds;
+exports.getBoundsXUL = getBoundsXUL;
+exports.Infobar = Infobar;
diff --git a/devtools/server/actors/highlighters/utils/canvas.js b/devtools/server/actors/highlighters/utils/canvas.js
new file mode 100644
index 0000000000..06f143d04d
--- /dev/null
+++ b/devtools/server/actors/highlighters/utils/canvas.js
@@ -0,0 +1,596 @@
+/* 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";
+
+const {
+ apply,
+ getNodeTransformationMatrix,
+ getWritingModeMatrix,
+ identity,
+ isIdentity,
+ multiply,
+ scale,
+ translate,
+} = require("devtools/shared/layout/dom-matrix-2d");
+const {
+ getCurrentZoom,
+ getViewportDimensions,
+} = require("devtools/shared/layout/utils");
+const {
+ getComputedStyle,
+} = require("devtools/server/actors/highlighters/utils/markup");
+
+// A set of utility functions for highlighters that render their content to a <canvas>
+// element.
+
+// We create a <canvas> element that has always 4096x4096 physical pixels, to displays
+// our grid's overlay.
+// Then, we move the element around when needed, to give the perception that it always
+// covers the screen (See bug 1345434).
+//
+// This canvas size value is the safest we can use because most GPUs can handle it.
+// It's also far from the maximum canvas memory allocation limit (4096x4096x4 is
+// 67.108.864 bytes, where the limit is 500.000.000 bytes, see
+// gfx_max_alloc_size in modules/libpref/init/StaticPrefList.yaml.
+//
+// Note:
+// Once bug 1232491 lands, we could try to refactor this code to use the values from
+// the displayport API instead.
+//
+// Using a fixed value should also solve bug 1348293.
+const CANVAS_SIZE = 4096;
+
+// The default color used for the canvas' font, fill and stroke colors.
+const DEFAULT_COLOR = "#9400FF";
+
+/**
+ * Draws a rect to the context given and applies a transformation matrix if passed.
+ * The coordinates are the start and end points of the rectangle's diagonal.
+ *
+ * @param {CanvasRenderingContext2D} ctx
+ * The 2D canvas context.
+ * @param {Number} x1
+ * The x-axis coordinate of the rectangle's diagonal start point.
+ * @param {Number} y1
+ * The y-axis coordinate of the rectangle's diagonal start point.
+ * @param {Number} x2
+ * The x-axis coordinate of the rectangle's diagonal end point.
+ * @param {Number} y2
+ * The y-axis coordinate of the rectangle's diagonal end point.
+ * @param {Array} [matrix=identity()]
+ * The transformation matrix to apply.
+ */
+function clearRect(ctx, x1, y1, x2, y2, matrix = identity()) {
+ const p = getPointsFromDiagonal(x1, y1, x2, y2, matrix);
+
+ // We are creating a clipping path and want it removed after we clear it's
+ // contents so we need to save the context.
+ ctx.save();
+
+ // Create a path to be cleared.
+ ctx.beginPath();
+ ctx.moveTo(Math.round(p[0].x), Math.round(p[0].y));
+ ctx.lineTo(Math.round(p[1].x), Math.round(p[1].y));
+ ctx.lineTo(Math.round(p[2].x), Math.round(p[2].y));
+ ctx.lineTo(Math.round(p[3].x), Math.round(p[3].y));
+ ctx.closePath();
+
+ // Restrict future drawing to the inside of the path.
+ ctx.clip();
+
+ // Clear any transforms applied to the canvas so that clearRect() really does
+ // clear everything.
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+
+ // Clear the contents of our clipped path by attempting to clear the canvas.
+ ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
+
+ // Restore the context to the state it was before changing transforms and
+ // adding clipping paths.
+ ctx.restore();
+}
+
+/**
+ * Draws an arrow-bubble rectangle in the provided canvas context.
+ *
+ * @param {CanvasRenderingContext2D} ctx
+ * The 2D canvas context.
+ * @param {Number} x
+ * The x-axis origin of the rectangle.
+ * @param {Number} y
+ * The y-axis origin of the rectangle.
+ * @param {Number} width
+ * The width of the rectangle.
+ * @param {Number} height
+ * The height of the rectangle.
+ * @param {Number} radius
+ * The radius of the rounding.
+ * @param {Number} margin
+ * The distance of the origin point from the pointer.
+ * @param {Number} arrowSize
+ * The size of the arrow.
+ * @param {String} alignment
+ * The alignment of the rectangle in relation to its position to the grid.
+ */
+function drawBubbleRect(
+ ctx,
+ x,
+ y,
+ width,
+ height,
+ radius,
+ margin,
+ arrowSize,
+ alignment
+) {
+ let angle = 0;
+
+ if (alignment === "bottom") {
+ angle = 180;
+ } else if (alignment === "right") {
+ angle = 90;
+ [width, height] = [height, width];
+ } else if (alignment === "left") {
+ [width, height] = [height, width];
+ angle = 270;
+ }
+
+ const originX = x;
+ const originY = y;
+
+ ctx.save();
+ ctx.translate(originX, originY);
+ ctx.rotate(angle * (Math.PI / 180));
+ ctx.translate(-originX, -originY);
+ ctx.translate(-width / 2, -height - arrowSize - margin);
+
+ // The contour of the bubble is drawn with a path. The canvas context will have taken
+ // care of transforming the coordinates before calling the function, so we just always
+ // draw with the arrow pointing down. The top edge has rounded corners too.
+ ctx.beginPath();
+ // Start at the top/left corner (below the rounded corner).
+ ctx.moveTo(x, y + radius);
+ // Go down.
+ ctx.lineTo(x, y + height);
+ // Go down and the right, to draw the first half of the arrow tip.
+ ctx.lineTo(x + width / 2, y + height + arrowSize);
+ // Go back up and to the right, to draw the second half of the arrow tip.
+ ctx.lineTo(x + width, y + height);
+ // Go up to just below the top/right rounded corner.
+ ctx.lineTo(x + width, y + radius);
+ // Draw the top/right rounded corner.
+ ctx.arcTo(x + width, y, x + width - radius, y, radius);
+ // Go to the left.
+ ctx.lineTo(x + radius, y);
+ // Draw the top/left rounded corner.
+ ctx.arcTo(x, y, x, y + radius, radius);
+
+ ctx.stroke();
+ ctx.fill();
+
+ ctx.restore();
+}
+
+/**
+ * Draws a line to the context given and applies a transformation matrix if passed.
+ *
+ * @param {CanvasRenderingContext2D} ctx
+ * The 2D canvas context.
+ * @param {Number} x1
+ * The x-axis of the coordinate for the begin of the line.
+ * @param {Number} y1
+ * The y-axis of the coordinate for the begin of the line.
+ * @param {Number} x2
+ * The x-axis of the coordinate for the end of the line.
+ * @param {Number} y2
+ * The y-axis of the coordinate for the end of the line.
+ * @param {Object} [options]
+ * The options object.
+ * @param {Array} [options.matrix=identity()]
+ * The transformation matrix to apply.
+ * @param {Array} [options.extendToBoundaries]
+ * If set, the line will be extended to reach the boundaries specified.
+ */
+function drawLine(ctx, x1, y1, x2, y2, options) {
+ const matrix = options.matrix || identity();
+
+ const p1 = apply(matrix, [x1, y1]);
+ const p2 = apply(matrix, [x2, y2]);
+
+ x1 = p1[0];
+ y1 = p1[1];
+ x2 = p2[0];
+ y2 = p2[1];
+
+ if (options.extendToBoundaries) {
+ if (p1[1] === p2[1]) {
+ x1 = options.extendToBoundaries[0];
+ x2 = options.extendToBoundaries[2];
+ } else {
+ y1 = options.extendToBoundaries[1];
+ x1 = ((p2[0] - p1[0]) * (y1 - p1[1])) / (p2[1] - p1[1]) + p1[0];
+ y2 = options.extendToBoundaries[3];
+ x2 = ((p2[0] - p1[0]) * (y2 - p1[1])) / (p2[1] - p1[1]) + p1[0];
+ }
+ }
+
+ ctx.beginPath();
+ ctx.moveTo(Math.round(x1), Math.round(y1));
+ ctx.lineTo(Math.round(x2), Math.round(y2));
+}
+
+/**
+ * Draws a rect to the context given and applies a transformation matrix if passed.
+ * The coordinates are the start and end points of the rectangle's diagonal.
+ *
+ * @param {CanvasRenderingContext2D} ctx
+ * The 2D canvas context.
+ * @param {Number} x1
+ * The x-axis coordinate of the rectangle's diagonal start point.
+ * @param {Number} y1
+ * The y-axis coordinate of the rectangle's diagonal start point.
+ * @param {Number} x2
+ * The x-axis coordinate of the rectangle's diagonal end point.
+ * @param {Number} y2
+ * The y-axis coordinate of the rectangle's diagonal end point.
+ * @param {Array} [matrix=identity()]
+ * The transformation matrix to apply.
+ */
+function drawRect(ctx, x1, y1, x2, y2, matrix = identity()) {
+ const p = getPointsFromDiagonal(x1, y1, x2, y2, matrix);
+
+ ctx.beginPath();
+ ctx.moveTo(Math.round(p[0].x), Math.round(p[0].y));
+ ctx.lineTo(Math.round(p[1].x), Math.round(p[1].y));
+ ctx.lineTo(Math.round(p[2].x), Math.round(p[2].y));
+ ctx.lineTo(Math.round(p[3].x), Math.round(p[3].y));
+ ctx.closePath();
+}
+
+/**
+ * Draws a rounded rectangle in the provided canvas context.
+ *
+ * @param {CanvasRenderingContext2D} ctx
+ * The 2D canvas context.
+ * @param {Number} x
+ * The x-axis origin of the rectangle.
+ * @param {Number} y
+ * The y-axis origin of the rectangle.
+ * @param {Number} width
+ * The width of the rectangle.
+ * @param {Number} height
+ * The height of the rectangle.
+ * @param {Number} radius
+ * The radius of the rounding.
+ */
+function drawRoundedRect(ctx, x, y, width, height, radius) {
+ ctx.beginPath();
+ ctx.moveTo(x, y + radius);
+ ctx.lineTo(x, y + height - radius);
+ ctx.arcTo(x, y + height, x + radius, y + height, radius);
+ ctx.lineTo(x + width - radius, y + height);
+ ctx.arcTo(x + width, y + height, x + width, y + height - radius, radius);
+ ctx.lineTo(x + width, y + radius);
+ ctx.arcTo(x + width, y, x + width - radius, y, radius);
+ ctx.lineTo(x + radius, y);
+ ctx.arcTo(x, y, x, y + radius, radius);
+ ctx.stroke();
+ ctx.fill();
+}
+
+/**
+ * Given an array of four points and returns a DOMRect-like object representing the
+ * boundaries defined by the four points.
+ *
+ * @param {Array} points
+ * An array with 4 pointer objects {x, y} representing the box quads.
+ * @return {Object} DOMRect-like object of the 4 points.
+ */
+function getBoundsFromPoints(points) {
+ const bounds = {};
+
+ bounds.left = Math.min(points[0].x, points[1].x, points[2].x, points[3].x);
+ bounds.right = Math.max(points[0].x, points[1].x, points[2].x, points[3].x);
+ bounds.top = Math.min(points[0].y, points[1].y, points[2].y, points[3].y);
+ bounds.bottom = Math.max(points[0].y, points[1].y, points[2].y, points[3].y);
+
+ bounds.x = bounds.left;
+ bounds.y = bounds.top;
+ bounds.width = bounds.right - bounds.left;
+ bounds.height = bounds.bottom - bounds.top;
+
+ return bounds;
+}
+
+/**
+ * Returns the current matrices for both canvas drawing and SVG taking into account the
+ * following transformations, in this order:
+ * 1. The scale given by the display pixel ratio.
+ * 2. The translation to the top left corner of the element.
+ * 3. The scale given by the current zoom.
+ * 4. The translation given by the top and left padding of the element.
+ * 5. Any CSS transformation applied directly to the element (only 2D
+ * transformation; the 3D transformation are flattened, see `dom-matrix-2d` module
+ * for further details.)
+ * 6. Rotate, translate, and reflect as needed to match the writing mode and text
+ * direction of the element.
+ *
+ * The transformations of the element's ancestors are not currently computed (see
+ * bug 1355675).
+ *
+ * @param {Element} element
+ * The current element.
+ * @param {Window} window
+ * The window object.
+ * @param {Object} [options.ignoreWritingModeAndTextDirection=false]
+ * Avoid transforming the current matrix to match the text direction
+ * and writing mode.
+ * @return {Object} An object with the following properties:
+ * - {Array} currentMatrix
+ * The current matrix.
+ * - {Boolean} hasNodeTransformations
+ * true if the node has transformed and false otherwise.
+ */
+function getCurrentMatrix(
+ element,
+ window,
+ { ignoreWritingModeAndTextDirection } = {}
+) {
+ const computedStyle = getComputedStyle(element);
+
+ const paddingTop = parseFloat(computedStyle.paddingTop);
+ const paddingRight = parseFloat(computedStyle.paddingRight);
+ const paddingBottom = parseFloat(computedStyle.paddingBottom);
+ const paddingLeft = parseFloat(computedStyle.paddingLeft);
+ const borderTop = parseFloat(computedStyle.borderTopWidth);
+ const borderRight = parseFloat(computedStyle.borderRightWidth);
+ const borderBottom = parseFloat(computedStyle.borderBottomWidth);
+ const borderLeft = parseFloat(computedStyle.borderLeftWidth);
+
+ const nodeMatrix = getNodeTransformationMatrix(
+ element,
+ window.document.documentElement
+ );
+
+ let currentMatrix = identity();
+ let hasNodeTransformations = false;
+
+ // Scale based on the device pixel ratio.
+ currentMatrix = multiply(currentMatrix, scale(window.devicePixelRatio));
+
+ // Apply the current node's transformation matrix, relative to the inspected window's
+ // root element, but only if it's not a identity matrix.
+ if (isIdentity(nodeMatrix)) {
+ hasNodeTransformations = false;
+ } else {
+ currentMatrix = multiply(currentMatrix, nodeMatrix);
+ hasNodeTransformations = true;
+ }
+
+ // Translate the origin based on the node's padding and border values.
+ currentMatrix = multiply(
+ currentMatrix,
+ translate(paddingLeft + borderLeft, paddingTop + borderTop)
+ );
+
+ // Adjust as needed to match the writing mode and text direction of the element.
+ const size = {
+ width:
+ element.offsetWidth -
+ borderLeft -
+ borderRight -
+ paddingLeft -
+ paddingRight,
+ height:
+ element.offsetHeight -
+ borderTop -
+ borderBottom -
+ paddingTop -
+ paddingBottom,
+ };
+
+ if (!ignoreWritingModeAndTextDirection) {
+ const writingModeMatrix = getWritingModeMatrix(size, computedStyle);
+ if (!isIdentity(writingModeMatrix)) {
+ currentMatrix = multiply(currentMatrix, writingModeMatrix);
+ }
+ }
+
+ return { currentMatrix, hasNodeTransformations };
+}
+
+/**
+ * Given an array of four points, returns a string represent a path description.
+ *
+ * @param {Array} points
+ * An array with 4 pointer objects {x, y} representing the box quads.
+ * @return {String} a Path Description that can be used in svg's <path> element.
+ */
+function getPathDescriptionFromPoints(points) {
+ return (
+ "M" +
+ points[0].x +
+ "," +
+ points[0].y +
+ " " +
+ "L" +
+ points[1].x +
+ "," +
+ points[1].y +
+ " " +
+ "L" +
+ points[2].x +
+ "," +
+ points[2].y +
+ " " +
+ "L" +
+ points[3].x +
+ "," +
+ points[3].y
+ );
+}
+
+/**
+ * Given the rectangle's diagonal start and end coordinates, returns an array containing
+ * the four coordinates of a rectangle. If a matrix is provided, applies the matrix
+ * function to each of the coordinates' value.
+ *
+ * @param {Number} x1
+ * The x-axis coordinate of the rectangle's diagonal start point.
+ * @param {Number} y1
+ * The y-axis coordinate of the rectangle's diagonal start point.
+ * @param {Number} x2
+ * The x-axis coordinate of the rectangle's diagonal end point.
+ * @param {Number} y2
+ * The y-axis coordinate of the rectangle's diagonal end point.
+ * @param {Array} [matrix=identity()]
+ * A transformation matrix to apply.
+ * @return {Array} the four coordinate points of the given rectangle transformed by the
+ * matrix given.
+ */
+function getPointsFromDiagonal(x1, y1, x2, y2, matrix = identity()) {
+ return [
+ [x1, y1],
+ [x2, y1],
+ [x2, y2],
+ [x1, y2],
+ ].map(point => {
+ const transformedPoint = apply(matrix, point);
+
+ return { x: transformedPoint[0], y: transformedPoint[1] };
+ });
+}
+
+/**
+ * Updates the <canvas> element's style in accordance with the current window's
+ * device pixel ratio, and the position calculated in `getCanvasPosition`. It also
+ * clears the drawing context. This is called on canvas update after a scroll event where
+ * `getCanvasPosition` updates the new canvasPosition.
+ *
+ * @param {Canvas} canvas
+ * The <canvas> element.
+ * @param {Object} canvasPosition
+ * A pointer object {x, y} representing the <canvas> position to the top left
+ * corner of the page.
+ * @param {Number} devicePixelRatio
+ * The device pixel ratio.
+ * @param {Window} [options.zoomWindow]
+ * Optional window object used to calculate zoom (default = undefined).
+ */
+function updateCanvasElement(
+ canvas,
+ canvasPosition,
+ devicePixelRatio,
+ { zoomWindow } = {}
+) {
+ let { x, y } = canvasPosition;
+ const size = CANVAS_SIZE / devicePixelRatio;
+
+ if (zoomWindow) {
+ const zoom = getCurrentZoom(zoomWindow);
+ x *= zoom;
+ y *= zoom;
+ }
+
+ // Resize the canvas taking the dpr into account so as to have crisp lines, and
+ // translating it to give the perception that it always covers the viewport.
+ canvas.setAttribute(
+ "style",
+ `width: ${size}px; height: ${size}px; transform: translate(${x}px, ${y}px);`
+ );
+ canvas.getCanvasContext("2d").clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
+}
+
+/**
+ * Calculates and returns the <canvas>'s position in accordance with the page's scroll,
+ * document's size, canvas size, and viewport's size. This is called when a page's scroll
+ * is detected.
+ *
+ * @param {Object} canvasPosition
+ * A pointer object {x, y} representing the <canvas> position to the top left
+ * corner of the page.
+ * @param {Object} scrollPosition
+ * A pointer object {x, y} representing the window's pageXOffset and pageYOffset.
+ * @param {Window} window
+ * The window object.
+ * @param {Object} windowDimensions
+ * An object {width, height} representing the window's dimensions for the
+ * `window` given.
+ * @return {Boolean} true if the <canvas> position was updated and false otherwise.
+ */
+function updateCanvasPosition(
+ canvasPosition,
+ scrollPosition,
+ window,
+ windowDimensions
+) {
+ let { x: canvasX, y: canvasY } = canvasPosition;
+ const { x: scrollX, y: scrollY } = scrollPosition;
+ const cssCanvasSize = CANVAS_SIZE / window.devicePixelRatio;
+ const viewportSize = getViewportDimensions(window);
+ const { height, width } = windowDimensions;
+ const canvasWidth = cssCanvasSize;
+ const canvasHeight = cssCanvasSize;
+ let hasUpdated = false;
+
+ // Those values indicates the relative horizontal and vertical space the page can
+ // scroll before we have to reposition the <canvas>; they're 1/4 of the delta between
+ // the canvas' size and the viewport's size: that's because we want to consider both
+ // sides (top/bottom, left/right; so 1/2 for each side) and also we don't want to
+ // shown the edges of the canvas in case of fast scrolling (to avoid showing undraw
+ // areas, therefore another 1/2 here).
+ const bufferSizeX = (canvasWidth - viewportSize.width) >> 2;
+ const bufferSizeY = (canvasHeight - viewportSize.height) >> 2;
+
+ // Defines the boundaries for the canvas.
+ const leftBoundary = 0;
+ const rightBoundary = width - canvasWidth;
+ const topBoundary = 0;
+ const bottomBoundary = height - canvasHeight;
+
+ // Defines the thresholds that triggers the canvas' position to be updated.
+ const leftThreshold = scrollX - bufferSizeX;
+ const rightThreshold =
+ scrollX - canvasWidth + viewportSize.width + bufferSizeX;
+ const topThreshold = scrollY - bufferSizeY;
+ const bottomThreshold =
+ scrollY - canvasHeight + viewportSize.height + bufferSizeY;
+
+ if (canvasX < rightBoundary && canvasX < rightThreshold) {
+ canvasX = Math.min(leftThreshold, rightBoundary);
+ hasUpdated = true;
+ } else if (canvasX > leftBoundary && canvasX > leftThreshold) {
+ canvasX = Math.max(rightThreshold, leftBoundary);
+ hasUpdated = true;
+ }
+
+ if (canvasY < bottomBoundary && canvasY < bottomThreshold) {
+ canvasY = Math.min(topThreshold, bottomBoundary);
+ hasUpdated = true;
+ } else if (canvasY > topBoundary && canvasY > topThreshold) {
+ canvasY = Math.max(bottomThreshold, topBoundary);
+ hasUpdated = true;
+ }
+
+ // Update the canvas position with the calculated canvasX and canvasY positions.
+ canvasPosition.x = canvasX;
+ canvasPosition.y = canvasY;
+
+ return hasUpdated;
+}
+
+exports.CANVAS_SIZE = CANVAS_SIZE;
+exports.DEFAULT_COLOR = DEFAULT_COLOR;
+exports.clearRect = clearRect;
+exports.drawBubbleRect = drawBubbleRect;
+exports.drawLine = drawLine;
+exports.drawRect = drawRect;
+exports.drawRoundedRect = drawRoundedRect;
+exports.getBoundsFromPoints = getBoundsFromPoints;
+exports.getCurrentMatrix = getCurrentMatrix;
+exports.getPathDescriptionFromPoints = getPathDescriptionFromPoints;
+exports.getPointsFromDiagonal = getPointsFromDiagonal;
+exports.updateCanvasElement = updateCanvasElement;
+exports.updateCanvasPosition = updateCanvasPosition;
diff --git a/devtools/server/actors/highlighters/utils/markup.js b/devtools/server/actors/highlighters/utils/markup.js
new file mode 100644
index 0000000000..c3e75a1ee2
--- /dev/null
+++ b/devtools/server/actors/highlighters/utils/markup.js
@@ -0,0 +1,856 @@
+/* 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";
+
+const { Cu, Cr } = require("chrome");
+const {
+ getCurrentZoom,
+ getWindowDimensions,
+ getViewportDimensions,
+ loadSheet,
+ removeSheet,
+} = require("devtools/shared/layout/utils");
+const EventEmitter = require("devtools/shared/event-emitter");
+const InspectorUtils = require("InspectorUtils");
+
+const lazyContainer = {};
+
+loader.lazyRequireGetter(
+ lazyContainer,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isDocumentReady",
+ "devtools/server/actors/inspector/utils",
+ true
+);
+
+exports.getComputedStyle = node =>
+ lazyContainer.CssLogic.getComputedStyle(node);
+
+exports.getBindingElementAndPseudo = node =>
+ lazyContainer.CssLogic.getBindingElementAndPseudo(node);
+
+exports.hasPseudoClassLock = (...args) =>
+ InspectorUtils.hasPseudoClassLock(...args);
+
+exports.addPseudoClassLock = (...args) =>
+ InspectorUtils.addPseudoClassLock(...args);
+
+exports.removePseudoClassLock = (...args) =>
+ InspectorUtils.removePseudoClassLock(...args);
+
+const SVG_NS = "http://www.w3.org/2000/svg";
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+// Highlighter in parent process will create an iframe relative to its target
+// window. We need to make sure that the iframe is styled correctly. Note:
+// this styles are taken from browser/base/content/browser.css
+// iframe.devtools-highlighter-renderer rules.
+const XUL_HIGHLIGHTER_STYLES_SHEET = `data:text/css;charset=utf-8,
+:root > iframe.devtools-highlighter-renderer {
+ border: none;
+ pointer-events: none;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ z-index: 2;
+}`;
+
+const STYLESHEET_URI =
+ "resource://devtools/server/actors/" + "highlighters.css";
+
+const _tokens = Symbol("classList/tokens");
+
+/**
+ * Shims the element's `classList` for anonymous content elements; used
+ * internally by `CanvasFrameAnonymousContentHelper.getElement()` method.
+ */
+function ClassList(className) {
+ const trimmed = (className || "").trim();
+ this[_tokens] = trimmed ? trimmed.split(/\s+/) : [];
+}
+
+ClassList.prototype = {
+ item(index) {
+ return this[_tokens][index];
+ },
+ contains(token) {
+ return this[_tokens].includes(token);
+ },
+ add(token) {
+ if (!this.contains(token)) {
+ this[_tokens].push(token);
+ }
+ EventEmitter.emit(this, "update");
+ },
+ remove(token) {
+ const index = this[_tokens].indexOf(token);
+
+ if (index > -1) {
+ this[_tokens].splice(index, 1);
+ }
+ EventEmitter.emit(this, "update");
+ },
+ toggle(token, force) {
+ // If force parameter undefined retain the toggle behavior
+ if (force === undefined) {
+ if (this.contains(token)) {
+ this.remove(token);
+ } else {
+ this.add(token);
+ }
+ } else if (force) {
+ // If force is true, enforce token addition
+ this.add(token);
+ } else {
+ // If force is falsy value, enforce token removal
+ this.remove(token);
+ }
+ },
+ get length() {
+ return this[_tokens].length;
+ },
+ [Symbol.iterator]: function*() {
+ for (let i = 0; i < this.tokens.length; i++) {
+ yield this[_tokens][i];
+ }
+ },
+ toString() {
+ return this[_tokens].join(" ");
+ },
+};
+
+/**
+ * Is this content window a XUL window?
+ * @param {Window} window
+ * @return {Boolean}
+ */
+function isXUL(window) {
+ // XXX: We temporarily return true for HTML documents if the document disables
+ // scroll frames since the regular highlighter is broken in this case. This
+ // should be removed when bug 1594587 is fixed.
+ return (
+ window.document.documentElement.namespaceURI === XUL_NS ||
+ (window.isChromeWindow &&
+ window.document.documentElement.getAttribute("scrolling") === "false")
+ );
+}
+exports.isXUL = isXUL;
+
+/**
+ * Returns true if a DOM node is "valid", where "valid" means that the node isn't a dead
+ * object wrapper, is still attached to a document, and is of a given type.
+ * @param {DOMNode} node
+ * @param {Number} nodeType Optional, defaults to ELEMENT_NODE
+ * @return {Boolean}
+ */
+function isNodeValid(node, nodeType = Node.ELEMENT_NODE) {
+ // Is it still alive?
+ if (!node || Cu.isDeadWrapper(node)) {
+ return false;
+ }
+
+ // Is it of the right type?
+ if (node.nodeType !== nodeType) {
+ return false;
+ }
+
+ // Is its document accessible?
+ const doc = node.nodeType === Node.DOCUMENT_NODE ? node : node.ownerDocument;
+ if (!doc || !doc.defaultView) {
+ return false;
+ }
+
+ // Is the node connected to the document?
+ if (!node.isConnected) {
+ return false;
+ }
+
+ return true;
+}
+exports.isNodeValid = isNodeValid;
+
+/**
+ * Every highlighters should insert their markup content into the document's
+ * canvasFrame anonymous content container (see dom/webidl/Document.webidl).
+ *
+ * Since this container gets cleared when the document navigates, highlighters
+ * should use this helper to have their markup content automatically re-inserted
+ * in the new document.
+ *
+ * Since the markup content is inserted in the canvasFrame using
+ * insertAnonymousContent, this means that it can be modified using the API
+ * described in AnonymousContent.webidl.
+ * To retrieve the AnonymousContent instance, use the content getter.
+ *
+ * @param {HighlighterEnv} highlighterEnv
+ * The environemnt which windows will be used to insert the node.
+ * @param {Function} nodeBuilder
+ * A function that, when executed, returns a DOM node to be inserted into
+ * the canvasFrame.
+ */
+function CanvasFrameAnonymousContentHelper(highlighterEnv, nodeBuilder) {
+ this.highlighterEnv = highlighterEnv;
+ this.nodeBuilder = nodeBuilder;
+
+ this._onWindowReady = this._onWindowReady.bind(this);
+ this.highlighterEnv.on("window-ready", this._onWindowReady);
+
+ this.listeners = new Map();
+ this.elements = new Map();
+}
+
+CanvasFrameAnonymousContentHelper.prototype = {
+ initialize() {
+ // _insert will resolve this promise once the markup is displayed
+ const onInitialized = new Promise(resolve => {
+ this._initialized = resolve;
+ });
+ // Only try to create the highlighter when the document is loaded,
+ // otherwise, wait for the window-ready event to fire.
+ const doc = this.highlighterEnv.document;
+ if (
+ doc.documentElement &&
+ (isDocumentReady(doc) || doc.readyState !== "uninitialized")
+ ) {
+ this._insert();
+ }
+
+ return onInitialized;
+ },
+
+ destroy() {
+ this._remove();
+ if (this._iframe) {
+ // If iframe is used, remove one ref count from its numberOfHighlighters
+ // data attribute.
+ const numberOfHighlighters =
+ parseInt(this._iframe.dataset.numberOfHighlighters, 10) - 1;
+ this._iframe.dataset.numberOfHighlighters = numberOfHighlighters;
+ // If we reached 0, we can now remove the iframe and its styling from
+ // target window.
+ if (numberOfHighlighters === 0) {
+ this._iframe.remove();
+ removeSheet(this.highlighterEnv.window, XUL_HIGHLIGHTER_STYLES_SHEET);
+ }
+ this._iframe = null;
+ }
+
+ this.highlighterEnv.off("window-ready", this._onWindowReady);
+ this.highlighterEnv = this.nodeBuilder = this._content = null;
+ this.anonymousContentDocument = null;
+ this.anonymousContentWindow = null;
+ this.pageListenerTarget = null;
+
+ this._removeAllListeners();
+ this.elements.clear();
+ },
+
+ async _insert() {
+ await waitForContentLoaded(this.highlighterEnv.window);
+ if (!this.highlighterEnv) {
+ // CanvasFrameAnonymousContentHelper was already destroyed.
+ return;
+ }
+ if (isXUL(this.highlighterEnv.window)) {
+ // In order to use anonymous content, we need to create and use an IFRAME
+ // inside a XUL document first and use its window/document the same way we
+ // would normally use highlighter environment's window/document. See
+ // TODO: bug 1594587 for more details.
+ //
+ // Note: xul:window is not necessarily the top chrome window (as it's the
+ // case with about:devtools-toolbox). We need to ensure that we use the
+ // top chrome window to look up or create the iframe.
+ if (!this._iframe) {
+ const { documentElement } = this.highlighterEnv.window.document;
+ this._iframe = documentElement.querySelector(
+ ":scope > .devtools-highlighter-renderer"
+ );
+ if (this._iframe) {
+ // If iframe is used and already exists, add one ref count to its
+ // numberOfHighlighters data attribute.
+ const numberOfHighlighters =
+ parseInt(this._iframe.dataset.numberOfHighlighters, 10) + 1;
+ this._iframe.dataset.numberOfHighlighters = numberOfHighlighters;
+ } else {
+ this._iframe = this.highlighterEnv.window.document.createElement(
+ "iframe"
+ );
+ this._iframe.classList.add("devtools-highlighter-renderer");
+ // If iframe is used for the first time, add ref count of one to its
+ // numberOfHighlighters data attribute.
+ this._iframe.dataset.numberOfHighlighters = 1;
+ documentElement.append(this._iframe);
+ loadSheet(this.highlighterEnv.window, XUL_HIGHLIGHTER_STYLES_SHEET);
+ }
+ }
+
+ await waitForContentLoaded(this._iframe);
+ if (!this.highlighterEnv) {
+ // CanvasFrameAnonymousContentHelper was already destroyed.
+ return;
+ }
+
+ // If it's a XUL window anonymous content will be inserted inside a newly
+ // created IFRAME in the chrome window.
+ this.anonymousContentDocument = this._iframe.contentDocument;
+ this.anonymousContentWindow = this._iframe.contentWindow;
+ this.pageListenerTarget = this._iframe.contentWindow;
+ } else {
+ // Regular highlighters are drawn inside the anonymous content of the
+ // highlighter environment document.
+ this.anonymousContentDocument = this.highlighterEnv.document;
+ this.anonymousContentWindow = this.highlighterEnv.window;
+ this.pageListenerTarget = this.highlighterEnv.pageListenerTarget;
+ }
+
+ // For now highlighters.css is injected in content as a ua sheet because
+ // we no longer support scoped style sheets (see bug 1345702).
+ // If it did, highlighters.css would be injected as an anonymous content
+ // node using CanvasFrameAnonymousContentHelper instead.
+ loadSheet(this.anonymousContentWindow, STYLESHEET_URI);
+
+ const node = this.nodeBuilder();
+
+ // It was stated that hidden documents don't accept
+ // `insertAnonymousContent` calls yet. That doesn't seems the case anymore,
+ // at least on desktop. Therefore, removing the code that was dealing with
+ // that scenario, fixes when we're adding anonymous content in a tab that
+ // is not the active one (see bug 1260043 and bug 1260044)
+ try {
+ this._content = this.anonymousContentDocument.insertAnonymousContent(
+ node
+ );
+ } catch (e) {
+ // If the `insertAnonymousContent` fails throwing a `NS_ERROR_UNEXPECTED`, it means
+ // we don't have access to a `CustomContentContainer` yet (see bug 1365075).
+ // At this point, it could only happen on document's interactive state, and we
+ // need to wait until the `complete` state before inserting the anonymous content
+ // again.
+ if (
+ e.result === Cr.NS_ERROR_UNEXPECTED &&
+ this.anonymousContentDocument.readyState === "interactive"
+ ) {
+ // The next state change will be "complete" since the current is "interactive"
+ await new Promise(resolve => {
+ this.anonymousContentDocument.addEventListener(
+ "readystatechange",
+ resolve,
+ { once: true }
+ );
+ });
+ this._content = this.anonymousContentDocument.insertAnonymousContent(
+ node
+ );
+ } else {
+ throw e;
+ }
+ }
+
+ this._initialized();
+ },
+
+ _remove() {
+ try {
+ this.anonymousContentDocument.removeAnonymousContent(this._content);
+ } catch (e) {
+ // If the current window isn't the one the content was inserted into, this
+ // will fail, but that's fine.
+ }
+ },
+
+ /**
+ * The "window-ready" event can be triggered when:
+ * - a new window is created
+ * - a window is unfrozen from bfcache
+ * - when first attaching to a page
+ * - when swapping frame loaders (moving tabs, toggling RDM)
+ */
+ _onWindowReady({ isTopLevel }) {
+ if (isTopLevel) {
+ this._removeAllListeners();
+ this.elements.clear();
+ if (this._iframe) {
+ // When we are switching top level targets, we can remove the iframe and
+ // its styling as well, since it will be re-created for the new top
+ // level target document.
+ this._iframe.remove();
+ removeSheet(this.highlighterEnv.window, XUL_HIGHLIGHTER_STYLES_SHEET);
+ this._iframe = null;
+ }
+
+ this._insert();
+ }
+ },
+
+ getComputedStylePropertyValue(id, property) {
+ return (
+ this.content && this.content.getComputedStylePropertyValue(id, property)
+ );
+ },
+
+ getTextContentForElement(id) {
+ return this.content && this.content.getTextContentForElement(id);
+ },
+
+ setTextContentForElement(id, text) {
+ if (this.content) {
+ this.content.setTextContentForElement(id, text);
+ }
+ },
+
+ setAttributeForElement(id, name, value) {
+ if (this.content) {
+ this.content.setAttributeForElement(id, name, value);
+ }
+ },
+
+ getAttributeForElement(id, name) {
+ return this.content && this.content.getAttributeForElement(id, name);
+ },
+
+ removeAttributeForElement(id, name) {
+ if (this.content) {
+ this.content.removeAttributeForElement(id, name);
+ }
+ },
+
+ hasAttributeForElement(id, name) {
+ return typeof this.getAttributeForElement(id, name) === "string";
+ },
+
+ getCanvasContext(id, type = "2d") {
+ return this.content && this.content.getCanvasContext(id, type);
+ },
+
+ /**
+ * Add an event listener to one of the elements inserted in the canvasFrame
+ * native anonymous container.
+ * Like other methods in this helper, this requires the ID of the element to
+ * be passed in.
+ *
+ * Note that if the content page navigates, the event listeners won't be
+ * added again.
+ *
+ * Also note that unlike traditional DOM events, the events handled by
+ * listeners added here will propagate through the document only through
+ * bubbling phase, so the useCapture parameter isn't supported.
+ * It is possible however to call e.stopPropagation() to stop the bubbling.
+ *
+ * IMPORTANT: the chrome-only canvasFrame insertion API takes great care of
+ * not leaking references to inserted elements to chrome JS code. That's
+ * because otherwise, chrome JS code could freely modify native anon elements
+ * inside the canvasFrame and probably change things that are assumed not to
+ * change by the C++ code managing this frame.
+ * See https://wiki.mozilla.org/DevTools/Highlighter#The_AnonymousContent_API
+ * Unfortunately, the inserted nodes are still available via
+ * event.originalTarget, and that's what the event handler here uses to check
+ * that the event actually occured on the right element, but that also means
+ * consumers of this code would be able to access the inserted elements.
+ * Therefore, the originalTarget property will be nullified before the event
+ * is passed to your handler.
+ *
+ * IMPL DETAIL: A single event listener is added per event types only, at
+ * browser level and if the event originalTarget is found to have the provided
+ * ID, the callback is executed (and then IDs of parent nodes of the
+ * originalTarget are checked too).
+ *
+ * @param {String} id
+ * @param {String} type
+ * @param {Function} handler
+ */
+ addEventListenerForElement(id, type, handler) {
+ if (typeof id !== "string") {
+ throw new Error(
+ "Expected a string ID in addEventListenerForElement but" + " got: " + id
+ );
+ }
+
+ // If no one is listening for this type of event yet, add one listener.
+ if (!this.listeners.has(type)) {
+ const target = this.pageListenerTarget;
+ target.addEventListener(type, this, true);
+ // Each type entry in the map is a map of ids:handlers.
+ this.listeners.set(type, new Map());
+ }
+
+ const listeners = this.listeners.get(type);
+ listeners.set(id, handler);
+ },
+
+ /**
+ * Remove an event listener from one of the elements inserted in the
+ * canvasFrame native anonymous container.
+ * @param {String} id
+ * @param {String} type
+ */
+ removeEventListenerForElement(id, type) {
+ const listeners = this.listeners.get(type);
+ if (!listeners) {
+ return;
+ }
+ listeners.delete(id);
+
+ // If no one is listening for event type anymore, remove the listener.
+ if (!this.listeners.has(type)) {
+ const target = this.pageListenerTarget;
+ target.removeEventListener(type, this, true);
+ }
+ },
+
+ handleEvent(event) {
+ const listeners = this.listeners.get(event.type);
+ if (!listeners) {
+ return;
+ }
+
+ // Hide the originalTarget property to avoid exposing references to native
+ // anonymous elements. See addEventListenerForElement's comment.
+ let isPropagationStopped = false;
+ const eventProxy = new Proxy(event, {
+ get: (obj, name) => {
+ if (name === "originalTarget") {
+ return null;
+ } else if (name === "stopPropagation") {
+ return () => {
+ isPropagationStopped = true;
+ };
+ }
+ return obj[name];
+ },
+ });
+
+ // Start at originalTarget, bubble through ancestors and call handlers when
+ // needed.
+ let node = event.originalTarget;
+ while (node) {
+ const handler = listeners.get(node.id);
+ if (handler) {
+ handler(eventProxy, node.id);
+ if (isPropagationStopped) {
+ break;
+ }
+ }
+ node = node.parentNode;
+ }
+ },
+
+ _removeAllListeners() {
+ if (this.pageListenerTarget) {
+ const target = this.pageListenerTarget;
+ for (const [type] of this.listeners) {
+ target.removeEventListener(type, this, true);
+ }
+ }
+ this.listeners.clear();
+ },
+
+ getElement(id) {
+ if (this.elements.has(id)) {
+ return this.elements.get(id);
+ }
+
+ const classList = new ClassList(this.getAttributeForElement(id, "class"));
+
+ EventEmitter.on(classList, "update", () => {
+ this.setAttributeForElement(id, "class", classList.toString());
+ });
+
+ const element = {
+ getTextContent: () => this.getTextContentForElement(id),
+ setTextContent: text => this.setTextContentForElement(id, text),
+ setAttribute: (name, val) => this.setAttributeForElement(id, name, val),
+ getAttribute: name => this.getAttributeForElement(id, name),
+ removeAttribute: name => this.removeAttributeForElement(id, name),
+ hasAttribute: name => this.hasAttributeForElement(id, name),
+ getCanvasContext: type => this.getCanvasContext(id, type),
+ addEventListener: (type, handler) => {
+ return this.addEventListenerForElement(id, type, handler);
+ },
+ removeEventListener: (type, handler) => {
+ return this.removeEventListenerForElement(id, type, handler);
+ },
+ computedStyle: {
+ getPropertyValue: property =>
+ this.getComputedStylePropertyValue(id, property),
+ },
+ classList,
+ };
+
+ this.elements.set(id, element);
+
+ return element;
+ },
+
+ get content() {
+ if (!this._content || Cu.isDeadWrapper(this._content)) {
+ return null;
+ }
+ return this._content;
+ },
+
+ /**
+ * The canvasFrame anonymous content container gets zoomed in/out with the
+ * page. If this is unwanted, i.e. if you want the inserted element to remain
+ * unzoomed, then this method can be used.
+ *
+ * Consumers of the CanvasFrameAnonymousContentHelper should call this method,
+ * it isn't executed automatically. Typically, AutoRefreshHighlighter can call
+ * it when _update is executed.
+ *
+ * The matching element will be scaled down or up by 1/zoomLevel (using css
+ * transform) to cancel the current zoom. The element's width and height
+ * styles will also be set according to the scale. Finally, the element's
+ * position will be set as absolute.
+ *
+ * Note that if the matching element already has an inline style attribute, it
+ * *won't* be preserved.
+ *
+ * @param {DOMNode} node This node is used to determine which container window
+ * should be used to read the current zoom value.
+ * @param {String} id The ID of the root element inserted with this API.
+ */
+ scaleRootElement(node, id) {
+ const boundaryWindow = this.highlighterEnv.window;
+ const zoom = getCurrentZoom(node);
+ // Hide the root element and force the reflow in order to get the proper window's
+ // dimensions without increasing them.
+ this.setAttributeForElement(id, "style", "display: none");
+ node.offsetWidth;
+
+ let { width, height } = getWindowDimensions(boundaryWindow);
+ let value = "";
+
+ if (zoom !== 1) {
+ value = `transform-origin:top left; transform:scale(${1 / zoom}); `;
+ width *= zoom;
+ height *= zoom;
+ }
+
+ value += `position:absolute; width:${width}px;height:${height}px; overflow:hidden`;
+
+ this.setAttributeForElement(id, "style", value);
+ },
+
+ /**
+ * Helper function that creates SVG DOM nodes.
+ * @param {Object} Options for the node include:
+ * - nodeType: the type of node, defaults to "box".
+ * - attributes: a {name:value} object to be used as attributes for the node.
+ * - prefix: a string that will be used to prefix the values of the id and class
+ * attributes.
+ * - parent: if provided, the newly created element will be appended to this
+ * node.
+ */
+ createSVGNode(options) {
+ if (!options.nodeType) {
+ options.nodeType = "box";
+ }
+
+ options.namespace = SVG_NS;
+
+ return this.createNode(options);
+ },
+
+ /**
+ * Helper function that creates DOM nodes.
+ * @param {Object} Options for the node include:
+ * - nodeType: the type of node, defaults to "div".
+ * - namespace: the namespace to use to create the node, defaults to XHTML namespace.
+ * - attributes: a {name:value} object to be used as attributes for the node.
+ * - prefix: a string that will be used to prefix the values of the id and class
+ * attributes.
+ * - parent: if provided, the newly created element will be appended to this
+ * node.
+ * - text: if provided, set the text content of the element.
+ */
+ createNode(options) {
+ const type = options.nodeType || "div";
+ const namespace = options.namespace || XHTML_NS;
+ const doc = this.anonymousContentDocument;
+
+ const node = doc.createElementNS(namespace, type);
+
+ for (const name in options.attributes || {}) {
+ let value = options.attributes[name];
+ if (options.prefix && (name === "class" || name === "id")) {
+ value = options.prefix + value;
+ }
+ node.setAttribute(name, value);
+ }
+
+ if (options.parent) {
+ options.parent.appendChild(node);
+ }
+
+ if (options.text) {
+ node.appendChild(doc.createTextNode(options.text));
+ }
+
+ return node;
+ },
+};
+exports.CanvasFrameAnonymousContentHelper = CanvasFrameAnonymousContentHelper;
+
+/**
+ * Wait for document readyness.
+ * @param {Object} iframeOrWindow
+ * IFrame or Window for which the content should be loaded.
+ */
+function waitForContentLoaded(iframeOrWindow) {
+ let loadEvent = "DOMContentLoaded";
+ // If we are waiting for an iframe to load and it is for a XUL window
+ // highlighter that is not browser toolbox, we must wait for IFRAME's "load".
+ if (
+ iframeOrWindow.contentWindow &&
+ iframeOrWindow.ownerGlobal !==
+ iframeOrWindow.contentWindow.browsingContext.topChromeWindow
+ ) {
+ loadEvent = "load";
+ }
+
+ const doc = iframeOrWindow.contentDocument || iframeOrWindow.document;
+ if (isDocumentReady(doc)) {
+ return Promise.resolve();
+ }
+
+ return new Promise(resolve => {
+ iframeOrWindow.addEventListener(loadEvent, resolve, { once: true });
+ });
+}
+
+/**
+ * Move the infobar to the right place in the highlighter. This helper method is utilized
+ * in both css-grid.js and box-model.js to help position the infobar in an appropriate
+ * space over the highlighted node element or grid area. The infobar is used to display
+ * relevant information about the highlighted item (ex, node or grid name and dimensions).
+ *
+ * This method will first try to position the infobar to top or bottom of the container
+ * such that it has enough space for the height of the infobar. Afterwards, it will try
+ * to horizontally center align with the container element if possible.
+ *
+ * @param {DOMNode} container
+ * The container element which will be used to position the infobar.
+ * @param {Object} bounds
+ * The content bounds of the container element.
+ * @param {Window} win
+ * The window object.
+ * @param {Object} [options={}]
+ * Advanced options for the infobar.
+ * @param {String} options.position
+ * Force the infobar to be displayed either on "top" or "bottom". Any other value
+ * will be ingnored.
+ * @param {Boolean} options.hideIfOffscreen
+ * If set to `true`, hides the infobar if it's offscreen, instead of automatically
+ * reposition it.
+ */
+function moveInfobar(container, bounds, win, options = {}) {
+ const zoom = getCurrentZoom(win);
+ const viewport = getViewportDimensions(win);
+
+ const { computedStyle } = container;
+
+ const margin = 2;
+ const arrowSize = parseFloat(
+ computedStyle.getPropertyValue("--highlighter-bubble-arrow-size")
+ );
+ const containerHeight = parseFloat(computedStyle.getPropertyValue("height"));
+ const containerWidth = parseFloat(computedStyle.getPropertyValue("width"));
+ const containerHalfWidth = containerWidth / 2;
+
+ const viewportWidth = viewport.width * zoom;
+ const viewportHeight = viewport.height * zoom;
+ let { pageXOffset, pageYOffset } = win;
+
+ pageYOffset *= zoom;
+ pageXOffset *= zoom;
+
+ // Defines the boundaries for the infobar.
+ const topBoundary = margin;
+ const bottomBoundary = viewportHeight - containerHeight - margin - 1;
+ const leftBoundary = containerHalfWidth + margin;
+ const rightBoundary = viewportWidth - containerHalfWidth - margin;
+
+ // Set the default values.
+ let top = bounds.y - containerHeight - arrowSize;
+ const bottom = bounds.bottom + margin + arrowSize;
+ let left = bounds.x + bounds.width / 2;
+ let isOverlapTheNode = false;
+ let positionAttribute = "top";
+ let position = "absolute";
+
+ // Here we start the math.
+ // We basically want to position absolutely the infobar, except when is pointing to a
+ // node that is offscreen or partially offscreen, in a way that the infobar can't
+ // be placed neither on top nor on bottom.
+ // In such cases, the infobar will overlap the node, and to limit the latency given
+ // by APZ (See Bug 1312103) it will be positioned as "fixed".
+ // It's a sort of "position: sticky" (but positioned as absolute instead of relative).
+ const canBePlacedOnTop = top >= pageYOffset;
+ const canBePlacedOnBottom = bottomBoundary + pageYOffset - bottom > 0;
+ const forcedOnTop = options.position === "top";
+ const forcedOnBottom = options.position === "bottom";
+
+ if (
+ (!canBePlacedOnTop && canBePlacedOnBottom && !forcedOnTop) ||
+ forcedOnBottom
+ ) {
+ top = bottom;
+ positionAttribute = "bottom";
+ }
+
+ const isOffscreenOnTop = top < topBoundary + pageYOffset;
+ const isOffscreenOnBottom = top > bottomBoundary + pageYOffset;
+ const isOffscreenOnLeft = left < leftBoundary + pageXOffset;
+ const isOffscreenOnRight = left > rightBoundary + pageXOffset;
+
+ if (isOffscreenOnTop) {
+ top = topBoundary;
+ isOverlapTheNode = true;
+ } else if (isOffscreenOnBottom) {
+ top = bottomBoundary;
+ isOverlapTheNode = true;
+ } else if (isOffscreenOnLeft || isOffscreenOnRight) {
+ isOverlapTheNode = true;
+ top -= pageYOffset;
+ }
+
+ if (isOverlapTheNode && options.hideIfOffscreen) {
+ container.setAttribute("hidden", "true");
+ return;
+ } else if (isOverlapTheNode) {
+ left = Math.min(Math.max(leftBoundary, left - pageXOffset), rightBoundary);
+
+ position = "fixed";
+ container.setAttribute("hide-arrow", "true");
+ } else {
+ position = "absolute";
+ container.removeAttribute("hide-arrow");
+ }
+
+ // We need to scale the infobar Independently from the highlighter's container;
+ // otherwise the `position: fixed` won't work, since "any value other than `none` for
+ // the transform, results in the creation of both a stacking context and a containing
+ // block. The object acts as a containing block for fixed positioned descendants."
+ // (See https://www.w3.org/TR/css-transforms-1/#transform-rendering)
+ // We also need to shift the infobar 50% to the left in order for it to appear centered
+ // on the element it points to.
+ container.setAttribute(
+ "style",
+ `
+ position:${position};
+ transform-origin: 0 0;
+ transform: scale(${1 / zoom}) translate(calc(${left}px - 50%), ${top}px)`
+ );
+
+ container.setAttribute("position", positionAttribute);
+}
+exports.moveInfobar = moveInfobar;
diff --git a/devtools/server/actors/highlighters/utils/moz.build b/devtools/server/actors/highlighters/utils/moz.build
new file mode 100644
index 0000000000..ab4f96912d
--- /dev/null
+++ b/devtools/server/actors/highlighters/utils/moz.build
@@ -0,0 +1,7 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules("accessibility.js", "canvas.js", "markup.js")
diff --git a/devtools/server/actors/inspector/constants.js b/devtools/server/actors/inspector/constants.js
new file mode 100644
index 0000000000..c253c67b02
--- /dev/null
+++ b/devtools/server/actors/inspector/constants.js
@@ -0,0 +1,17 @@
+/* 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";
+
+/**
+ * Any event listener flagged with this symbol will not be considered when
+ * the EventCollector class enumerates listeners for nodes. For example:
+ *
+ * const someListener = () => {};
+ * someListener[EXCLUDED_LISTENER] = true;
+ * eventListenerService.addSystemEventListener(node, "event", someListener);
+ */
+const EXCLUDED_LISTENER = Symbol("event-collector-excluded-listener");
+
+exports.EXCLUDED_LISTENER = EXCLUDED_LISTENER;
diff --git a/devtools/server/actors/inspector/css-logic.js b/devtools/server/actors/inspector/css-logic.js
new file mode 100644
index 0000000000..74a229dea0
--- /dev/null
+++ b/devtools/server/actors/inspector/css-logic.js
@@ -0,0 +1,1653 @@
+/* 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/. */
+
+/*
+ * About the objects defined in this file:
+ * - CssLogic contains style information about a view context. It provides
+ * access to 2 sets of objects: Css[Sheet|Rule|Selector] provide access to
+ * information that does not change when the selected element changes while
+ * Css[Property|Selector]Info provide information that is dependent on the
+ * selected element.
+ * Its key methods are highlight(), getPropertyInfo() and forEachSheet(), etc
+ *
+ * - CssSheet provides a more useful API to a DOM CSSSheet for our purposes,
+ * including shortSource and href.
+ * - CssRule a more useful API to a DOM CSSRule including access to the group
+ * of CssSelectors that the rule provides properties for
+ * - CssSelector A single selector - i.e. not a selector group. In other words
+ * a CssSelector does not contain ','. This terminology is different from the
+ * standard DOM API, but more inline with the definition in the spec.
+ *
+ * - CssPropertyInfo contains style information for a single property for the
+ * highlighted element.
+ * - CssSelectorInfo is a wrapper around CssSelector, which adds sorting with
+ * reference to the selected element.
+ */
+
+"use strict";
+
+const { Cu } = require("chrome");
+const nodeConstants = require("devtools/shared/dom-node-constants");
+const {
+ getBindingElementAndPseudo,
+ getCSSStyleRules,
+ l10n,
+ hasVisitedState,
+ isAgentStylesheet,
+ isAuthorStylesheet,
+ isUserStylesheet,
+ shortSource,
+ FILTER,
+ STATUS,
+} = require("devtools/shared/inspector/css-logic");
+const InspectorUtils = require("InspectorUtils");
+
+const COMPAREMODE = {
+ BOOLEAN: "bool",
+ INTEGER: "int",
+};
+
+function CssLogic() {
+ this._propertyInfos = {};
+}
+
+exports.CssLogic = CssLogic;
+
+CssLogic.prototype = {
+ // Both setup by highlight().
+ viewedElement: null,
+ viewedDocument: null,
+
+ // The cache of the known sheets.
+ _sheets: null,
+
+ // Have the sheets been cached?
+ _sheetsCached: false,
+
+ // The total number of rules, in all stylesheets, after filtering.
+ _ruleCount: 0,
+
+ // The computed styles for the viewedElement.
+ _computedStyle: null,
+
+ // Source filter. Only display properties coming from the given source
+ _sourceFilter: FILTER.USER,
+
+ // Used for tracking unique CssSheet/CssRule/CssSelector objects, in a run of
+ // processMatchedSelectors().
+ _passId: 0,
+
+ // Used for tracking matched CssSelector objects.
+ _matchId: 0,
+
+ _matchedRules: null,
+ _matchedSelectors: null,
+
+ // Cached keyframes rules in all stylesheets
+ _keyframesRules: null,
+
+ /**
+ * Reset various properties
+ */
+ reset: function() {
+ this._propertyInfos = {};
+ this._ruleCount = 0;
+ this._sheetIndex = 0;
+ this._sheets = {};
+ this._sheetsCached = false;
+ this._matchedRules = null;
+ this._matchedSelectors = null;
+ this._keyframesRules = [];
+ },
+
+ /**
+ * Focus on a new element - remove the style caches.
+ *
+ * @param {Element} aViewedElement the element the user has highlighted
+ * in the Inspector.
+ */
+ highlight: function(viewedElement) {
+ if (!viewedElement) {
+ this.viewedElement = null;
+ this.viewedDocument = null;
+ this._computedStyle = null;
+ this.reset();
+ return;
+ }
+
+ if (viewedElement === this.viewedElement) {
+ return;
+ }
+
+ this.viewedElement = viewedElement;
+
+ const doc = this.viewedElement.ownerDocument;
+ if (doc != this.viewedDocument) {
+ // New document: clear/rebuild the cache.
+ this.viewedDocument = doc;
+
+ // Hunt down top level stylesheets, and cache them.
+ this._cacheSheets();
+ } else {
+ // Clear cached data in the CssPropertyInfo objects.
+ this._propertyInfos = {};
+ }
+
+ this._matchedRules = null;
+ this._matchedSelectors = null;
+ this._computedStyle = CssLogic.getComputedStyle(this.viewedElement);
+ },
+
+ /**
+ * Get the values of all the computed CSS properties for the highlighted
+ * element.
+ * @returns {object} The computed CSS properties for a selected element
+ */
+ get computedStyle() {
+ return this._computedStyle;
+ },
+
+ /**
+ * Get the source filter.
+ * @returns {string} The source filter being used.
+ */
+ get sourceFilter() {
+ return this._sourceFilter;
+ },
+
+ /**
+ * Source filter. Only display properties coming from the given source (web
+ * address). Note that in order to avoid information overload we DO NOT show
+ * unmatched system rules.
+ * @see FILTER.*
+ */
+ set sourceFilter(value) {
+ const oldValue = this._sourceFilter;
+ this._sourceFilter = value;
+
+ let ruleCount = 0;
+
+ // Update the CssSheet objects.
+ this.forEachSheet(function(sheet) {
+ if (sheet.authorSheet && sheet.sheetAllowed) {
+ ruleCount += sheet.ruleCount;
+ }
+ }, this);
+
+ this._ruleCount = ruleCount;
+
+ // Full update is needed because the this.processMatchedSelectors() method
+ // skips UA stylesheets if the filter does not allow such sheets.
+ const needFullUpdate = oldValue == FILTER.UA || value == FILTER.UA;
+
+ if (needFullUpdate) {
+ this._matchedRules = null;
+ this._matchedSelectors = null;
+ this._propertyInfos = {};
+ } else {
+ // Update the CssPropertyInfo objects.
+ for (const property in this._propertyInfos) {
+ this._propertyInfos[property].needRefilter = true;
+ }
+ }
+ },
+
+ /**
+ * Return a CssPropertyInfo data structure for the currently viewed element
+ * and the specified CSS property. If there is no currently viewed element we
+ * return an empty object.
+ *
+ * @param {string} property The CSS property to look for.
+ * @return {CssPropertyInfo} a CssPropertyInfo structure for the given
+ * property.
+ */
+ getPropertyInfo: function(property) {
+ if (!this.viewedElement) {
+ return {};
+ }
+
+ let info = this._propertyInfos[property];
+ if (!info) {
+ info = new CssPropertyInfo(this, property);
+ this._propertyInfos[property] = info;
+ }
+
+ return info;
+ },
+
+ /**
+ * Cache all the stylesheets in the inspected document
+ * @private
+ */
+ _cacheSheets: function() {
+ this._passId++;
+ this.reset();
+
+ // styleSheets isn't an array, but forEach can work on it anyway
+ const styleSheets = InspectorUtils.getAllStyleSheets(
+ this.viewedDocument,
+ true
+ );
+ Array.prototype.forEach.call(styleSheets, this._cacheSheet, this);
+
+ this._sheetsCached = true;
+ },
+
+ /**
+ * Cache a stylesheet if it falls within the requirements: if it's enabled,
+ * and if the @media is allowed. This method also walks through the stylesheet
+ * cssRules to find @imported rules, to cache the stylesheets of those rules
+ * as well. In addition, the @keyframes rules in the stylesheet are cached.
+ *
+ * @private
+ * @param {CSSStyleSheet} domSheet the CSSStyleSheet object to cache.
+ */
+ _cacheSheet: function(domSheet) {
+ if (domSheet.disabled) {
+ return;
+ }
+
+ // Only work with stylesheets that have their media allowed.
+ if (!this.mediaMatches(domSheet)) {
+ return;
+ }
+
+ // Cache the sheet.
+ const cssSheet = this.getSheet(domSheet, this._sheetIndex++);
+ if (cssSheet._passId != this._passId) {
+ cssSheet._passId = this._passId;
+
+ // Find import and keyframes rules.
+ for (const aDomRule of cssSheet.getCssRules()) {
+ if (
+ aDomRule.type == CSSRule.IMPORT_RULE &&
+ aDomRule.styleSheet &&
+ this.mediaMatches(aDomRule)
+ ) {
+ this._cacheSheet(aDomRule.styleSheet);
+ } else if (aDomRule.type == CSSRule.KEYFRAMES_RULE) {
+ this._keyframesRules.push(aDomRule);
+ }
+ }
+ }
+ },
+
+ /**
+ * Retrieve the list of stylesheets in the document.
+ *
+ * @return {array} the list of stylesheets in the document.
+ */
+ get sheets() {
+ if (!this._sheetsCached) {
+ this._cacheSheets();
+ }
+
+ const sheets = [];
+ this.forEachSheet(function(sheet) {
+ if (sheet.authorSheet) {
+ sheets.push(sheet);
+ }
+ }, this);
+
+ return sheets;
+ },
+
+ /**
+ * Retrieve the list of keyframes rules in the document.
+ *
+ * @ return {array} the list of keyframes rules in the document.
+ */
+ get keyframesRules() {
+ if (!this._sheetsCached) {
+ this._cacheSheets();
+ }
+ return this._keyframesRules;
+ },
+
+ /**
+ * Retrieve a CssSheet object for a given a CSSStyleSheet object. If the
+ * stylesheet is already cached, you get the existing CssSheet object,
+ * otherwise the new CSSStyleSheet object is cached.
+ *
+ * @param {CSSStyleSheet} domSheet the CSSStyleSheet object you want.
+ * @param {number} index the index, within the document, of the stylesheet.
+ *
+ * @return {CssSheet} the CssSheet object for the given CSSStyleSheet object.
+ */
+ getSheet: function(domSheet, index) {
+ let cacheId = "";
+
+ if (domSheet.href) {
+ cacheId = domSheet.href;
+ } else if (domSheet.ownerNode?.ownerDocument) {
+ cacheId = domSheet.ownerNode.ownerDocument.location;
+ }
+
+ let sheet = null;
+ let sheetFound = false;
+
+ if (cacheId in this._sheets) {
+ for (sheet of this._sheets[cacheId]) {
+ if (sheet.domSheet === domSheet) {
+ if (index != -1) {
+ sheet.index = index;
+ }
+ sheetFound = true;
+ break;
+ }
+ }
+ }
+
+ if (!sheetFound) {
+ if (!(cacheId in this._sheets)) {
+ this._sheets[cacheId] = [];
+ }
+
+ sheet = new CssSheet(this, domSheet, index);
+ if (sheet.sheetAllowed && sheet.authorSheet) {
+ this._ruleCount += sheet.ruleCount;
+ }
+
+ this._sheets[cacheId].push(sheet);
+ }
+
+ return sheet;
+ },
+
+ /**
+ * Process each cached stylesheet in the document using your callback.
+ *
+ * @param {function} callback the function you want executed for each of the
+ * CssSheet objects cached.
+ * @param {object} scope the scope you want for the callback function. scope
+ * will be the this object when callback executes.
+ */
+ forEachSheet: function(callback, scope) {
+ for (const cacheId in this._sheets) {
+ const sheets = this._sheets[cacheId];
+ for (let i = 0; i < sheets.length; i++) {
+ // We take this as an opportunity to clean dead sheets
+ try {
+ const sheet = sheets[i];
+ // If accessing domSheet raises an exception, then the style
+ // sheet is a dead object.
+ sheet.domSheet;
+ callback.call(scope, sheet, i, sheets);
+ } catch (e) {
+ sheets.splice(i, 1);
+ i--;
+ }
+ }
+ }
+ },
+
+ /**
+
+ /**
+ * Get the number CSSRule objects in the document, counted from all of
+ * the stylesheets. System sheets are excluded. If a filter is active, this
+ * tells only the number of CSSRule objects inside the selected
+ * CSSStyleSheet.
+ *
+ * WARNING: This only provides an estimate of the rule count, and the results
+ * could change at a later date. Todo remove this
+ *
+ * @return {number} the number of CSSRule (all rules).
+ */
+ get ruleCount() {
+ if (!this._sheetsCached) {
+ this._cacheSheets();
+ }
+
+ return this._ruleCount;
+ },
+
+ /**
+ * Process the CssSelector objects that match the highlighted element and its
+ * parent elements. scope.callback() is executed for each CssSelector
+ * object, being passed the CssSelector object and the match status.
+ *
+ * This method also includes all of the element.style properties, for each
+ * highlighted element parent and for the highlighted element itself.
+ *
+ * Note that the matched selectors are cached, such that next time your
+ * callback is invoked for the cached list of CssSelector objects.
+ *
+ * @param {function} callback the function you want to execute for each of
+ * the matched selectors.
+ * @param {object} scope the scope you want for the callback function. scope
+ * will be the this object when callback executes.
+ */
+ processMatchedSelectors: function(callback, scope) {
+ if (this._matchedSelectors) {
+ if (callback) {
+ this._passId++;
+ this._matchedSelectors.forEach(function(value) {
+ callback.call(scope, value[0], value[1]);
+ value[0].cssRule._passId = this._passId;
+ }, this);
+ }
+ return;
+ }
+
+ if (!this._matchedRules) {
+ this._buildMatchedRules();
+ }
+
+ this._matchedSelectors = [];
+ this._passId++;
+
+ for (const matchedRule of this._matchedRules) {
+ const [rule, status, distance] = matchedRule;
+
+ rule.selectors.forEach(function(selector) {
+ if (
+ selector._matchId !== this._matchId &&
+ (selector.inlineStyle ||
+ this.selectorMatchesElement(rule.domRule, selector.selectorIndex))
+ ) {
+ selector._matchId = this._matchId;
+ this._matchedSelectors.push([selector, status, distance]);
+ if (callback) {
+ callback.call(scope, selector, status, distance);
+ }
+ }
+ }, this);
+
+ rule._passId = this._passId;
+ }
+ },
+
+ /**
+ * Check if the given selector matches the highlighted element or any of its
+ * parents.
+ *
+ * @private
+ * @param {DOMRule} domRule
+ * The DOM Rule containing the selector.
+ * @param {Number} idx
+ * The index of the selector within the DOMRule.
+ * @return {boolean}
+ * true if the given selector matches the highlighted element or any
+ * of its parents, otherwise false is returned.
+ */
+ selectorMatchesElement: function(domRule, idx) {
+ let element = this.viewedElement;
+ do {
+ if (InspectorUtils.selectorMatchesElement(element, domRule, idx)) {
+ return true;
+ }
+ } while (
+ (element = element.parentNode) &&
+ element.nodeType === nodeConstants.ELEMENT_NODE
+ );
+
+ return false;
+ },
+
+ /**
+ * Check if the highlighted element or it's parents have matched selectors.
+ *
+ * @param {array} aProperties The list of properties you want to check if they
+ * have matched selectors or not.
+ * @return {object} An object that tells for each property if it has matched
+ * selectors or not. Object keys are property names and values are booleans.
+ */
+ hasMatchedSelectors: function(properties) {
+ if (!this._matchedRules) {
+ this._buildMatchedRules();
+ }
+
+ const result = {};
+
+ this._matchedRules.some(function(value) {
+ const rule = value[0];
+ const status = value[1];
+ properties = properties.filter(property => {
+ // We just need to find if a rule has this property while it matches
+ // the viewedElement (or its parents).
+ if (
+ rule.getPropertyValue(property) &&
+ (status == STATUS.MATCHED ||
+ (status == STATUS.PARENT_MATCH &&
+ InspectorUtils.isInheritedProperty(property)))
+ ) {
+ result[property] = true;
+ return false;
+ }
+ // Keep the property for the next rule.
+ return true;
+ });
+ return properties.length == 0;
+ }, this);
+
+ return result;
+ },
+
+ /**
+ * Build the array of matched rules for the currently highlighted element.
+ * The array will hold rules that match the viewedElement and its parents.
+ *
+ * @private
+ */
+ _buildMatchedRules: function() {
+ let domRules;
+ let element = this.viewedElement;
+ const filter = this.sourceFilter;
+ let sheetIndex = 0;
+
+ // distance is used to tell us how close an ancestor is to an element e.g.
+ // 0: The rule is directly applied to the current element.
+ // -1: The rule is inherited from the current element's first parent.
+ // -2: The rule is inherited from the current element's second parent.
+ // etc.
+ let distance = 0;
+
+ this._matchId++;
+ this._passId++;
+ this._matchedRules = [];
+
+ if (!element) {
+ return;
+ }
+
+ do {
+ const status =
+ this.viewedElement === element ? STATUS.MATCHED : STATUS.PARENT_MATCH;
+
+ try {
+ domRules = getCSSStyleRules(element);
+ } catch (ex) {
+ console.log("CL__buildMatchedRules error: " + ex);
+ continue;
+ }
+
+ // getCSSStyleRules can return null with a shadow DOM element.
+ for (const domRule of domRules || []) {
+ if (domRule.type !== CSSRule.STYLE_RULE) {
+ continue;
+ }
+
+ const sheet = this.getSheet(domRule.parentStyleSheet, -1);
+ if (sheet._passId !== this._passId) {
+ sheet.index = sheetIndex++;
+ sheet._passId = this._passId;
+ }
+
+ if (filter === FILTER.USER && !sheet.authorSheet) {
+ continue;
+ }
+
+ const rule = sheet.getRule(domRule);
+ if (rule._passId === this._passId) {
+ continue;
+ }
+
+ rule._matchId = this._matchId;
+ rule._passId = this._passId;
+ this._matchedRules.push([rule, status, distance]);
+ }
+
+ // Add element.style information.
+ if (element.style && element.style.length > 0) {
+ const rule = new CssRule(null, { style: element.style }, element);
+ rule._matchId = this._matchId;
+ rule._passId = this._passId;
+ this._matchedRules.push([rule, status, distance]);
+ }
+
+ distance--;
+ } while (
+ (element = element.parentNode) &&
+ element.nodeType === nodeConstants.ELEMENT_NODE
+ );
+ },
+
+ /**
+ * Tells if the given DOM CSS object matches the current view media.
+ *
+ * @param {object} domObject The DOM CSS object to check.
+ * @return {boolean} True if the DOM CSS object matches the current view
+ * media, or false otherwise.
+ */
+ mediaMatches: function(domObject) {
+ const mediaText = domObject.media.mediaText;
+ return (
+ !mediaText ||
+ this.viewedDocument.defaultView.matchMedia(mediaText).matches
+ );
+ },
+};
+
+/**
+ * If the element has an id, return '#id'. Otherwise return 'tagname[n]' where
+ * n is the index of this element in its siblings.
+ * <p>A technically more 'correct' output from the no-id case might be:
+ * 'tagname:nth-of-type(n)' however this is unlikely to be more understood
+ * and it is longer.
+ *
+ * @param {Element} element the element for which you want the short name.
+ * @return {string} the string to be displayed for element.
+ */
+CssLogic.getShortName = function(element) {
+ if (!element) {
+ return "null";
+ }
+ if (element.id) {
+ return "#" + element.id;
+ }
+ let priorSiblings = 0;
+ let temp = element;
+ while ((temp = temp.previousElementSibling)) {
+ priorSiblings++;
+ }
+ return element.tagName + "[" + priorSiblings + "]";
+};
+
+/**
+ * Get a string list of selectors for a given DOMRule.
+ *
+ * @param {DOMRule} domRule
+ * The DOMRule to parse.
+ * @return {Array}
+ * An array of string selectors.
+ */
+CssLogic.getSelectors = function(domRule) {
+ if (domRule.type !== CSSRule.STYLE_RULE) {
+ // Return empty array since InspectorUtils.getSelectorCount() assumes
+ // only STYLE_RULE type.
+ return [];
+ }
+
+ const selectors = [];
+
+ const len = InspectorUtils.getSelectorCount(domRule);
+ for (let i = 0; i < len; i++) {
+ const text = InspectorUtils.getSelectorText(domRule, i);
+ selectors.push(text);
+ }
+ return selectors;
+};
+
+/**
+ * Given a node, check to see if it is a ::before or ::after element.
+ * If so, return the node that is accessible from within the document
+ * (the parent of the anonymous node), along with which pseudo element
+ * it was. Otherwise, return the node itself.
+ *
+ * @returns {Object}
+ * - {DOMNode} node The non-anonymous node
+ * - {string} pseudo One of ':marker', ':before', ':after', or null.
+ */
+CssLogic.getBindingElementAndPseudo = getBindingElementAndPseudo;
+
+/**
+ * Get the computed style on a node. Automatically handles reading
+ * computed styles on a ::before/::after element by reading on the
+ * parent node with the proper pseudo argument.
+ *
+ * @param {Node}
+ * @returns {CSSStyleDeclaration}
+ */
+CssLogic.getComputedStyle = function(node) {
+ if (
+ !node ||
+ Cu.isDeadWrapper(node) ||
+ node.nodeType !== nodeConstants.ELEMENT_NODE ||
+ !node.ownerGlobal
+ ) {
+ return null;
+ }
+
+ const { bindingElement, pseudo } = CssLogic.getBindingElementAndPseudo(node);
+
+ // For reasons that still escape us, pseudo-elements can sometimes be "unattached" (i.e.
+ // not have a parentNode defined). This seems to happen when a page is reloaded while
+ // the inspector is open. Bailing out here ensures that the inspector does not fail at
+ // presenting DOM nodes and CSS styles when this happens. This is a temporary measure.
+ // See bug 1506792.
+ if (!bindingElement) {
+ return null;
+ }
+
+ return node.ownerGlobal.getComputedStyle(bindingElement, pseudo);
+};
+
+/**
+ * Get a source for a stylesheet, taking into account embedded stylesheets
+ * for which we need to use document.defaultView.location.href rather than
+ * sheet.href
+ *
+ * @param {CSSStyleSheet} sheet the DOM object for the style sheet.
+ * @return {string} the address of the stylesheet.
+ */
+CssLogic.href = function(sheet) {
+ let href = sheet.href;
+ if (!href) {
+ href = sheet.ownerNode.ownerDocument.location;
+ }
+
+ return href;
+};
+
+/**
+ * Returns true if the given node has visited state.
+ */
+CssLogic.hasVisitedState = hasVisitedState;
+
+/**
+ * A safe way to access cached bits of information about a stylesheet.
+ *
+ * @constructor
+ * @param {CssLogic} cssLogic pointer to the CssLogic instance working with
+ * this CssSheet object.
+ * @param {CSSStyleSheet} domSheet reference to a DOM CSSStyleSheet object.
+ * @param {number} index tells the index/position of the stylesheet within the
+ * main document.
+ */
+function CssSheet(cssLogic, domSheet, index) {
+ this._cssLogic = cssLogic;
+ this.domSheet = domSheet;
+ this.index = this.authorSheet ? index : -100 * index;
+
+ // Cache of the sheets href. Cached by the getter.
+ this._href = null;
+ // Short version of href for use in select boxes etc. Cached by getter.
+ this._shortSource = null;
+
+ // null for uncached.
+ this._sheetAllowed = null;
+
+ // Cached CssRules from the given stylesheet.
+ this._rules = {};
+
+ this._ruleCount = -1;
+}
+
+CssSheet.prototype = {
+ _passId: null,
+ _agentSheet: null,
+ _authorSheet: null,
+ _userSheet: null,
+
+ /**
+ * Check if the stylesheet is an agent stylesheet (provided by the browser).
+ *
+ * @return {boolean} true if this is an agent stylesheet, false otherwise.
+ */
+ get agentSheet() {
+ if (this._agentSheet === null) {
+ this._agentSheet = isAgentStylesheet(this.domSheet);
+ }
+ return this._agentSheet;
+ },
+
+ /**
+ * Check if the stylesheet is an author stylesheet (provided by the content page).
+ *
+ * @return {boolean} true if this is an author stylesheet, false otherwise.
+ */
+ get authorSheet() {
+ if (this._authorSheet === null) {
+ this._authorSheet = isAuthorStylesheet(this.domSheet);
+ }
+ return this._authorSheet;
+ },
+
+ /**
+ * Check if the stylesheet is a user stylesheet (provided by userChrome.css or
+ * userContent.css).
+ *
+ * @return {boolean} true if this is a user stylesheet, false otherwise.
+ */
+ get userSheet() {
+ if (this._userSheet === null) {
+ this._userSheet = isUserStylesheet(this.domSheet);
+ }
+ return this._userSheet;
+ },
+
+ /**
+ * Check if the stylesheet is disabled or not.
+ * @return {boolean} true if this stylesheet is disabled, or false otherwise.
+ */
+ get disabled() {
+ return this.domSheet.disabled;
+ },
+
+ /**
+ * Get a source for a stylesheet, using CssLogic.href
+ *
+ * @return {string} the address of the stylesheet.
+ */
+ get href() {
+ if (this._href) {
+ return this._href;
+ }
+
+ this._href = CssLogic.href(this.domSheet);
+ return this._href;
+ },
+
+ /**
+ * Create a shorthand version of the href of a stylesheet.
+ *
+ * @return {string} the shorthand source of the stylesheet.
+ */
+ get shortSource() {
+ if (this._shortSource) {
+ return this._shortSource;
+ }
+
+ this._shortSource = shortSource(this.domSheet);
+ return this._shortSource;
+ },
+
+ /**
+ * Tells if the sheet is allowed or not by the current CssLogic.sourceFilter.
+ *
+ * @return {boolean} true if the stylesheet is allowed by the sourceFilter, or
+ * false otherwise.
+ */
+ get sheetAllowed() {
+ if (this._sheetAllowed !== null) {
+ return this._sheetAllowed;
+ }
+
+ this._sheetAllowed = true;
+
+ const filter = this._cssLogic.sourceFilter;
+ if (filter === FILTER.USER && !this.authorSheet) {
+ this._sheetAllowed = false;
+ }
+ if (filter !== FILTER.USER && filter !== FILTER.UA) {
+ this._sheetAllowed = filter === this.href;
+ }
+
+ return this._sheetAllowed;
+ },
+
+ /**
+ * Retrieve the number of rules in this stylesheet.
+ *
+ * @return {number} the number of CSSRule objects in this stylesheet.
+ */
+ get ruleCount() {
+ try {
+ return this._ruleCount > -1 ? this._ruleCount : this.getCssRules().length;
+ } catch (e) {
+ return 0;
+ }
+ },
+
+ /**
+ * Retrieve the array of css rules for this stylesheet.
+ *
+ * Accessing cssRules on a stylesheet that is not completely loaded can throw a
+ * DOMException (Bug 625013). This wrapper will return an empty array instead.
+ *
+ * @return {Array} array of css rules.
+ **/
+ getCssRules: function() {
+ try {
+ return this.domSheet.cssRules;
+ } catch (e) {
+ return [];
+ }
+ },
+
+ /**
+ * Retrieve a CssRule object for the given CSSStyleRule. The CssRule object is
+ * cached, such that subsequent retrievals return the same CssRule object for
+ * the same CSSStyleRule object.
+ *
+ * @param {CSSStyleRule} aDomRule the CSSStyleRule object for which you want a
+ * CssRule object.
+ * @return {CssRule} the cached CssRule object for the given CSSStyleRule
+ * object.
+ */
+ getRule: function(domRule) {
+ const cacheId = domRule.type + domRule.selectorText;
+
+ let rule = null;
+ let ruleFound = false;
+
+ if (cacheId in this._rules) {
+ for (rule of this._rules[cacheId]) {
+ if (rule.domRule === domRule) {
+ ruleFound = true;
+ break;
+ }
+ }
+ }
+
+ if (!ruleFound) {
+ if (!(cacheId in this._rules)) {
+ this._rules[cacheId] = [];
+ }
+
+ rule = new CssRule(this, domRule);
+ this._rules[cacheId].push(rule);
+ }
+
+ return rule;
+ },
+
+ toString: function() {
+ return "CssSheet[" + this.shortSource + "]";
+ },
+};
+
+/**
+ * Information about a single CSSStyleRule.
+ *
+ * @param {CSSSheet|null} cssSheet the CssSheet object of the stylesheet that
+ * holds the CSSStyleRule. If the rule comes from element.style, set this
+ * argument to null.
+ * @param {CSSStyleRule|object} domRule the DOM CSSStyleRule for which you want
+ * to cache data. If the rule comes from element.style, then provide
+ * an object of the form: {style: element.style}.
+ * @param {Element} [element] If the rule comes from element.style, then this
+ * argument must point to the element.
+ * @constructor
+ */
+function CssRule(cssSheet, domRule, element) {
+ this._cssSheet = cssSheet;
+ this.domRule = domRule;
+
+ const parentRule = domRule.parentRule;
+ if (parentRule && parentRule.type == CSSRule.MEDIA_RULE) {
+ this.mediaText = parentRule.media.mediaText;
+ }
+
+ if (this._cssSheet) {
+ // parse domRule.selectorText on call to this.selectors
+ this._selectors = null;
+ this.line = InspectorUtils.getRuleLine(this.domRule);
+ this.column = InspectorUtils.getRuleColumn(this.domRule);
+ this.source = this._cssSheet.shortSource + ":" + this.line;
+ if (this.mediaText) {
+ this.source += " @media " + this.mediaText;
+ }
+ this.href = this._cssSheet.href;
+ this.authorRule = this._cssSheet.authorSheet;
+ this.userRule = this._cssSheet.userSheet;
+ this.agentRule = this._cssSheet.agentSheet;
+ } else if (element) {
+ this._selectors = [new CssSelector(this, "@element.style", 0)];
+ this.line = -1;
+ this.source = l10n("rule.sourceElement");
+ this.href = "#";
+ this.authorRule = true;
+ this.userRule = false;
+ this.agentRule = false;
+ this.sourceElement = element;
+ }
+}
+
+CssRule.prototype = {
+ _passId: null,
+
+ mediaText: "",
+
+ get isMediaRule() {
+ return !!this.mediaText;
+ },
+
+ /**
+ * Check if the parent stylesheet is allowed by the CssLogic.sourceFilter.
+ *
+ * @return {boolean} true if the parent stylesheet is allowed by the current
+ * sourceFilter, or false otherwise.
+ */
+ get sheetAllowed() {
+ return this._cssSheet ? this._cssSheet.sheetAllowed : true;
+ },
+
+ /**
+ * Retrieve the parent stylesheet index/position in the viewed document.
+ *
+ * @return {number} the parent stylesheet index/position in the viewed
+ * document.
+ */
+ get sheetIndex() {
+ return this._cssSheet ? this._cssSheet.index : 0;
+ },
+
+ /**
+ * Retrieve the style property value from the current CSSStyleRule.
+ *
+ * @param {string} property the CSS property name for which you want the
+ * value.
+ * @return {string} the property value.
+ */
+ getPropertyValue: function(property) {
+ return this.domRule.style.getPropertyValue(property);
+ },
+
+ /**
+ * Retrieve the style property priority from the current CSSStyleRule.
+ *
+ * @param {string} property the CSS property name for which you want the
+ * priority.
+ * @return {string} the property priority.
+ */
+ getPropertyPriority: function(property) {
+ return this.domRule.style.getPropertyPriority(property);
+ },
+
+ /**
+ * Retrieve the list of CssSelector objects for each of the parsed selectors
+ * of the current CSSStyleRule.
+ *
+ * @return {array} the array hold the CssSelector objects.
+ */
+ get selectors() {
+ if (this._selectors) {
+ return this._selectors;
+ }
+
+ // Parse the CSSStyleRule.selectorText string.
+ this._selectors = [];
+
+ if (!this.domRule.selectorText) {
+ return this._selectors;
+ }
+
+ const selectors = CssLogic.getSelectors(this.domRule);
+
+ for (let i = 0, len = selectors.length; i < len; i++) {
+ this._selectors.push(new CssSelector(this, selectors[i], i));
+ }
+
+ return this._selectors;
+ },
+
+ toString: function() {
+ return "[CssRule " + this.domRule.selectorText + "]";
+ },
+};
+
+/**
+ * The CSS selector class allows us to document the ranking of various CSS
+ * selectors.
+ *
+ * @constructor
+ * @param {CssRule} cssRule the CssRule instance from where the selector comes.
+ * @param {string} selector The selector that we wish to investigate.
+ * @param {Number} index The index of the selector within it's rule.
+ */
+function CssSelector(cssRule, selector, index) {
+ this.cssRule = cssRule;
+ this.text = selector;
+ this.inlineStyle = this.text == "@element.style";
+ this._specificity = null;
+ this.selectorIndex = index;
+}
+
+exports.CssSelector = CssSelector;
+
+CssSelector.prototype = {
+ _matchId: null,
+
+ /**
+ * Retrieve the CssSelector source, which is the source of the CssSheet owning
+ * the selector.
+ *
+ * @return {string} the selector source.
+ */
+ get source() {
+ return this.cssRule.source;
+ },
+
+ /**
+ * Retrieve the CssSelector source element, which is the source of the CssRule
+ * owning the selector. This is only available when the CssSelector comes from
+ * an element.style.
+ *
+ * @return {string} the source element selector.
+ */
+ get sourceElement() {
+ return this.cssRule.sourceElement;
+ },
+
+ /**
+ * Retrieve the address of the CssSelector. This points to the address of the
+ * CssSheet owning this selector.
+ *
+ * @return {string} the address of the CssSelector.
+ */
+ get href() {
+ return this.cssRule.href;
+ },
+
+ /**
+ * Check if the selector comes from an agent stylesheet (provided by the browser).
+ *
+ * @return {boolean} true if this is an agent stylesheet, false otherwise.
+ */
+ get agentRule() {
+ return this.cssRule.agentRule;
+ },
+
+ /**
+ * Check if the selector comes from an author stylesheet (provided by the content page).
+ *
+ * @return {boolean} true if this is an author stylesheet, false otherwise.
+ */
+ get authorRule() {
+ return this.cssRule.authorRule;
+ },
+
+ /**
+ * Check if the selector comes from a user stylesheet (provided by userChrome.css or
+ * userContent.css).
+ *
+ * @return {boolean} true if this is a user stylesheet, false otherwise.
+ */
+ get userRule() {
+ return this.cssRule.userRule;
+ },
+
+ /**
+ * Check if the parent stylesheet is allowed by the CssLogic.sourceFilter.
+ *
+ * @return {boolean} true if the parent stylesheet is allowed by the current
+ * sourceFilter, or false otherwise.
+ */
+ get sheetAllowed() {
+ return this.cssRule.sheetAllowed;
+ },
+
+ /**
+ * Retrieve the parent stylesheet index/position in the viewed document.
+ *
+ * @return {number} the parent stylesheet index/position in the viewed
+ * document.
+ */
+ get sheetIndex() {
+ return this.cssRule.sheetIndex;
+ },
+
+ /**
+ * Retrieve the line of the parent CSSStyleRule in the parent CSSStyleSheet.
+ *
+ * @return {number} the line of the parent CSSStyleRule in the parent
+ * stylesheet.
+ */
+ get ruleLine() {
+ return this.cssRule.line;
+ },
+
+ /**
+ * Retrieve the column of the parent CSSStyleRule in the parent CSSStyleSheet.
+ *
+ * @return {number} the column of the parent CSSStyleRule in the parent
+ * stylesheet.
+ */
+ get ruleColumn() {
+ return this.cssRule.column;
+ },
+
+ /**
+ * Retrieve specificity information for the current selector.
+ *
+ * @see http://www.w3.org/TR/css3-selectors/#specificity
+ * @see http://www.w3.org/TR/CSS2/selector.html
+ *
+ * @return {Number} The selector's specificity.
+ */
+ get specificity() {
+ if (this.inlineStyle) {
+ // We can't ask specificity from DOMUtils as element styles don't provide
+ // CSSStyleRule interface DOMUtils expect. However, specificity of element
+ // style is constant, 1,0,0,0 or 0x40000000, just return the constant
+ // directly. @see http://www.w3.org/TR/CSS2/cascade.html#specificity
+ return 0x40000000;
+ }
+
+ if (typeof this._specificity !== "number") {
+ this._specificity = InspectorUtils.getSpecificity(
+ this.cssRule.domRule,
+ this.selectorIndex
+ );
+ }
+
+ return this._specificity;
+ },
+
+ toString: function() {
+ return this.text;
+ },
+};
+
+/**
+ * A cache of information about the matched rules, selectors and values attached
+ * to a CSS property, for the highlighted element.
+ *
+ * The heart of the CssPropertyInfo object is the _findMatchedSelectors()
+ * method. This are invoked when the PropertyView tries to access the
+ * .matchedSelectors array.
+ * Results are cached, for later reuse.
+ *
+ * @param {CssLogic} cssLogic Reference to the parent CssLogic instance
+ * @param {string} property The CSS property we are gathering information for
+ * @constructor
+ */
+function CssPropertyInfo(cssLogic, property) {
+ this._cssLogic = cssLogic;
+ this.property = property;
+ this._value = "";
+
+ // An array holding CssSelectorInfo objects for each of the matched selectors
+ // that are inside a CSS rule. Only rules that hold the this.property are
+ // counted. This includes rules that come from filtered stylesheets (those
+ // that have sheetAllowed = false).
+ this._matchedSelectors = null;
+}
+
+CssPropertyInfo.prototype = {
+ /**
+ * Retrieve the computed style value for the current property, for the
+ * highlighted element.
+ *
+ * @return {string} the computed style value for the current property, for the
+ * highlighted element.
+ */
+ get value() {
+ if (!this._value && this._cssLogic.computedStyle) {
+ try {
+ this._value = this._cssLogic.computedStyle.getPropertyValue(
+ this.property
+ );
+ } catch (ex) {
+ console.log("Error reading computed style for " + this.property);
+ console.log(ex);
+ }
+ }
+ return this._value;
+ },
+
+ /**
+ * Retrieve the array holding CssSelectorInfo objects for each of the matched
+ * selectors, from each of the matched rules. Only selectors coming from
+ * allowed stylesheets are included in the array.
+ *
+ * @return {array} the list of CssSelectorInfo objects of selectors that match
+ * the highlighted element and its parents.
+ */
+ get matchedSelectors() {
+ if (!this._matchedSelectors) {
+ this._findMatchedSelectors();
+ } else if (this.needRefilter) {
+ this._refilterSelectors();
+ }
+
+ return this._matchedSelectors;
+ },
+
+ /**
+ * Find the selectors that match the highlighted element and its parents.
+ * Uses CssLogic.processMatchedSelectors() to find the matched selectors,
+ * passing in a reference to CssPropertyInfo._processMatchedSelector() to
+ * create CssSelectorInfo objects, which we then sort
+ * @private
+ */
+ _findMatchedSelectors: function() {
+ this._matchedSelectors = [];
+ this.needRefilter = false;
+
+ this._cssLogic.processMatchedSelectors(this._processMatchedSelector, this);
+
+ // Sort the selectors by how well they match the given element.
+ this._matchedSelectors.sort(function(selectorInfo1, selectorInfo2) {
+ return selectorInfo1.compareTo(selectorInfo2);
+ });
+
+ // Now we know which of the matches is best, we can mark it BEST_MATCH.
+ if (
+ this._matchedSelectors.length > 0 &&
+ this._matchedSelectors[0].status > STATUS.UNMATCHED
+ ) {
+ this._matchedSelectors[0].status = STATUS.BEST;
+ }
+ },
+
+ /**
+ * Process a matched CssSelector object.
+ *
+ * @private
+ * @param {CssSelector} selector the matched CssSelector object.
+ * @param {STATUS} status the CssSelector match status.
+ */
+ _processMatchedSelector: function(selector, status, distance) {
+ const cssRule = selector.cssRule;
+ const value = cssRule.getPropertyValue(this.property);
+ if (
+ value &&
+ (status == STATUS.MATCHED ||
+ (status == STATUS.PARENT_MATCH &&
+ InspectorUtils.isInheritedProperty(this.property)))
+ ) {
+ const selectorInfo = new CssSelectorInfo(
+ selector,
+ this.property,
+ value,
+ status,
+ distance
+ );
+ this._matchedSelectors.push(selectorInfo);
+ }
+ },
+
+ /**
+ * Refilter the matched selectors array when the CssLogic.sourceFilter
+ * changes. This allows for quick filter changes.
+ * @private
+ */
+ _refilterSelectors: function() {
+ const passId = ++this._cssLogic._passId;
+
+ const iterator = function(selectorInfo) {
+ const cssRule = selectorInfo.selector.cssRule;
+ if (cssRule._passId != passId) {
+ cssRule._passId = passId;
+ }
+ };
+
+ if (this._matchedSelectors) {
+ this._matchedSelectors.forEach(iterator);
+ }
+
+ this.needRefilter = false;
+ },
+
+ toString: function() {
+ return "CssPropertyInfo[" + this.property + "]";
+ },
+};
+
+/**
+ * A class that holds information about a given CssSelector object.
+ *
+ * Instances of this class are given to CssHtmlTree in the array of matched
+ * selectors. Each such object represents a displayable row in the PropertyView
+ * objects. The information given by this object blends data coming from the
+ * CssSheet, CssRule and from the CssSelector that own this object.
+ *
+ * @param {CssSelector} selector The CssSelector object for which to
+ * present information.
+ * @param {string} property The property for which information should
+ * be retrieved.
+ * @param {string} value The property value from the CssRule that owns
+ * the selector.
+ * @param {STATUS} status The selector match status.
+ * @constructor
+ */
+function CssSelectorInfo(selector, property, value, status, distance) {
+ this.selector = selector;
+ this.property = property;
+ this.status = status;
+ this.distance = distance;
+ this.value = value;
+ const priority = this.selector.cssRule.getPropertyPriority(this.property);
+ this.important = priority === "important";
+}
+
+CssSelectorInfo.prototype = {
+ /**
+ * Retrieve the CssSelector source, which is the source of the CssSheet owning
+ * the selector.
+ *
+ * @return {string} the selector source.
+ */
+ get source() {
+ return this.selector.source;
+ },
+
+ /**
+ * Retrieve the CssSelector source element, which is the source of the CssRule
+ * owning the selector. This is only available when the CssSelector comes from
+ * an element.style.
+ *
+ * @return {string} the source element selector.
+ */
+ get sourceElement() {
+ return this.selector.sourceElement;
+ },
+
+ /**
+ * Retrieve the address of the CssSelector. This points to the address of the
+ * CssSheet owning this selector.
+ *
+ * @return {string} the address of the CssSelector.
+ */
+ get href() {
+ return this.selector.href;
+ },
+
+ /**
+ * Check if the CssSelector comes from element.style or not.
+ *
+ * @return {boolean} true if the CssSelector comes from element.style, or
+ * false otherwise.
+ */
+ get inlineStyle() {
+ return this.selector.inlineStyle;
+ },
+
+ /**
+ * Retrieve specificity information for the current selector.
+ *
+ * @return {object} an object holding specificity information for the current
+ * selector.
+ */
+ get specificity() {
+ return this.selector.specificity;
+ },
+
+ /**
+ * Retrieve the parent stylesheet index/position in the viewed document.
+ *
+ * @return {number} the parent stylesheet index/position in the viewed
+ * document.
+ */
+ get sheetIndex() {
+ return this.selector.sheetIndex;
+ },
+
+ /**
+ * Check if the parent stylesheet is allowed by the CssLogic.sourceFilter.
+ *
+ * @return {boolean} true if the parent stylesheet is allowed by the current
+ * sourceFilter, or false otherwise.
+ */
+ get sheetAllowed() {
+ return this.selector.sheetAllowed;
+ },
+
+ /**
+ * Retrieve the line of the parent CSSStyleRule in the parent CSSStyleSheet.
+ *
+ * @return {number} the line of the parent CSSStyleRule in the parent
+ * stylesheet.
+ */
+ get ruleLine() {
+ return this.selector.ruleLine;
+ },
+
+ /**
+ * Retrieve the column of the parent CSSStyleRule in the parent CSSStyleSheet.
+ *
+ * @return {number} the column of the parent CSSStyleRule in the parent
+ * stylesheet.
+ */
+ get ruleColumn() {
+ return this.selector.ruleColumn;
+ },
+
+ /**
+ * Check if the selector comes from a browser-provided stylesheet.
+ *
+ * @return {boolean} true if the selector comes from a browser-provided
+ * stylesheet, or false otherwise.
+ */
+ get agentRule() {
+ return this.selector.agentRule;
+ },
+
+ /**
+ * Check if the selector comes from a webpage-provided stylesheet.
+ *
+ * @return {boolean} true if the selector comes from a webpage-provided
+ * stylesheet, or false otherwise.
+ */
+ get authorRule() {
+ return this.selector.authorRule;
+ },
+
+ /**
+ * Check if the selector comes from a user stylesheet (userChrome.css or
+ * userContent.css).
+ *
+ * @return {boolean} true if the selector comes from a webpage-provided
+ * stylesheet, or false otherwise.
+ */
+ get userRule() {
+ return this.selector.userRule;
+ },
+
+ /**
+ * Compare the current CssSelectorInfo instance to another instance, based on
+ * the CSS cascade (see https://www.w3.org/TR/css-cascade-4/#cascading):
+ *
+ * The cascade sorts declarations according to the following criteria, in
+ * descending order of priority:
+ *
+ * - Rules targetting a node directly must always win over rules targetting an
+ * ancestor.
+ *
+ * - Origin and Importance
+ * The origin of a declaration is based on where it comes from and its
+ * importance is whether or not it is declared !important (see below). For
+ * our purposes here we can safely ignore Transition declarations and
+ * Animation declarations.
+ * The precedence of the various origins is, in descending order:
+ * - Transition declarations (ignored)
+ * - Important user agent declarations (User-Agent & !important)
+ * - Important user declarations (User & !important)
+ * - Important author declarations (Author & !important)
+ * - Animation declarations (ignored)
+ * - Normal author declarations (Author, normal weight)
+ * - Normal user declarations (User, normal weight)
+ * - Normal user agent declarations (User-Agent, normal weight)
+ *
+ * - Specificity (see https://www.w3.org/TR/selectors/#specificity)
+ * - A selector’s specificity is calculated for a given element as follows:
+ * - count the number of ID selectors in the selector (= A)
+ * - count the number of class selectors, attributes selectors, and
+ * pseudo-classes in the selector (= B)
+ * - count the number of type selectors and pseudo-elements in the
+ * selector (= C)
+ * - ignore the universal selector
+ * - So "UL OL LI.red" has a specificity of a=0 b=1 c=3.
+ *
+ * - Order of Appearance
+ * - The last declaration in document order wins. For this purpose:
+ * - Declarations from imported style sheets are ordered as if their style
+ * sheets were substituted in place of the @import rule.
+ * - Declarations from style sheets independently linked by the
+ * originating document are treated as if they were concatenated in
+ * linking order, as determined by the host document language.
+ * - Declarations from style attributes are ordered according to the
+ * document order of the element the style attribute appears on, and are
+ * all placed after any style sheets.
+ * - We use three methods to calculate this:
+ * - Sheet index
+ * - Rule line
+ * - Rule column
+ *
+ * @param {CssSelectorInfo} that
+ * The instance to compare ourselves against.
+ * @return {Number}
+ * -1, 0, 1 depending on how that compares with this.
+ */
+ compareTo: function(that) {
+ let current = null;
+
+ // Rules targetting the node must always win over rules targetting a node's
+ // ancestor.
+ current = this.compare(that, "distance", COMPAREMODE.INTEGER);
+ if (current) {
+ return current;
+ }
+
+ if (this.important) {
+ // User-Agent & !important
+ // User & !important
+ // Author & !important
+ for (const propName of ["agentRule", "userRule", "authorRule"]) {
+ current = this.compare(that, propName, COMPAREMODE.BOOLEAN);
+ if (current) {
+ return current;
+ }
+ }
+ }
+
+ // Author, normal weight
+ // User, normal weight
+ // User-Agent, normal weight
+ for (const propName of ["authorRule", "userRule", "agentRule"]) {
+ current = this.compare(that, propName, COMPAREMODE.BOOLEAN);
+ if (current) {
+ return current;
+ }
+ }
+
+ // Specificity
+ // Sheet index
+ // Rule line
+ // Rule column
+ for (const propName of [
+ "specificity",
+ "sheetIndex",
+ "ruleLine",
+ "ruleColumn",
+ ]) {
+ current = this.compare(that, propName, COMPAREMODE.INTEGER);
+ if (current) {
+ return current;
+ }
+ }
+
+ // A rule has been compared against itself so return 0.
+ return 0;
+ },
+
+ compare: function(that, propertyName, type) {
+ switch (type) {
+ case COMPAREMODE.BOOLEAN:
+ if (this[propertyName] && !that[propertyName]) {
+ return -1;
+ }
+ if (!this[propertyName] && that[propertyName]) {
+ return 1;
+ }
+ break;
+ case COMPAREMODE.INTEGER:
+ if (this[propertyName] > that[propertyName]) {
+ return -1;
+ }
+ if (this[propertyName] < that[propertyName]) {
+ return 1;
+ }
+ break;
+ }
+ return 0;
+ },
+
+ toString: function() {
+ return this.selector + " -> " + this.value;
+ },
+};
diff --git a/devtools/server/actors/inspector/custom-element-watcher.js b/devtools/server/actors/inspector/custom-element-watcher.js
new file mode 100644
index 0000000000..0732585e04
--- /dev/null
+++ b/devtools/server/actors/inspector/custom-element-watcher.js
@@ -0,0 +1,146 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const InspectorUtils = require("InspectorUtils");
+const EventEmitter = require("devtools/shared/event-emitter");
+
+/**
+ * The CustomElementWatcher can be used to be notified if a custom element definition
+ * is created for a node.
+ *
+ * When a custom element is defined for a monitored name, an "element-defined" event is
+ * fired with the following Object argument:
+ * - {String} name: name of the custom element defined
+ * - {Set} Set of impacted node actors
+ */
+class CustomElementWatcher extends EventEmitter {
+ constructor(chromeEventHandler) {
+ super();
+
+ this.chromeEventHandler = chromeEventHandler;
+ this._onCustomElementDefined = this._onCustomElementDefined.bind(this);
+ this.chromeEventHandler.addEventListener(
+ "customelementdefined",
+ this._onCustomElementDefined
+ );
+
+ /**
+ * Each window keeps its own custom element registry, all of them are watched
+ * separately. The struture of the watchedRegistries is as follows
+ *
+ * WeakMap(
+ * registry -> Map (
+ * name -> Set(NodeActors)
+ * )
+ * )
+ */
+ this.watchedRegistries = new WeakMap();
+ }
+
+ destroy() {
+ this.watchedRegistries = null;
+ this.chromeEventHandler.removeEventListener(
+ "customelementdefined",
+ this._onCustomElementDefined
+ );
+ }
+
+ /**
+ * Watch for custom element definitions matching the name of the provided NodeActor.
+ */
+ manageNode(nodeActor) {
+ if (!this._isValidNode(nodeActor)) {
+ return;
+ }
+
+ if (!this._shouldWatchDefinition(nodeActor)) {
+ return;
+ }
+
+ const registry = nodeActor.rawNode.ownerGlobal.customElements;
+ const registryMap = this._getMapForRegistry(registry);
+
+ const name = nodeActor.rawNode.localName;
+ const actorsSet = this._getActorsForName(name, registryMap);
+ actorsSet.add(nodeActor);
+ }
+
+ /**
+ * Stop watching the provided NodeActor.
+ */
+ unmanageNode(nodeActor) {
+ if (!this._isValidNode(nodeActor)) {
+ return;
+ }
+
+ const win = nodeActor.rawNode.ownerGlobal;
+ const registry = win.customElements;
+ const registryMap = this._getMapForRegistry(registry);
+ const name = nodeActor.rawNode.localName;
+ if (registryMap.has(name)) {
+ registryMap.get(name).delete(nodeActor);
+ }
+ }
+
+ /**
+ * Retrieve the map of name->nodeActors for a given CustomElementsRegistry.
+ * Will create the map if not created yet.
+ */
+ _getMapForRegistry(registry) {
+ if (!this.watchedRegistries.has(registry)) {
+ this.watchedRegistries.set(registry, new Map());
+ }
+ return this.watchedRegistries.get(registry);
+ }
+
+ /**
+ * Retrieve the set of nodeActors for a given name and registry.
+ * Will create the set if not created yet.
+ */
+ _getActorsForName(name, registryMap) {
+ if (!registryMap.has(name)) {
+ registryMap.set(name, new Set());
+ }
+ return registryMap.get(name);
+ }
+
+ _shouldWatchDefinition(nodeActor) {
+ const doc = nodeActor.rawNode.ownerDocument;
+ const namespaceURI = doc.documentElement.namespaceURI;
+ const name = nodeActor.rawNode.localName;
+ const isValidName = InspectorUtils.isCustomElementName(name, namespaceURI);
+
+ const customElements = doc.defaultView.customElements;
+ return isValidName && !customElements.get(name);
+ }
+
+ _onCustomElementDefined(event) {
+ const doc = event.target;
+ const registry = doc.defaultView.customElements;
+ const registryMap = this._getMapForRegistry(registry);
+
+ const name = event.detail;
+ const actors = this._getActorsForName(name, registryMap);
+ this.emit("element-defined", { name, actors });
+ registryMap.delete(name);
+ }
+
+ /**
+ * Some nodes (e.g. inside of <template> tags) don't have a documentElement or an
+ * ownerGlobal and can't be watched by this helper.
+ */
+ _isValidNode(nodeActor) {
+ const node = nodeActor.rawNode;
+ return (
+ !Cu.isDeadWrapper(node) &&
+ node.ownerGlobal &&
+ node.ownerDocument?.documentElement
+ );
+ }
+}
+
+exports.CustomElementWatcher = CustomElementWatcher;
diff --git a/devtools/server/actors/inspector/document-walker.js b/devtools/server/actors/inspector/document-walker.js
new file mode 100644
index 0000000000..d44bae42d1
--- /dev/null
+++ b/devtools/server/actors/inspector/document-walker.js
@@ -0,0 +1,223 @@
+/* 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";
+
+const { Cc, Ci, Cu } = require("chrome");
+
+loader.lazyRequireGetter(
+ this,
+ "isShadowRoot",
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "nodeFilterConstants",
+ "devtools/shared/dom-node-filter-constants"
+);
+loader.lazyRequireGetter(
+ this,
+ "standardTreeWalkerFilter",
+ "devtools/server/actors/inspector/utils",
+ true
+);
+
+// SKIP_TO_* arguments are used with the DocumentWalker, driving the strategy to use if
+// the starting node is incompatible with the filter function of the walker.
+const SKIP_TO_PARENT = "SKIP_TO_PARENT";
+const SKIP_TO_SIBLING = "SKIP_TO_SIBLING";
+
+/**
+ * Wrapper for inDeepTreeWalker. Adds filtering to the traversal methods.
+ * See inDeepTreeWalker for more information about the methods.
+ *
+ * @param {DOMNode} node
+ * @param {Window} rootWin
+ * @param {Object}
+ * - {Number} whatToShow
+ * See nodeFilterConstants / inIDeepTreeWalker for options.
+ * - {Function} filter
+ * A custom filter function Taking in a DOMNode and returning an Int. See
+ * WalkerActor.nodeFilter for an example.
+ * - {String} skipTo
+ * Either SKIP_TO_PARENT or SKIP_TO_SIBLING. If the provided node is not
+ * compatible with the filter function for this walker, try to find a compatible
+ * one either in the parents or in the siblings of the node.
+ * - {Boolean} showAnonymousContent
+ * Pass true to let the walker return and traverse anonymous content.
+ * When navigating host elements to which shadow DOM is attached, the light tree
+ * will be visible only to a walker with showAnonymousContent=false. The shadow
+ * tree will only be visible to a walker with showAnonymousContent=true.
+ */
+function DocumentWalker(
+ node,
+ rootWin,
+ {
+ whatToShow = nodeFilterConstants.SHOW_ALL,
+ filter = standardTreeWalkerFilter,
+ skipTo = SKIP_TO_PARENT,
+ showAnonymousContent = true,
+ } = {}
+) {
+ if (Cu.isDeadWrapper(rootWin) || !rootWin.location) {
+ throw new Error("Got an invalid root window in DocumentWalker");
+ }
+
+ this.walker = Cc["@mozilla.org/inspector/deep-tree-walker;1"].createInstance(
+ Ci.inIDeepTreeWalker
+ );
+ this.walker.showAnonymousContent = showAnonymousContent;
+ this.walker.showSubDocuments = true;
+ this.walker.showDocumentsAsNodes = true;
+ this.walker.init(rootWin.document, whatToShow);
+ this.filter = filter;
+
+ // Make sure that the walker knows about the initial node (which could
+ // be skipped due to a filter).
+ this.walker.currentNode = this.getStartingNode(node, skipTo);
+}
+
+DocumentWalker.prototype = {
+ get whatToShow() {
+ return this.walker.whatToShow;
+ },
+ get currentNode() {
+ return this.walker.currentNode;
+ },
+ set currentNode(val) {
+ this.walker.currentNode = val;
+ },
+
+ parentNode: function() {
+ if (isShadowRoot(this.currentNode)) {
+ this.currentNode = this.currentNode.host;
+ return this.currentNode;
+ }
+
+ const parentNode = this.currentNode.parentNode;
+ // deep-tree-walker currently does not return shadowRoot elements as parentNodes.
+ if (parentNode && isShadowRoot(parentNode)) {
+ this.currentNode = parentNode;
+ return this.currentNode;
+ }
+ return this.walker.parentNode();
+ },
+
+ nextNode: function() {
+ const node = this.walker.currentNode;
+ if (!node) {
+ return null;
+ }
+
+ let nextNode = this.walker.nextNode();
+ while (nextNode && this.isSkippedNode(nextNode)) {
+ nextNode = this.walker.nextNode();
+ }
+
+ return nextNode;
+ },
+
+ firstChild: function() {
+ const node = this.walker.currentNode;
+ if (!node) {
+ return null;
+ }
+
+ let firstChild = this.walker.firstChild();
+ while (firstChild && this.isSkippedNode(firstChild)) {
+ firstChild = this.walker.nextSibling();
+ }
+
+ return firstChild;
+ },
+
+ lastChild: function() {
+ const node = this.walker.currentNode;
+ if (!node) {
+ return null;
+ }
+
+ let lastChild = this.walker.lastChild();
+ while (lastChild && this.isSkippedNode(lastChild)) {
+ lastChild = this.walker.previousSibling();
+ }
+
+ return lastChild;
+ },
+
+ previousSibling: function() {
+ let node = this.walker.previousSibling();
+ while (node && this.isSkippedNode(node)) {
+ node = this.walker.previousSibling();
+ }
+ return node;
+ },
+
+ nextSibling: function() {
+ let node = this.walker.nextSibling();
+ while (node && this.isSkippedNode(node)) {
+ node = this.walker.nextSibling();
+ }
+ return node;
+ },
+
+ getStartingNode: function(node, skipTo) {
+ // Keep a reference on the starting node in case we can't find a node compatible with
+ // the filter.
+ const startingNode = node;
+
+ if (skipTo === SKIP_TO_PARENT) {
+ while (node && this.isSkippedNode(node)) {
+ node = node.parentNode;
+ }
+ } else if (skipTo === SKIP_TO_SIBLING) {
+ node = this.getClosestAcceptedSibling(node);
+ }
+
+ return node || startingNode;
+ },
+
+ /**
+ * Loop on all of the provided node siblings until finding one that is compliant with
+ * the filter function.
+ */
+ getClosestAcceptedSibling: function(node) {
+ if (this.filter(node) === nodeFilterConstants.FILTER_ACCEPT) {
+ // node is already valid, return immediately.
+ return node;
+ }
+
+ // Loop on starting node siblings.
+ let previous = node;
+ let next = node;
+ while (previous || next) {
+ previous = previous?.previousSibling;
+ next = next?.nextSibling;
+
+ if (
+ previous &&
+ this.filter(previous) === nodeFilterConstants.FILTER_ACCEPT
+ ) {
+ // A valid node was found in the previous siblings of the node.
+ return previous;
+ }
+
+ if (next && this.filter(next) === nodeFilterConstants.FILTER_ACCEPT) {
+ // A valid node was found in the next siblings of the node.
+ return next;
+ }
+ }
+
+ return null;
+ },
+
+ isSkippedNode: function(node) {
+ return this.filter(node) === nodeFilterConstants.FILTER_SKIP;
+ },
+};
+
+exports.DocumentWalker = DocumentWalker;
+exports.SKIP_TO_PARENT = SKIP_TO_PARENT;
+exports.SKIP_TO_SIBLING = SKIP_TO_SIBLING;
diff --git a/devtools/server/actors/inspector/event-collector.js b/devtools/server/actors/inspector/event-collector.js
new file mode 100644
index 0000000000..551b66523a
--- /dev/null
+++ b/devtools/server/actors/inspector/event-collector.js
@@ -0,0 +1,1065 @@
+/* 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/. */
+
+// This file contains event collectors that are then used by developer tools in
+// order to find information about events affecting an HTML element.
+
+"use strict";
+
+const { Cu } = require("chrome");
+const Services = require("Services");
+const {
+ isAfterPseudoElement,
+ isBeforePseudoElement,
+ isMarkerPseudoElement,
+ isNativeAnonymous,
+} = require("devtools/shared/layout/utils");
+const Debugger = require("Debugger");
+const {
+ EXCLUDED_LISTENER,
+} = require("devtools/server/actors/inspector/constants");
+
+// eslint-disable-next-line
+const JQUERY_LIVE_REGEX = /return typeof \w+.*.event\.triggered[\s\S]*\.event\.(dispatch|handle).*arguments/;
+
+const REACT_EVENT_NAMES = [
+ "onAbort",
+ "onAnimationEnd",
+ "onAnimationIteration",
+ "onAnimationStart",
+ "onAuxClick",
+ "onBeforeInput",
+ "onBlur",
+ "onCanPlay",
+ "onCanPlayThrough",
+ "onCancel",
+ "onChange",
+ "onClick",
+ "onClose",
+ "onCompositionEnd",
+ "onCompositionStart",
+ "onCompositionUpdate",
+ "onContextMenu",
+ "onCopy",
+ "onCut",
+ "onDoubleClick",
+ "onDrag",
+ "onDragEnd",
+ "onDragEnter",
+ "onDragExit",
+ "onDragLeave",
+ "onDragOver",
+ "onDragStart",
+ "onDrop",
+ "onDurationChange",
+ "onEmptied",
+ "onEncrypted",
+ "onEnded",
+ "onError",
+ "onFocus",
+ "onGotPointerCapture",
+ "onInput",
+ "onInvalid",
+ "onKeyDown",
+ "onKeyPress",
+ "onKeyUp",
+ "onLoad",
+ "onLoadStart",
+ "onLoadedData",
+ "onLoadedMetadata",
+ "onLostPointerCapture",
+ "onMouseDown",
+ "onMouseEnter",
+ "onMouseLeave",
+ "onMouseMove",
+ "onMouseOut",
+ "onMouseOver",
+ "onMouseUp",
+ "onPaste",
+ "onPause",
+ "onPlay",
+ "onPlaying",
+ "onPointerCancel",
+ "onPointerDown",
+ "onPointerEnter",
+ "onPointerLeave",
+ "onPointerMove",
+ "onPointerOut",
+ "onPointerOver",
+ "onPointerUp",
+ "onProgress",
+ "onRateChange",
+ "onReset",
+ "onScroll",
+ "onSeeked",
+ "onSeeking",
+ "onSelect",
+ "onStalled",
+ "onSubmit",
+ "onSuspend",
+ "onTimeUpdate",
+ "onToggle",
+ "onTouchCancel",
+ "onTouchEnd",
+ "onTouchMove",
+ "onTouchStart",
+ "onTransitionEnd",
+ "onVolumeChange",
+ "onWaiting",
+ "onWheel",
+ "onAbortCapture",
+ "onAnimationEndCapture",
+ "onAnimationIterationCapture",
+ "onAnimationStartCapture",
+ "onAuxClickCapture",
+ "onBeforeInputCapture",
+ "onBlurCapture",
+ "onCanPlayCapture",
+ "onCanPlayThroughCapture",
+ "onCancelCapture",
+ "onChangeCapture",
+ "onClickCapture",
+ "onCloseCapture",
+ "onCompositionEndCapture",
+ "onCompositionStartCapture",
+ "onCompositionUpdateCapture",
+ "onContextMenuCapture",
+ "onCopyCapture",
+ "onCutCapture",
+ "onDoubleClickCapture",
+ "onDragCapture",
+ "onDragEndCapture",
+ "onDragEnterCapture",
+ "onDragExitCapture",
+ "onDragLeaveCapture",
+ "onDragOverCapture",
+ "onDragStartCapture",
+ "onDropCapture",
+ "onDurationChangeCapture",
+ "onEmptiedCapture",
+ "onEncryptedCapture",
+ "onEndedCapture",
+ "onErrorCapture",
+ "onFocusCapture",
+ "onGotPointerCaptureCapture",
+ "onInputCapture",
+ "onInvalidCapture",
+ "onKeyDownCapture",
+ "onKeyPressCapture",
+ "onKeyUpCapture",
+ "onLoadCapture",
+ "onLoadStartCapture",
+ "onLoadedDataCapture",
+ "onLoadedMetadataCapture",
+ "onLostPointerCaptureCapture",
+ "onMouseDownCapture",
+ "onMouseEnterCapture",
+ "onMouseLeaveCapture",
+ "onMouseMoveCapture",
+ "onMouseOutCapture",
+ "onMouseOverCapture",
+ "onMouseUpCapture",
+ "onPasteCapture",
+ "onPauseCapture",
+ "onPlayCapture",
+ "onPlayingCapture",
+ "onPointerCancelCapture",
+ "onPointerDownCapture",
+ "onPointerEnterCapture",
+ "onPointerLeaveCapture",
+ "onPointerMoveCapture",
+ "onPointerOutCapture",
+ "onPointerOverCapture",
+ "onPointerUpCapture",
+ "onProgressCapture",
+ "onRateChangeCapture",
+ "onResetCapture",
+ "onScrollCapture",
+ "onSeekedCapture",
+ "onSeekingCapture",
+ "onSelectCapture",
+ "onStalledCapture",
+ "onSubmitCapture",
+ "onSuspendCapture",
+ "onTimeUpdateCapture",
+ "onToggleCapture",
+ "onTouchCancelCapture",
+ "onTouchEndCapture",
+ "onTouchMoveCapture",
+ "onTouchStartCapture",
+ "onTransitionEndCapture",
+ "onVolumeChangeCapture",
+ "onWaitingCapture",
+ "onWheelCapture",
+];
+
+/**
+ * The base class that all the enent collectors should be based upon.
+ */
+class MainEventCollector {
+ /**
+ * We allow displaying chrome events if the page is chrome or if
+ * `devtools.chrome.enabled = true`.
+ */
+ get chromeEnabled() {
+ if (typeof this._chromeEnabled === "undefined") {
+ this._chromeEnabled = Services.prefs.getBoolPref(
+ "devtools.chrome.enabled"
+ );
+ }
+
+ return this._chromeEnabled;
+ }
+
+ /**
+ * Check if a node has any event listeners attached. Please do not override
+ * this method... your getListeners() implementation needs to have the
+ * following signature:
+ * `getListeners(node, {checkOnly} = {})`
+ *
+ * @param {DOMNode} node
+ * The not for which we want to check for event listeners.
+ * @return {Boolean}
+ * true if the node has event listeners, false otherwise.
+ */
+ hasListeners(node) {
+ return this.getListeners(node, {
+ checkOnly: true,
+ });
+ }
+
+ /**
+ * Get all listeners for a node. This method must be overridden.
+ *
+ * @param {DOMNode} node
+ * The not for which we want to get event listeners.
+ * @param {Object} options
+ * An object for passing in options.
+ * @param {Boolean} [options.checkOnly = false]
+ * Don't get any listeners but return true when the first event is
+ * found.
+ * @return {Array}
+ * An array of event handlers.
+ */
+ getListeners(node, { checkOnly }) {
+ throw new Error("You have to implement the method getListeners()!");
+ }
+
+ /**
+ * Get unfiltered DOM Event listeners for a node.
+ * NOTE: These listeners may contain invalid events and events based
+ * on C++ rather than JavaScript.
+ *
+ * @param {DOMNode} node
+ * The node for which we want to get unfiltered event listeners.
+ * @return {Array}
+ * An array of unfiltered event listeners or an empty array
+ */
+ getDOMListeners(node) {
+ let listeners;
+ if (
+ typeof node.nodeName !== "undefined" &&
+ node.nodeName.toLowerCase() === "html"
+ ) {
+ const winListeners =
+ Services.els.getListenerInfoFor(node.ownerGlobal) || [];
+ const docElementListeners = Services.els.getListenerInfoFor(node) || [];
+ const docListeners =
+ Services.els.getListenerInfoFor(node.parentNode) || [];
+
+ listeners = [...winListeners, ...docElementListeners, ...docListeners];
+ } else {
+ listeners = Services.els.getListenerInfoFor(node) || [];
+ }
+
+ return listeners.filter(listener => {
+ const obj = this.unwrap(listener.listenerObject);
+ return !obj || !obj[EXCLUDED_LISTENER];
+ });
+ }
+
+ getJQuery(node) {
+ if (Cu.isDeadWrapper(node)) {
+ return null;
+ }
+
+ const global = this.unwrap(node.ownerGlobal);
+ if (!global) {
+ return null;
+ }
+
+ const hasJQuery = global.jQuery?.fn?.jquery;
+
+ if (hasJQuery) {
+ return global.jQuery;
+ }
+ return null;
+ }
+
+ unwrap(obj) {
+ return Cu.isXrayWrapper(obj) ? obj.wrappedJSObject : obj;
+ }
+
+ isChromeHandler(handler) {
+ try {
+ const handlerPrincipal = Cu.getObjectPrincipal(handler);
+
+ // Chrome codebase may register listeners on the page from a frame script or
+ // JSM <video> tags may also report internal listeners, but they won't be
+ // coming from the system principal. Instead, they will be using an expanded
+ // principal.
+ return (
+ handlerPrincipal.isSystemPrincipal ||
+ handlerPrincipal.isExpandedPrincipal
+ );
+ } catch (e) {
+ // Anything from a dead object to a CSP error can leave us here so let's
+ // return false so that we can fail gracefully.
+ return false;
+ }
+ }
+}
+
+/**
+ * Get or detect DOM events. These may include DOM events created by libraries
+ * that enable their custom events to work. At this point we are unable to
+ * effectively filter them as they may be proxied or wrapped. Although we know
+ * there is an event, we may not know the true contents until it goes
+ * through `processHandlerForEvent()`.
+ */
+class DOMEventCollector extends MainEventCollector {
+ getListeners(node, { checkOnly } = {}) {
+ const handlers = [];
+ const listeners = this.getDOMListeners(node);
+
+ for (const listener of listeners) {
+ // Ignore listeners without a type, e.g.
+ // node.addEventListener("", function() {})
+ if (!listener.type) {
+ continue;
+ }
+
+ // Get the listener object, either a Function or an Object.
+ const obj = listener.listenerObject;
+
+ // Ignore listeners without any listener, e.g.
+ // node.addEventListener("mouseover", null);
+ if (!obj) {
+ continue;
+ }
+
+ let handler = null;
+
+ // An object without a valid handleEvent is not a valid listener.
+ if (typeof obj === "object") {
+ const unwrapped = this.unwrap(obj);
+ if (typeof unwrapped.handleEvent === "function") {
+ handler = Cu.unwaiveXrays(unwrapped.handleEvent);
+ }
+ } else if (typeof obj === "function") {
+ // Ignore DOM events used to trigger jQuery events as they are only
+ // useful to the developers of the jQuery library.
+ if (JQUERY_LIVE_REGEX.test(obj.toString())) {
+ continue;
+ }
+ // Otherwise, the other valid listener type is function.
+ handler = obj;
+ }
+
+ // Ignore listeners that have no handler.
+ if (!handler) {
+ continue;
+ }
+
+ // If we shouldn't be showing chrome events due to context and this is a
+ // chrome handler we can ignore it.
+ if (!this.chromeEnabled && this.isChromeHandler(handler)) {
+ continue;
+ }
+
+ // If this is checking if a node has any listeners then we have found one
+ // so return now.
+ if (checkOnly) {
+ return true;
+ }
+
+ const eventInfo = {
+ capturing: listener.capturing,
+ type: listener.type,
+ handler: handler,
+ };
+
+ handlers.push(eventInfo);
+ }
+
+ // If this is checking if a node has any listeners then none were found so
+ // return false.
+ if (checkOnly) {
+ return false;
+ }
+
+ return handlers;
+ }
+}
+
+/**
+ * Get or detect jQuery events.
+ */
+class JQueryEventCollector extends MainEventCollector {
+ // eslint-disable-next-line complexity
+ getListeners(node, { checkOnly } = {}) {
+ const jQuery = this.getJQuery(node);
+ const handlers = [];
+
+ // If jQuery is not on the page, if this is an anonymous node or a pseudo
+ // element we need to return early.
+ if (
+ !jQuery ||
+ isNativeAnonymous(node) ||
+ isMarkerPseudoElement(node) ||
+ isBeforePseudoElement(node) ||
+ isAfterPseudoElement(node)
+ ) {
+ if (checkOnly) {
+ return false;
+ }
+ return handlers;
+ }
+
+ let eventsObj = null;
+ const data = jQuery._data || jQuery.data;
+
+ if (data) {
+ // jQuery 1.2+
+ try {
+ eventsObj = data(node, "events");
+ } catch (e) {
+ // We have no access to a JS object. This is probably due to a CORS
+ // violation. Using try / catch is the only way to avoid this error.
+ }
+ } else {
+ // JQuery 1.0 & 1.1
+ let entry;
+ try {
+ entry = entry = jQuery(node)[0];
+ } catch (e) {
+ // We have no access to a JS object. This is probably due to a CORS
+ // violation. Using try / catch is the only way to avoid this error.
+ }
+
+ if (!entry || !entry.events) {
+ if (checkOnly) {
+ return false;
+ }
+ return handlers;
+ }
+
+ eventsObj = entry.events;
+ }
+
+ if (eventsObj) {
+ for (const [type, events] of Object.entries(eventsObj)) {
+ for (const [, event] of Object.entries(events)) {
+ // Skip events that are part of jQueries internals.
+ if (node.nodeType == node.DOCUMENT_NODE && event.selector) {
+ continue;
+ }
+
+ if (typeof event === "function" || typeof event === "object") {
+ // If we shouldn't be showing chrome events due to context and this
+ // is a chrome handler we can ignore it.
+ const handler = event.handler || event;
+ if (!this.chromeEnabled && this.isChromeHandler(handler)) {
+ continue;
+ }
+
+ if (checkOnly) {
+ return true;
+ }
+
+ const eventInfo = {
+ type: type,
+ handler: handler,
+ tags: "jQuery",
+ hide: {
+ capturing: true,
+ dom0: true,
+ },
+ };
+
+ handlers.push(eventInfo);
+ }
+ }
+ }
+ }
+
+ if (checkOnly) {
+ return false;
+ }
+ return handlers;
+ }
+}
+
+/**
+ * Get or detect jQuery live events.
+ */
+class JQueryLiveEventCollector extends MainEventCollector {
+ // eslint-disable-next-line complexity
+ getListeners(node, { checkOnly } = {}) {
+ const jQuery = this.getJQuery(node);
+ const handlers = [];
+
+ if (!jQuery) {
+ if (checkOnly) {
+ return false;
+ }
+ return handlers;
+ }
+
+ const data = jQuery._data || jQuery.data;
+
+ if (data) {
+ // Live events are added to the document and bubble up to all elements.
+ // Any element matching the specified selector will trigger the live
+ // event.
+ const win = this.unwrap(node.ownerGlobal);
+ let events = null;
+
+ try {
+ events = data(win.document, "events");
+ } catch (e) {
+ // We have no access to a JS object. This is probably due to a CORS
+ // violation. Using try / catch is the only way to avoid this error.
+ }
+
+ if (events) {
+ for (const [, eventHolder] of Object.entries(events)) {
+ for (const [idx, event] of Object.entries(eventHolder)) {
+ if (typeof idx !== "string" || isNaN(parseInt(idx, 10))) {
+ continue;
+ }
+
+ let selector = event.selector;
+
+ if (!selector && event.data) {
+ selector = event.data.selector || event.data || event.selector;
+ }
+
+ if (!selector || !node.ownerDocument) {
+ continue;
+ }
+
+ let matches;
+ try {
+ matches = node.matches && node.matches(selector);
+ } catch (e) {
+ // Invalid selector, do nothing.
+ }
+
+ if (!matches) {
+ continue;
+ }
+
+ if (typeof event === "function" || typeof event === "object") {
+ // If we shouldn't be showing chrome events due to context and this
+ // is a chrome handler we can ignore it.
+ const handler = event.handler || event;
+ if (!this.chromeEnabled && this.isChromeHandler(handler)) {
+ continue;
+ }
+
+ if (checkOnly) {
+ return true;
+ }
+ const eventInfo = {
+ type: event.origType || event.type.substr(selector.length + 1),
+ handler: handler,
+ tags: "jQuery,Live",
+ hide: {
+ dom0: true,
+ capturing: true,
+ },
+ };
+
+ if (!eventInfo.type && event.data?.live) {
+ eventInfo.type = event.data.live;
+ }
+
+ handlers.push(eventInfo);
+ }
+ }
+ }
+ }
+ }
+
+ if (checkOnly) {
+ return false;
+ }
+ return handlers;
+ }
+
+ normalizeListener(handlerDO) {
+ function isFunctionInProxy(funcDO) {
+ // If the anonymous function is inside the |proxy| function and the
+ // function only has guessed atom, the guessed atom should starts with
+ // "proxy/".
+ const displayName = funcDO.displayName;
+ if (displayName && displayName.startsWith("proxy/")) {
+ return true;
+ }
+
+ // If the anonymous function is inside the |proxy| function and the
+ // function gets name at compile time by SetFunctionName, its guessed
+ // atom doesn't contain "proxy/". In that case, check if the caller is
+ // "proxy" function, as a fallback.
+ const calleeDS = funcDO.environment.calleeScript;
+ if (!calleeDS) {
+ return false;
+ }
+ const calleeName = calleeDS.displayName;
+ return calleeName == "proxy";
+ }
+
+ function getFirstFunctionVariable(funcDO) {
+ // The handler function inside the |proxy| function should point the
+ // unwrapped function via environment variable.
+ const names = funcDO.environment.names();
+ for (const varName of names) {
+ const varDO = handlerDO.environment.getVariable(varName);
+ if (!varDO) {
+ continue;
+ }
+ if (varDO.class == "Function") {
+ return varDO;
+ }
+ }
+ return null;
+ }
+
+ if (!isFunctionInProxy(handlerDO)) {
+ return handlerDO;
+ }
+
+ const MAX_NESTED_HANDLER_COUNT = 2;
+ for (let i = 0; i < MAX_NESTED_HANDLER_COUNT; i++) {
+ const funcDO = getFirstFunctionVariable(handlerDO);
+ if (!funcDO) {
+ return handlerDO;
+ }
+
+ handlerDO = funcDO;
+ if (isFunctionInProxy(handlerDO)) {
+ continue;
+ }
+ break;
+ }
+
+ return handlerDO;
+ }
+}
+
+/**
+ * Get or detect React events.
+ */
+class ReactEventCollector extends MainEventCollector {
+ getListeners(node, { checkOnly } = {}) {
+ const handlers = [];
+ const props = this.getProps(node);
+
+ if (props) {
+ for (const [name, prop] of Object.entries(props)) {
+ if (REACT_EVENT_NAMES.includes(name)) {
+ const listener = prop?.__reactBoundMethod || prop;
+
+ if (typeof listener !== "function") {
+ continue;
+ }
+
+ if (!this.chromeEnabled && this.isChromeHandler(listener)) {
+ continue;
+ }
+
+ if (checkOnly) {
+ return true;
+ }
+
+ const handler = {
+ type: name,
+ handler: listener,
+ tags: "React",
+ hide: {
+ dom0: true,
+ },
+ override: {
+ capturing: name.endsWith("Capture"),
+ },
+ };
+
+ handlers.push(handler);
+ }
+ }
+ }
+
+ if (checkOnly) {
+ return false;
+ }
+
+ return handlers;
+ }
+
+ getProps(node) {
+ node = this.unwrap(node);
+
+ for (const key of Object.keys(node)) {
+ if (key.startsWith("__reactInternalInstance$")) {
+ const value = node[key];
+ if (value.memoizedProps) {
+ return value.memoizedProps; // React 16
+ }
+ return value?._currentElement?.props; // React 15
+ }
+ }
+ return null;
+ }
+
+ normalizeListener(handlerDO, listener) {
+ let functionText = "";
+
+ if (handlerDO.boundTargetFunction) {
+ handlerDO = handlerDO.boundTargetFunction;
+ }
+
+ const script = handlerDO.script;
+ // Script might be undefined (eg for methods bound several times, see
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1589658)
+ const introScript = script?.source.introductionScript;
+
+ // If this is a Babel transpiled function we have no access to the
+ // source location so we need to hide the filename and debugger
+ // icon.
+ if (introScript && introScript.displayName.endsWith("/transform.run")) {
+ listener.hide.debugger = true;
+ listener.hide.filename = true;
+
+ if (!handlerDO.isArrowFunction) {
+ functionText += "function (";
+ } else {
+ functionText += "(";
+ }
+
+ functionText += handlerDO.parameterNames.join(", ");
+
+ functionText += ") {\n";
+
+ const scriptSource = script.source.text;
+ functionText += scriptSource.substr(
+ script.sourceStart,
+ script.sourceLength
+ );
+
+ listener.override.handler = functionText;
+ }
+
+ return handlerDO;
+ }
+}
+
+/**
+ * The exposed class responsible for gathering events.
+ */
+class EventCollector {
+ constructor(targetActor) {
+ this.targetActor = targetActor;
+
+ // The event collector array. Please preserve the order otherwise there will
+ // be multiple failing tests.
+ this.eventCollectors = [
+ new ReactEventCollector(),
+ new JQueryLiveEventCollector(),
+ new JQueryEventCollector(),
+ new DOMEventCollector(),
+ ];
+ }
+
+ /**
+ * Destructor (must be called manually).
+ */
+ destroy() {
+ this.eventCollectors = null;
+ }
+
+ /**
+ * Iterate through all event collectors returning on the first found event.
+ *
+ * @param {DOMNode} node
+ * The node to be checked for events.
+ * @return {Boolean}
+ * True if the node has event listeners, false otherwise.
+ */
+ hasEventListeners(node) {
+ for (const collector of this.eventCollectors) {
+ if (collector.hasListeners(node)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * We allow displaying chrome events if the page is chrome or if
+ * `devtools.chrome.enabled = true`.
+ */
+ get chromeEnabled() {
+ if (typeof this._chromeEnabled === "undefined") {
+ this._chromeEnabled = Services.prefs.getBoolPref(
+ "devtools.chrome.enabled"
+ );
+ }
+
+ return this._chromeEnabled;
+ }
+
+ /**
+ *
+ * @param {DOMNode} node
+ * The node for which events are to be gathered.
+ * @return {Array}
+ * An array containing objects in the following format:
+ * {
+ * type: type, // e.g. "click"
+ * handler: handler, // The function called when event is triggered.
+ * tags: "jQuery", // Comma separated list of tags displayed
+ * // inside event bubble.
+ * hide: { // Flags for hiding certain properties.
+ * capturing: true,
+ * dom0: true,
+ * }
+ * }
+ */
+ getEventListeners(node) {
+ const listenerArray = [];
+ let dbg;
+ if (!this.chromeEnabled) {
+ dbg = new Debugger();
+ } else {
+ // When the chrome pref is turned on, we may try to debug system compartments.
+ // But since bug 1517210, the server is also loaded using the system principal
+ // and so here, we have to ensure using a special Debugger instance, loaded
+ // in a compartment flagged with invisibleToDebugger=true. This helps the Debugger
+ // know about the precise boundary between debuggee and debugger code.
+ const ChromeDebugger = require("ChromeDebugger");
+ dbg = new ChromeDebugger();
+ }
+
+ for (const collector of this.eventCollectors) {
+ const listeners = collector.getListeners(node);
+
+ if (!listeners) {
+ continue;
+ }
+
+ for (const listener of listeners) {
+ if (collector.normalizeListener) {
+ listener.normalizeListener = collector.normalizeListener;
+ }
+ this.processHandlerForEvent(listenerArray, listener, dbg);
+ }
+ }
+
+ listenerArray.sort((a, b) => {
+ return a.type.localeCompare(b.type);
+ });
+
+ return listenerArray;
+ }
+
+ /**
+ * Process an event listener.
+ *
+ * @param {Array} listenerArray
+ * listenerArray contains all event objects that we have gathered
+ * so far.
+ * @param {EventListener} listener
+ * The event listener to process.
+ * @param {Debugger} dbg
+ * Debugger instance.
+ *
+ * @return {Array}
+ * An array of objects where a typical object looks like this:
+ * {
+ * type: "click",
+ * handler: function() { doSomething() },
+ * origin: "http://www.mozilla.com",
+ * tags: tags,
+ * DOM0: true,
+ * capturing: true,
+ * hide: {
+ * DOM0: true
+ * },
+ * native: false
+ * }
+ */
+ // eslint-disable-next-line complexity
+ processHandlerForEvent(listenerArray, listener, dbg) {
+ let globalDO;
+
+ try {
+ const { capturing, handler } = listener;
+
+ const global = Cu.getGlobalForObject(handler);
+
+ // It is important that we recreate the globalDO for each handler because
+ // their global object can vary e.g. resource:// URLs on a video control. If
+ // we don't do this then all chrome listeners simply display "native code."
+ globalDO = dbg.addDebuggee(global);
+ let listenerDO = globalDO.makeDebuggeeValue(handler);
+
+ const { normalizeListener } = listener;
+
+ if (normalizeListener) {
+ listenerDO = normalizeListener(listenerDO, listener);
+ }
+
+ const hide = listener.hide || {};
+ const override = listener.override || {};
+ const tags = listener.tags || "";
+ const type = listener.type || "";
+ let dom0 = false;
+ let functionSource = handler.toString();
+ let line = 0;
+ let column = null;
+ let native = false;
+ let url = "";
+ let sourceActor = "";
+
+ // If the listener is an object with a 'handleEvent' method, use that.
+ if (
+ listenerDO.class === "Object" ||
+ /^XUL\w*Element$/.test(listenerDO.class)
+ ) {
+ let desc;
+
+ while (!desc && listenerDO) {
+ desc = listenerDO.getOwnPropertyDescriptor("handleEvent");
+ listenerDO = listenerDO.proto;
+ }
+
+ if (desc?.value) {
+ listenerDO = desc.value;
+ }
+ }
+
+ // If the listener is bound to a different context then we need to switch
+ // to the bound function.
+ if (listenerDO.isBoundFunction) {
+ listenerDO = listenerDO.boundTargetFunction;
+ }
+
+ const { isArrowFunction, name, script, parameterNames } = listenerDO;
+
+ if (script) {
+ const scriptSource = script.source.text;
+
+ // Scripts are provided via script tags. If it wasn't provided by a
+ // script tag it must be a DOM0 event.
+ if (script.source.element) {
+ dom0 = script.source.element.class !== "HTMLScriptElement";
+ } else {
+ dom0 = false;
+ }
+ line = script.startLine;
+ column = script.startColumn;
+ url = script.url;
+ const actor = this.targetActor.sourcesManager.getOrCreateSourceActor(
+ script.source
+ );
+ sourceActor = actor ? actor.actorID : null;
+
+ // Checking for the string "[native code]" is the only way at this point
+ // to check for native code. Even if this provides a false positive then
+ // grabbing the source code a second time is harmless.
+ if (
+ functionSource === "[object Object]" ||
+ functionSource === "[object XULElement]" ||
+ functionSource.includes("[native code]")
+ ) {
+ functionSource = scriptSource.substr(
+ script.sourceStart,
+ script.sourceLength
+ );
+
+ // At this point the script looks like this:
+ // () { ... }
+ // We prefix this with "function" if it is not a fat arrow function.
+ if (!isArrowFunction) {
+ functionSource = "function " + functionSource;
+ }
+ }
+ } else {
+ // If the listener is a native one (provided by C++ code) then we have no
+ // access to the script. We use the native flag to prevent showing the
+ // debugger button because the script is not available.
+ native = true;
+ }
+
+ // Arrow function text always contains the parameters. Function
+ // parameters are often missing e.g. if Array.sort is used as a handler.
+ // If they are missing we provide the parameters ourselves.
+ if (parameterNames && parameterNames.length > 0) {
+ const prefix = "function " + name + "()";
+ const paramString = parameterNames.join(", ");
+
+ if (functionSource.startsWith(prefix)) {
+ functionSource = functionSource.substr(prefix.length);
+
+ functionSource = `function ${name} (${paramString})${functionSource}`;
+ }
+ }
+
+ // If the listener is native code we display the filename "[native code]."
+ // This is the official string and should *not* be translated.
+ let origin;
+ if (native) {
+ origin = "[native code]";
+ } else {
+ origin =
+ url +
+ (dom0 || line === 0
+ ? ""
+ : ":" + line + (column === null ? "" : ":" + column));
+ }
+
+ const eventObj = {
+ type: override.type || type,
+ handler: override.handler || functionSource.trim(),
+ origin: override.origin || origin,
+ tags: override.tags || tags,
+ DOM0: typeof override.dom0 !== "undefined" ? override.dom0 : dom0,
+ capturing:
+ typeof override.capturing !== "undefined"
+ ? override.capturing
+ : capturing,
+ hide: typeof override.hide !== "undefined" ? override.hide : hide,
+ native,
+ sourceActor,
+ };
+
+ // Hide the debugger icon for DOM0 and native listeners. DOM0 listeners are
+ // generated dynamically from e.g. an onclick="" attribute so the script
+ // doesn't actually exist.
+ if (native || dom0) {
+ eventObj.hide.debugger = true;
+ }
+ listenerArray.push(eventObj);
+ } finally {
+ // Ensure that we always remove the debuggee.
+ if (globalDO) {
+ dbg.removeDebuggee(globalDO);
+ }
+ }
+ }
+}
+
+exports.EventCollector = EventCollector;
diff --git a/devtools/server/actors/inspector/inspector.js b/devtools/server/actors/inspector/inspector.js
new file mode 100644
index 0000000000..50aa5132af
--- /dev/null
+++ b/devtools/server/actors/inspector/inspector.js
@@ -0,0 +1,331 @@
+/* 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";
+
+/**
+ * Here's the server side of the remote inspector.
+ *
+ * The WalkerActor is the client's view of the debuggee's DOM. It's gives
+ * the client a tree of NodeActor objects.
+ *
+ * The walker presents the DOM tree mostly unmodified from the source DOM
+ * tree, but with a few key differences:
+ *
+ * - Empty text nodes are ignored. This is pretty typical of developer
+ * tools, but maybe we should reconsider that on the server side.
+ * - iframes with documents loaded have the loaded document as the child,
+ * the walker provides one big tree for the whole document tree.
+ *
+ * There are a few ways to get references to NodeActors:
+ *
+ * - When you first get a WalkerActor reference, it comes with a free
+ * reference to the root document's node.
+ * - Given a node, you can ask for children, siblings, and parents.
+ * - You can issue querySelector and querySelectorAll requests to find
+ * other elements.
+ * - Requests that return arbitrary nodes from the tree (like querySelector
+ * and querySelectorAll) will also return any nodes the client hasn't
+ * seen in order to have a complete set of parents.
+ *
+ * Once you have a NodeFront, you should be able to answer a few questions
+ * without further round trips, like the node's name, namespace/tagName,
+ * attributes, etc. Other questions (like a text node's full nodeValue)
+ * might require another round trip.
+ *
+ * The protocol guarantees that the client will always know the parent of
+ * any node that is returned by the server. This means that some requests
+ * (like querySelector) will include the extra nodes needed to satisfy this
+ * requirement. The client keeps track of this parent relationship, so the
+ * node fronts form a tree that is a subset of the actual DOM tree.
+ *
+ *
+ * We maintain this guarantee to support the ability to release subtrees on
+ * the client - when a node is disconnected from the DOM tree we want to be
+ * able to free the client objects for all the children nodes.
+ *
+ * So to be able to answer "all the children of a given node that we have
+ * seen on the client side", we guarantee that every time we've seen a node,
+ * we connect it up through its parents.
+ */
+
+const Services = require("Services");
+const protocol = require("devtools/shared/protocol");
+const { LongStringActor } = require("devtools/server/actors/string");
+
+const { inspectorSpec } = require("devtools/shared/specs/inspector");
+
+loader.lazyRequireGetter(
+ this,
+ "InspectorActorUtils",
+ "devtools/server/actors/inspector/utils"
+);
+loader.lazyRequireGetter(
+ this,
+ "WalkerActor",
+ "devtools/server/actors/inspector/walker",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "EyeDropper",
+ "devtools/server/actors/highlighters/eye-dropper",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "PageStyleActor",
+ "devtools/server/actors/page-style",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["CustomHighlighterActor", "isTypeRegistered", "HighlighterEnvironment"],
+ "devtools/server/actors/highlighters",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "CompatibilityActor",
+ "devtools/server/actors/compatibility/compatibility",
+ true
+);
+
+const SVG_NS = "http://www.w3.org/2000/svg";
+const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+
+/**
+ * Server side of the inspector actor, which is used to create
+ * inspector-related actors, including the walker.
+ */
+exports.InspectorActor = protocol.ActorClassWithSpec(inspectorSpec, {
+ initialize: function(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+
+ this._onColorPicked = this._onColorPicked.bind(this);
+ this._onColorPickCanceled = this._onColorPickCanceled.bind(this);
+ this.destroyEyeDropper = this.destroyEyeDropper.bind(this);
+ },
+
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+ this.destroyEyeDropper();
+
+ this._compatibility = null;
+ this._pageStylePromise = null;
+ this._walkerPromise = null;
+ this.walker = null;
+ this.targetActor = null;
+ },
+
+ get window() {
+ return this.targetActor.window;
+ },
+
+ getWalker: function(options = {}) {
+ if (this._walkerPromise) {
+ return this._walkerPromise;
+ }
+
+ this._walkerPromise = new Promise(resolve => {
+ const domReady = () => {
+ const targetActor = this.targetActor;
+ this.walker = WalkerActor(this.conn, targetActor, options);
+ this.manage(this.walker);
+ this.walker.once("destroyed", () => {
+ this._walkerPromise = null;
+ this._pageStylePromise = null;
+ });
+ resolve(this.walker);
+ };
+
+ if (this.window.document.readyState === "loading") {
+ this.window.addEventListener("DOMContentLoaded", domReady, {
+ capture: true,
+ once: true,
+ });
+ } else {
+ domReady();
+ }
+ });
+
+ return this._walkerPromise;
+ },
+
+ getPageStyle: function() {
+ if (this._pageStylePromise) {
+ return this._pageStylePromise;
+ }
+
+ this._pageStylePromise = this.getWalker().then(walker => {
+ const pageStyle = PageStyleActor(this);
+ this.manage(pageStyle);
+ return pageStyle;
+ });
+ return this._pageStylePromise;
+ },
+
+ getCompatibility: function() {
+ if (this._compatibility) {
+ return this._compatibility;
+ }
+
+ this._compatibility = CompatibilityActor(this);
+ this.manage(this._compatibility);
+ return this._compatibility;
+ },
+
+ /**
+ * If consumers need to display several highlighters at the same time or
+ * different types of highlighters, then this method should be used, passing
+ * the type name of the highlighter needed as argument.
+ * A new instance will be created everytime the method is called, so it's up
+ * to the consumer to release it when it is not needed anymore
+ *
+ * @param {String} type The type of highlighter to create
+ * @return {Highlighter} The highlighter actor instance or null if the
+ * typeName passed doesn't match any available highlighter
+ */
+ getHighlighterByType: async function(typeName) {
+ if (isTypeRegistered(typeName)) {
+ const highlighterActor = CustomHighlighterActor(this, typeName);
+ if (highlighterActor.instance.isReady) {
+ await highlighterActor.instance.isReady;
+ }
+
+ return highlighterActor;
+ }
+ return null;
+ },
+
+ /**
+ * Get the node's image data if any (for canvas and img nodes).
+ * Returns an imageData object with the actual data being a LongStringActor
+ * and a size json object.
+ * The image data is transmitted as a base64 encoded png data-uri.
+ * The method rejects if the node isn't an image or if the image is missing
+ *
+ * Accepts a maxDim request parameter to resize images that are larger. This
+ * is important as the resizing occurs server-side so that image-data being
+ * transfered in the longstring back to the client will be that much smaller
+ */
+ getImageDataFromURL: function(url, maxDim) {
+ const img = new this.window.Image();
+ img.src = url;
+
+ // imageToImageData waits for the image to load.
+ return InspectorActorUtils.imageToImageData(img, maxDim).then(imageData => {
+ return {
+ data: LongStringActor(this.conn, imageData.data),
+ size: imageData.size,
+ };
+ });
+ },
+
+ /**
+ * Resolve a URL to its absolute form, in the scope of a given content window.
+ * @param {String} url.
+ * @param {NodeActor} node If provided, the owner window of this node will be
+ * used to resolve the URL. Otherwise, the top-level content window will be
+ * used instead.
+ * @return {String} url.
+ */
+ resolveRelativeURL: function(url, node) {
+ const document = InspectorActorUtils.isNodeDead(node)
+ ? this.window.document
+ : InspectorActorUtils.nodeDocument(node.rawNode);
+
+ if (!document) {
+ return url;
+ }
+
+ const baseURI = Services.io.newURI(document.location.href);
+ return Services.io.newURI(url, null, baseURI).spec;
+ },
+
+ /**
+ * Create an instance of the eye-dropper highlighter and store it on this._eyeDropper.
+ * Note that for now, a new instance is created every time to deal with page navigation.
+ */
+ createEyeDropper: function() {
+ this.destroyEyeDropper();
+ this._highlighterEnv = new HighlighterEnvironment();
+ this._highlighterEnv.initFromTargetActor(this.targetActor);
+ this._eyeDropper = new EyeDropper(this._highlighterEnv);
+ return this._eyeDropper.isReady;
+ },
+
+ /**
+ * Destroy the current eye-dropper highlighter instance.
+ */
+ destroyEyeDropper: function() {
+ if (this._eyeDropper) {
+ this.cancelPickColorFromPage();
+ this._eyeDropper.destroy();
+ this._eyeDropper = null;
+ this._highlighterEnv.destroy();
+ this._highlighterEnv = null;
+ }
+ },
+
+ /**
+ * Pick a color from the page using the eye-dropper. This method doesn't return anything
+ * but will cause events to be sent to the front when a color is picked or when the user
+ * cancels the picker.
+ * @param {Object} options
+ */
+ pickColorFromPage: async function(options) {
+ await this.createEyeDropper();
+ this._eyeDropper.show(this.window.document.documentElement, options);
+ this._eyeDropper.once("selected", this._onColorPicked);
+ this._eyeDropper.once("canceled", this._onColorPickCanceled);
+ this.targetActor.once("will-navigate", this.destroyEyeDropper);
+ },
+
+ /**
+ * After the pickColorFromPage method is called, the only way to dismiss the eye-dropper
+ * highlighter is for the user to click in the page and select a color. If you need to
+ * dismiss the eye-dropper programatically instead, use this method.
+ */
+ cancelPickColorFromPage: function() {
+ if (this._eyeDropper) {
+ this._eyeDropper.hide();
+ this._eyeDropper.off("selected", this._onColorPicked);
+ this._eyeDropper.off("canceled", this._onColorPickCanceled);
+ this.targetActor.off("will-navigate", this.destroyEyeDropper);
+ }
+ },
+
+ /**
+ * Check if the current document supports highlighters using a canvasFrame anonymous
+ * content container.
+ * It is impossible to detect the feature programmatically as some document types simply
+ * don't render the canvasFrame without throwing any error.
+ */
+ supportsHighlighters: function() {
+ const doc = this.targetActor.window.document;
+ const ns = doc.documentElement.namespaceURI;
+
+ // XUL documents do not support insertAnonymousContent().
+ if (ns === XUL_NS) {
+ return false;
+ }
+
+ // SVG documents do not render the canvasFrame (see Bug 1157592).
+ if (ns === SVG_NS) {
+ return false;
+ }
+
+ return true;
+ },
+
+ _onColorPicked: function(color) {
+ this.emit("color-picked", color);
+ },
+
+ _onColorPickCanceled: function() {
+ this.emit("color-pick-canceled");
+ },
+});
diff --git a/devtools/server/actors/inspector/moz.build b/devtools/server/actors/inspector/moz.build
new file mode 100644
index 0000000000..03c69dc9fe
--- /dev/null
+++ b/devtools/server/actors/inspector/moz.build
@@ -0,0 +1,21 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "constants.js",
+ "css-logic.js",
+ "custom-element-watcher.js",
+ "document-walker.js",
+ "event-collector.js",
+ "inspector.js",
+ "node-picker.js",
+ "node.js",
+ "utils.js",
+ "walker.js",
+)
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Inspector")
diff --git a/devtools/server/actors/inspector/node-picker.js b/devtools/server/actors/inspector/node-picker.js
new file mode 100644
index 0000000000..fa75029968
--- /dev/null
+++ b/devtools/server/actors/inspector/node-picker.js
@@ -0,0 +1,311 @@
+/* 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";
+const { Ci } = require("chrome");
+const Services = require("Services");
+
+loader.lazyRequireGetter(
+ this,
+ "isWindowIncluded",
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isRemoteFrame",
+ "devtools/shared/layout/utils",
+ true
+);
+
+const IS_OSX = Services.appinfo.OS === "Darwin";
+
+class NodePicker {
+ constructor(walker, targetActor) {
+ this._walker = walker;
+ this._targetActor = targetActor;
+
+ this._isPicking = false;
+ this._hoveredNode = null;
+ this._currentNode = null;
+
+ this._onHovered = this._onHovered.bind(this);
+ this._onKey = this._onKey.bind(this);
+ this._onPick = this._onPick.bind(this);
+ this._onSuppressedEvent = this._onSuppressedEvent.bind(this);
+ }
+
+ _findAndAttachElement(event) {
+ // originalTarget allows access to the "real" element before any retargeting
+ // is applied, such as in the case of XBL anonymous elements. See also
+ // https://developer.mozilla.org/docs/XBL/XBL_1.0_Reference/Anonymous_Content#Event_Flow_and_Targeting
+ const node = event.originalTarget || event.target;
+ return this._walker.attachElement(node);
+ }
+
+ /**
+ * Returns `true` if the event was dispatched from a window included in
+ * the current highlighter environment; or if the highlighter environment has
+ * chrome privileges
+ *
+ * @param {Event} event
+ * The event to allow
+ * @return {Boolean}
+ */
+ _isEventAllowed({ view }) {
+ const { window } = this._targetActor;
+
+ return (
+ window instanceof Ci.nsIDOMChromeWindow || isWindowIncluded(window, view)
+ );
+ }
+
+ /**
+ * Pick a node on click.
+ *
+ * This method doesn't respond anything interesting, however, it starts
+ * mousemove, and click listeners on the content document to fire
+ * events and let connected clients know when nodes are hovered over or
+ * clicked.
+ *
+ * Once a node is picked, events will cease, and listeners will be removed.
+ */
+ _onPick(event) {
+ // If the picked node is a remote frame, then we need to let the event through
+ // since there's a highlighter actor in that sub-frame also picking.
+ if (isRemoteFrame(event.target)) {
+ return;
+ }
+
+ this._preventContentEvent(event);
+ if (!this._isEventAllowed(event)) {
+ return;
+ }
+
+ // If Shift is pressed, this is only a preview click.
+ // Send the event to the client, but don't stop picking.
+ if (event.shiftKey) {
+ this._walker.emit(
+ "picker-node-previewed",
+ this._findAndAttachElement(event)
+ );
+ return;
+ }
+
+ this._stopPickerListeners();
+ this._isPicking = false;
+ if (!this._currentNode) {
+ this._currentNode = this._findAndAttachElement(event);
+ }
+
+ this._walker.emit("picker-node-picked", this._currentNode);
+ }
+
+ _onHovered(event) {
+ // If the hovered node is a remote frame, then we need to let the event through
+ // since there's a highlighter actor in that sub-frame also picking.
+ if (isRemoteFrame(event.target)) {
+ return;
+ }
+
+ this._preventContentEvent(event);
+ if (!this._isEventAllowed(event)) {
+ return;
+ }
+
+ this._currentNode = this._findAndAttachElement(event);
+ if (this._hoveredNode !== this._currentNode.node) {
+ this._walker.emit("picker-node-hovered", this._currentNode);
+ this._hoveredNode = this._currentNode.node;
+ }
+ }
+
+ _onKey(event) {
+ if (!this._currentNode || !this._isPicking) {
+ return;
+ }
+
+ this._preventContentEvent(event);
+ if (!this._isEventAllowed(event)) {
+ return;
+ }
+
+ let currentNode = this._currentNode.node.rawNode;
+
+ /**
+ * KEY: Action/scope
+ * LEFT_KEY: wider or parent
+ * RIGHT_KEY: narrower or child
+ * ENTER/CARRIAGE_RETURN: Picks currentNode
+ * ESC/CTRL+SHIFT+C: Cancels picker, picks currentNode
+ */
+ switch (event.keyCode) {
+ // Wider.
+ case event.DOM_VK_LEFT:
+ if (!currentNode.parentElement) {
+ return;
+ }
+ currentNode = currentNode.parentElement;
+ break;
+
+ // Narrower.
+ case event.DOM_VK_RIGHT:
+ if (!currentNode.children.length) {
+ return;
+ }
+
+ // Set firstElementChild by default
+ let child = currentNode.firstElementChild;
+ // If currentNode is parent of hoveredNode, then
+ // previously selected childNode is set
+ const hoveredNode = this._hoveredNode.rawNode;
+ for (const sibling of currentNode.children) {
+ if (sibling.contains(hoveredNode) || sibling === hoveredNode) {
+ child = sibling;
+ }
+ }
+
+ currentNode = child;
+ break;
+
+ // Select the element.
+ case event.DOM_VK_RETURN:
+ this._onPick(event);
+ return;
+
+ // Cancel pick mode.
+ case event.DOM_VK_ESCAPE:
+ this.cancelPick();
+ this._walker.emit("picker-node-canceled");
+ return;
+ case event.DOM_VK_C:
+ const { altKey, ctrlKey, metaKey, shiftKey } = event;
+
+ if (
+ (IS_OSX && metaKey && altKey | shiftKey) ||
+ (!IS_OSX && ctrlKey && shiftKey)
+ ) {
+ this.cancelPick();
+ this._walker.emit("picker-node-canceled");
+ }
+ return;
+ default:
+ return;
+ }
+
+ // Store currently attached element
+ this._currentNode = this._walker.attachElement(currentNode);
+ this._walker.emit("picker-node-hovered", this._currentNode);
+ }
+
+ _onSuppressedEvent(event) {
+ if (event.type == "mousemove") {
+ this._onHovered(event);
+ } else if (event.type == "mouseup") {
+ // Suppressed mousedown/mouseup events will be sent to us before they have
+ // been converted into click events. Just treat any mouseup as a click.
+ this._onPick(event);
+ }
+ }
+
+ // In most cases, we need to prevent content events from reaching the content. This is
+ // needed to avoid triggering actions such as submitting forms or following links.
+ // In the case where the event happens on a remote frame however, we do want to let it
+ // through. That is because otherwise the pickers started in nested remote frames will
+ // never have a chance of picking their own elements.
+ _preventContentEvent(event) {
+ if (isRemoteFrame(event.target)) {
+ return;
+ }
+ event.stopPropagation();
+ event.preventDefault();
+ }
+
+ /**
+ * When the debugger pauses execution in a page, events will not be delivered
+ * to any handlers added to elements on that page. This method uses the
+ * document's setSuppressedEventListener interface to bypass this restriction:
+ * events will be delivered to the callback at times when they would
+ * otherwise be suppressed. The set of events delivered this way is currently
+ * limited to mouse events.
+ *
+ * @param callback The function to call with suppressed events, or null.
+ */
+ _setSuppressedEventListener(callback) {
+ const { document } = this._targetActor.window;
+
+ // Pass the callback to setSuppressedEventListener as an EventListener.
+ document.setSuppressedEventListener(
+ callback ? { handleEvent: callback } : null
+ );
+ }
+
+ _startPickerListeners() {
+ const target = this._targetActor.chromeEventHandler;
+ target.addEventListener("mousemove", this._onHovered, true);
+ target.addEventListener("click", this._onPick, true);
+ target.addEventListener("mousedown", this._preventContentEvent, true);
+ target.addEventListener("mouseup", this._preventContentEvent, true);
+ target.addEventListener("dblclick", this._preventContentEvent, true);
+ target.addEventListener("keydown", this._onKey, true);
+ target.addEventListener("keyup", this._preventContentEvent, true);
+
+ this._setSuppressedEventListener(this._onSuppressedEvent);
+ }
+
+ _stopPickerListeners() {
+ const target = this._targetActor.chromeEventHandler;
+ if (!target) {
+ return;
+ }
+
+ target.removeEventListener("mousemove", this._onHovered, true);
+ target.removeEventListener("click", this._onPick, true);
+ target.removeEventListener("mousedown", this._preventContentEvent, true);
+ target.removeEventListener("mouseup", this._preventContentEvent, true);
+ target.removeEventListener("dblclick", this._preventContentEvent, true);
+ target.removeEventListener("keydown", this._onKey, true);
+ target.removeEventListener("keyup", this._preventContentEvent, true);
+
+ this._setSuppressedEventListener(null);
+ }
+
+ cancelPick() {
+ if (this._targetActor.threadActor) {
+ this._targetActor.threadActor.showOverlay();
+ }
+
+ if (this._isPicking) {
+ this._stopPickerListeners();
+ this._isPicking = false;
+ this._hoveredNode = null;
+ }
+ }
+
+ pick(doFocus = false) {
+ if (this._targetActor.threadActor) {
+ this._targetActor.threadActor.hideOverlay();
+ }
+
+ if (this._isPicking) {
+ return;
+ }
+
+ this._startPickerListeners();
+ this._isPicking = true;
+
+ if (doFocus) {
+ this._targetActor.window.focus();
+ }
+ }
+
+ destroy() {
+ this.cancelPick();
+
+ this._targetActor = null;
+ this._walker = null;
+ }
+}
+
+exports.NodePicker = NodePicker;
diff --git a/devtools/server/actors/inspector/node.js b/devtools/server/actors/inspector/node.js
new file mode 100644
index 0000000000..c265493289
--- /dev/null
+++ b/devtools/server/actors/inspector/node.js
@@ -0,0 +1,741 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const Services = require("Services");
+const InspectorUtils = require("InspectorUtils");
+const protocol = require("devtools/shared/protocol");
+const { PSEUDO_CLASSES } = require("devtools/shared/css/constants");
+const { nodeSpec, nodeListSpec } = require("devtools/shared/specs/node");
+loader.lazyRequireGetter(
+ this,
+ ["getCssPath", "getXPath", "findCssSelector", "findAllCssSelectors"],
+ "devtools/shared/inspector/css-logic",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ [
+ "isAfterPseudoElement",
+ "isAnonymous",
+ "isBeforePseudoElement",
+ "isDirectShadowHostChild",
+ "isMarkerPseudoElement",
+ "isNativeAnonymous",
+ "isShadowHost",
+ "isShadowRoot",
+ "getShadowRootMode",
+ "isRemoteFrame",
+ ],
+ "devtools/shared/layout/utils",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ [
+ "getBackgroundColor",
+ "getClosestBackgroundColor",
+ "getNodeDisplayName",
+ "imageToImageData",
+ "isNodeDead",
+ ],
+ "devtools/server/actors/inspector/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "LongStringActor",
+ "devtools/server/actors/string",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getFontPreviewData",
+ "devtools/server/actors/utils/style-utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "EventCollector",
+ "devtools/server/actors/inspector/event-collector",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "DOMHelpers",
+ "devtools/shared/dom-helpers",
+ true
+);
+
+const SUBGRID_ENABLED = Services.prefs.getBoolPref(
+ "layout.css.grid-template-subgrid-value.enabled"
+);
+
+const FONT_FAMILY_PREVIEW_TEXT = "The quick brown fox jumps over the lazy dog";
+const FONT_FAMILY_PREVIEW_TEXT_SIZE = 20;
+
+/**
+ * Server side of the node actor.
+ */
+const NodeActor = protocol.ActorClassWithSpec(nodeSpec, {
+ initialize: function(walker, node) {
+ protocol.Actor.prototype.initialize.call(this, null);
+ this.walker = walker;
+ this.rawNode = node;
+ this._eventCollector = new EventCollector(this.walker.targetActor);
+
+ // Store the original display type and scrollable state and whether or not the node is
+ // displayed to track changes when reflows occur.
+ const wasScrollable = this.isScrollable;
+
+ this.currentDisplayType = this.displayType;
+ this.wasDisplayed = this.isDisplayed;
+ this.wasScrollable = wasScrollable;
+
+ if (wasScrollable) {
+ this.walker.updateOverflowCausingElements(
+ this,
+ this.walker.overflowCausingElementsMap
+ );
+ }
+ },
+
+ toString: function() {
+ return (
+ "[NodeActor " + this.actorID + " for " + this.rawNode.toString() + "]"
+ );
+ },
+
+ /**
+ * Instead of storing a connection object, the NodeActor gets its connection
+ * from its associated walker.
+ */
+ get conn() {
+ return this.walker.conn;
+ },
+
+ isDocumentElement: function() {
+ return (
+ this.rawNode.ownerDocument &&
+ this.rawNode.ownerDocument.documentElement === this.rawNode
+ );
+ },
+
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+
+ if (this.mutationObserver) {
+ if (!Cu.isDeadWrapper(this.mutationObserver)) {
+ this.mutationObserver.disconnect();
+ }
+ this.mutationObserver = null;
+ }
+
+ if (this.slotchangeListener) {
+ if (!isNodeDead(this)) {
+ this.rawNode.removeEventListener("slotchange", this.slotchangeListener);
+ }
+ this.slotchangeListener = null;
+ }
+
+ this._eventCollector.destroy();
+ this._eventCollector = null;
+ this.rawNode = null;
+ this.walker = null;
+ },
+
+ // Returns the JSON representation of this object over the wire.
+ form: function() {
+ const parentNode = this.walker.parentNode(this);
+ const inlineTextChild = this.walker.inlineTextChild(this);
+ const shadowRoot = isShadowRoot(this.rawNode);
+ const hostActor = shadowRoot
+ ? this.walker.getNode(this.rawNode.host)
+ : null;
+
+ const form = {
+ actor: this.actorID,
+ host: hostActor ? hostActor.actorID : undefined,
+ baseURI: this.rawNode.baseURI,
+ parent: parentNode ? parentNode.actorID : undefined,
+ nodeType: this.rawNode.nodeType,
+ namespaceURI: this.rawNode.namespaceURI,
+ nodeName: this.rawNode.nodeName,
+ nodeValue: this.rawNode.nodeValue,
+ displayName: getNodeDisplayName(this.rawNode),
+ numChildren: this.numChildren,
+ inlineTextChild: inlineTextChild ? inlineTextChild.form() : undefined,
+ displayType: this.displayType,
+ isScrollable: this.isScrollable,
+ isTopLevelDocument: this.isTopLevelDocument,
+ causesOverflow: this.walker.overflowCausingElementsMap.has(this.rawNode),
+
+ // doctype attributes
+ name: this.rawNode.name,
+ publicId: this.rawNode.publicId,
+ systemId: this.rawNode.systemId,
+
+ attrs: this.writeAttrs(),
+ customElementLocation: this.getCustomElementLocation(),
+ isMarkerPseudoElement: isMarkerPseudoElement(this.rawNode),
+ isBeforePseudoElement: isBeforePseudoElement(this.rawNode),
+ isAfterPseudoElement: isAfterPseudoElement(this.rawNode),
+ isAnonymous: isAnonymous(this.rawNode),
+ isNativeAnonymous: isNativeAnonymous(this.rawNode),
+ isShadowRoot: shadowRoot,
+ shadowRootMode: getShadowRootMode(this.rawNode),
+ isShadowHost: isShadowHost(this.rawNode),
+ isDirectShadowHostChild: isDirectShadowHostChild(this.rawNode),
+ pseudoClassLocks: this.writePseudoClassLocks(),
+ mutationBreakpoints: this.walker.getMutationBreakpoints(this),
+
+ isDisplayed: this.isDisplayed,
+ isInHTMLDocument:
+ this.rawNode.ownerDocument &&
+ this.rawNode.ownerDocument.contentType === "text/html",
+ hasEventListeners: this._hasEventListeners,
+ traits: {},
+ };
+
+ if (this.isDocumentElement()) {
+ form.isDocumentElement = true;
+ }
+
+ // Flag the remote frame and declare at least one child (the #document element) so
+ // that they can be expanded.
+ if (this.isRemoteFrame) {
+ form.remoteFrame = true;
+ form.numChildren = 1;
+ form.browsingContextID = this.rawNode.browsingContext.id;
+ }
+
+ return form;
+ },
+
+ /**
+ * Watch the given document node for mutations using the DOM observer
+ * API.
+ */
+ watchDocument: function(doc, callback) {
+ const node = this.rawNode;
+ // Create the observer on the node's actor. The node will make sure
+ // the observer is cleaned up when the actor is released.
+ const observer = new doc.defaultView.MutationObserver(callback);
+ observer.mergeAttributeRecords = true;
+ observer.observe(node, {
+ nativeAnonymousChildList: true,
+ attributes: true,
+ characterData: true,
+ characterDataOldValue: true,
+ childList: true,
+ subtree: true,
+ });
+ this.mutationObserver = observer;
+ },
+
+ /**
+ * Watch for all "slotchange" events on the node.
+ */
+ watchSlotchange: function(callback) {
+ this.slotchangeListener = callback;
+ this.rawNode.addEventListener("slotchange", this.slotchangeListener);
+ },
+
+ /**
+ * Check if the current node is representing a remote frame.
+ * In the context of the browser toolbox, a remote frame can be the <browser remote>
+ * element found inside each tab.
+ * In the context of the content toolbox, a remote frame can be a <iframe> that contains
+ * a different origin document.
+ */
+ get isRemoteFrame() {
+ return isRemoteFrame(this.rawNode);
+ },
+
+ get isTopLevelDocument() {
+ return this.rawNode === this.walker.rootDoc;
+ },
+
+ // Estimate the number of children that the walker will return without making
+ // a call to children() if possible.
+ get numChildren() {
+ // For pseudo elements, childNodes.length returns 1, but the walker
+ // will return 0.
+ if (
+ isMarkerPseudoElement(this.rawNode) ||
+ isBeforePseudoElement(this.rawNode) ||
+ isAfterPseudoElement(this.rawNode)
+ ) {
+ return 0;
+ }
+
+ const rawNode = this.rawNode;
+ let numChildren = rawNode.childNodes.length;
+ const hasContentDocument = rawNode.contentDocument;
+ const hasSVGDocument = rawNode.getSVGDocument && rawNode.getSVGDocument();
+ if (numChildren === 0 && (hasContentDocument || hasSVGDocument)) {
+ // This might be an iframe with virtual children.
+ numChildren = 1;
+ }
+
+ // Normal counting misses ::before/::after. Also, some anonymous children
+ // may ultimately be skipped, so we have to consult with the walker.
+ //
+ // FIXME: We should be able to just check <slot> rather than
+ // containingShadowRoot.
+ if (
+ numChildren === 0 ||
+ isShadowHost(this.rawNode) ||
+ this.rawNode.containingShadowRoot
+ ) {
+ numChildren = this.walker.countChildren(this);
+ }
+
+ return numChildren;
+ },
+
+ get computedStyle() {
+ if (!this._computedStyle) {
+ this._computedStyle = CssLogic.getComputedStyle(this.rawNode);
+ }
+ return this._computedStyle;
+ },
+
+ /**
+ * Returns the computed display style property value of the node.
+ */
+ get displayType() {
+ // Consider all non-element nodes as displayed.
+ if (isNodeDead(this) || this.rawNode.nodeType !== Node.ELEMENT_NODE) {
+ return null;
+ }
+
+ const style = this.computedStyle;
+ if (!style) {
+ return null;
+ }
+
+ let display = null;
+ try {
+ display = style.display;
+ } catch (e) {
+ // Fails for <scrollbar> elements.
+ }
+
+ if (
+ SUBGRID_ENABLED &&
+ (display === "grid" || display === "inline-grid") &&
+ (style.gridTemplateRows.startsWith("subgrid") ||
+ style.gridTemplateColumns.startsWith("subgrid"))
+ ) {
+ display = "subgrid";
+ }
+
+ return display;
+ },
+
+ /**
+ * Check whether the node currently has scrollbars and is scrollable.
+ */
+ get isScrollable() {
+ return (
+ this.rawNode.nodeType === Node.ELEMENT_NODE &&
+ this.rawNode.hasVisibleScrollbars
+ );
+ },
+
+ /**
+ * Is the node currently displayed?
+ */
+ get isDisplayed() {
+ const type = this.displayType;
+
+ // Consider all non-elements or elements with no display-types to be displayed.
+ if (!type) {
+ return true;
+ }
+
+ // Otherwise consider elements to be displayed only if their display-types is other
+ // than "none"".
+ return type !== "none";
+ },
+
+ /**
+ * Are there event listeners that are listening on this node? This method
+ * uses all parsers registered via event-parsers.js.registerEventParser() to
+ * check if there are any event listeners.
+ */
+ get _hasEventListeners() {
+ // We need to pass a debugger instance from this compartment because
+ // otherwise we can't make use of it inside the event-collector module.
+ const dbg = this.getParent().targetActor.makeDebugger();
+ return this._eventCollector.hasEventListeners(this.rawNode, dbg);
+ },
+
+ writeAttrs: function() {
+ // If the node has no attributes or this.rawNode is the document node and a
+ // node with `name="attributes"` exists in the DOM we need to bail.
+ if (
+ !this.rawNode.attributes ||
+ !(this.rawNode.attributes instanceof NamedNodeMap)
+ ) {
+ return undefined;
+ }
+
+ return [...this.rawNode.attributes].map(attr => {
+ return { namespace: attr.namespace, name: attr.name, value: attr.value };
+ });
+ },
+
+ writePseudoClassLocks: function() {
+ if (this.rawNode.nodeType !== Node.ELEMENT_NODE) {
+ return undefined;
+ }
+ let ret = undefined;
+ for (const pseudo of PSEUDO_CLASSES) {
+ if (InspectorUtils.hasPseudoClassLock(this.rawNode, pseudo)) {
+ ret = ret || [];
+ ret.push(pseudo);
+ }
+ }
+ return ret;
+ },
+
+ /**
+ * Gets event listeners and adds their information to the events array.
+ *
+ * @param {Node} node
+ * Node for which we are to get listeners.
+ */
+ getEventListeners: function(node) {
+ return this._eventCollector.getEventListeners(node);
+ },
+
+ /**
+ * Retrieve the script location of the custom element definition for this node, when
+ * relevant. To be linked to a custom element definition
+ */
+ getCustomElementLocation: function() {
+ // Get a reference to the custom element definition function.
+ const name = this.rawNode.localName;
+
+ if (!this.rawNode.ownerGlobal) {
+ return undefined;
+ }
+
+ const customElementsRegistry = this.rawNode.ownerGlobal.customElements;
+ const customElement =
+ customElementsRegistry && customElementsRegistry.get(name);
+ if (!customElement) {
+ return undefined;
+ }
+ // Create debugger object for the customElement function.
+ const global = Cu.getGlobalForObject(customElement);
+
+ const dbg = this.getParent().targetActor.makeDebugger();
+
+ // If we hit a <browser> element of Firefox, its global will be the chrome window
+ // which is system principal and will be in the same compartment as the debuggee.
+ // For some reason, this happens when we run the content toolbox. As for the content
+ // toolboxes, the modules are loaded in the same compartment as the <browser> element,
+ // this throws as the debugger can _not_ be in the same compartment as the debugger.
+ // This happens when we toggle fission for content toolbox because we try to reparent
+ // the Walker of the tab. This happens because we do not detect in Walker.reparentRemoteFrame
+ // that the target of the tab is the top level. That's because the target is a FrameTargetActor
+ // which is retrieved via Node.getEmbedderElement and doesn't return the LocalTabTargetActor.
+ // We should probably work on TabDescriptor so that the LocalTabTargetActor has a descriptor,
+ // and see if we can possibly move the local tab specific out of the TargetActor and have
+ // the TabDescriptor expose a pure FrameTargetActor?? (See bug 1579042)
+ if (Cu.getObjectPrincipal(global) == Cu.getObjectPrincipal(dbg)) {
+ return undefined;
+ }
+
+ const globalDO = dbg.addDebuggee(global);
+ const customElementDO = globalDO.makeDebuggeeValue(customElement);
+
+ // Return undefined if we can't find a script for the custom element definition.
+ if (!customElementDO.script) {
+ return undefined;
+ }
+
+ return {
+ url: customElementDO.script.url,
+ line: customElementDO.script.startLine,
+ column: customElementDO.script.startColumn,
+ };
+ },
+
+ /**
+ * Returns a LongStringActor with the node's value.
+ */
+ getNodeValue: function() {
+ return new LongStringActor(this.conn, this.rawNode.nodeValue || "");
+ },
+
+ /**
+ * Set the node's value to a given string.
+ */
+ setNodeValue: function(value) {
+ this.rawNode.nodeValue = value;
+ },
+
+ /**
+ * Get a unique selector string for this node.
+ */
+ getUniqueSelector: function() {
+ if (Cu.isDeadWrapper(this.rawNode)) {
+ return [];
+ }
+ return findCssSelector(this.rawNode);
+ },
+
+ /**
+ * Get the full array of selectors from the topmost document, going through
+ * iframes.
+ */
+ getAllSelectors: function() {
+ if (Cu.isDeadWrapper(this.rawNode)) {
+ return "";
+ }
+ return findAllCssSelectors(this.rawNode);
+ },
+
+ /**
+ * Get the full CSS path for this node.
+ *
+ * @return {String} A CSS selector with a part for the node and each of its ancestors.
+ */
+ getCssPath: function() {
+ if (Cu.isDeadWrapper(this.rawNode)) {
+ return "";
+ }
+ return getCssPath(this.rawNode);
+ },
+
+ /**
+ * Get the XPath for this node.
+ *
+ * @return {String} The XPath for finding this node on the page.
+ */
+ getXPath: function() {
+ if (Cu.isDeadWrapper(this.rawNode)) {
+ return "";
+ }
+ return getXPath(this.rawNode);
+ },
+
+ /**
+ * Scroll the selected node into view.
+ */
+ scrollIntoView: function() {
+ this.rawNode.scrollIntoView(true);
+ },
+
+ /**
+ * Get the node's image data if any (for canvas and img nodes).
+ * Returns an imageData object with the actual data being a LongStringActor
+ * and a size json object.
+ * The image data is transmitted as a base64 encoded png data-uri.
+ * The method rejects if the node isn't an image or if the image is missing
+ *
+ * Accepts a maxDim request parameter to resize images that are larger. This
+ * is important as the resizing occurs server-side so that image-data being
+ * transfered in the longstring back to the client will be that much smaller
+ */
+ getImageData: function(maxDim) {
+ return imageToImageData(this.rawNode, maxDim).then(imageData => {
+ return {
+ data: LongStringActor(this.conn, imageData.data),
+ size: imageData.size,
+ };
+ });
+ },
+
+ /**
+ * Get all event listeners that are listening on this node.
+ */
+ getEventListenerInfo: function() {
+ return this.getEventListeners(this.rawNode);
+ },
+
+ /**
+ * Modify a node's attributes. Passed an array of modifications
+ * similar in format to "attributes" mutations.
+ * {
+ * attributeName: <string>
+ * attributeNamespace: <optional string>
+ * newValue: <optional string> - If null or undefined, the attribute
+ * will be removed.
+ * }
+ *
+ * Returns when the modifications have been made. Mutations will
+ * be queued for any changes made.
+ */
+ modifyAttributes: function(modifications) {
+ const rawNode = this.rawNode;
+ for (const change of modifications) {
+ if (change.newValue == null) {
+ if (change.attributeNamespace) {
+ rawNode.removeAttributeNS(
+ change.attributeNamespace,
+ change.attributeName
+ );
+ } else {
+ rawNode.removeAttribute(change.attributeName);
+ }
+ } else if (change.attributeNamespace) {
+ rawNode.setAttributeDevtoolsNS(
+ change.attributeNamespace,
+ change.attributeName,
+ change.newValue
+ );
+ } else {
+ rawNode.setAttributeDevtools(change.attributeName, change.newValue);
+ }
+ }
+ },
+
+ /**
+ * Given the font and fill style, get the image data of a canvas with the
+ * preview text and font.
+ * Returns an imageData object with the actual data being a LongStringActor
+ * and the width of the text as a string.
+ * The image data is transmitted as a base64 encoded png data-uri.
+ */
+ getFontFamilyDataURL: function(font, fillStyle = "black") {
+ const doc = this.rawNode.ownerDocument;
+ const options = {
+ previewText: FONT_FAMILY_PREVIEW_TEXT,
+ previewFontSize: FONT_FAMILY_PREVIEW_TEXT_SIZE,
+ fillStyle: fillStyle,
+ };
+ const { dataURL, size } = getFontPreviewData(font, doc, options);
+
+ return { data: LongStringActor(this.conn, dataURL), size: size };
+ },
+
+ /**
+ * Finds the computed background color of the closest parent with a set background
+ * color.
+ *
+ * @return {String}
+ * String with the background color of the form rgba(r, g, b, a). Defaults to
+ * rgba(255, 255, 255, 1) if no background color is found.
+ */
+ getClosestBackgroundColor: function() {
+ return getClosestBackgroundColor(this.rawNode);
+ },
+
+ /**
+ * Finds the background color range for the parent of a single text node
+ * (i.e. for multi-colored backgrounds with gradients, images) or a single
+ * background color for single-colored backgrounds. Defaults to the closest
+ * background color if an error is encountered.
+ *
+ * @return {Object}
+ * Object with one or more of the following properties: value, min, max
+ */
+ getBackgroundColor: function() {
+ return getBackgroundColor(this);
+ },
+
+ /**
+ * Returns an object with the width and height of the node's owner window.
+ *
+ * @return {Object}
+ */
+ getOwnerGlobalDimensions: function() {
+ const win = this.rawNode.ownerGlobal;
+ return {
+ innerWidth: win.innerWidth,
+ innerHeight: win.innerHeight,
+ };
+ },
+
+ /**
+ * If the current node is an iframe, wait for the content window to be loaded.
+ */
+ async waitForFrameLoad() {
+ if (Cu.isDeadWrapper(this.rawNode)) {
+ return;
+ }
+
+ const { contentDocument, contentWindow } = this.rawNode;
+ if (contentDocument && contentDocument.readyState !== "complete") {
+ await new Promise(resolve => {
+ DOMHelpers.onceDOMReady(contentWindow, resolve);
+ });
+ }
+ },
+});
+
+/**
+ * Server side of a node list as returned by querySelectorAll()
+ */
+const NodeListActor = protocol.ActorClassWithSpec(nodeListSpec, {
+ initialize: function(walker, nodeList) {
+ protocol.Actor.prototype.initialize.call(this);
+ this.walker = walker;
+ this.nodeList = nodeList || [];
+ },
+
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Instead of storing a connection object, the NodeActor gets its connection
+ * from its associated walker.
+ */
+ get conn() {
+ return this.walker.conn;
+ },
+
+ /**
+ * Items returned by this actor should belong to the parent walker.
+ */
+ marshallPool: function() {
+ return this.walker;
+ },
+
+ // Returns the JSON representation of this object over the wire.
+ form: function() {
+ return {
+ actor: this.actorID,
+ length: this.nodeList ? this.nodeList.length : 0,
+ };
+ },
+
+ /**
+ * Get a single node from the node list.
+ */
+ item: function(index) {
+ return this.walker.attachElement(this.nodeList[index]);
+ },
+
+ /**
+ * Get a range of the items from the node list.
+ */
+ items: function(start = 0, end = this.nodeList.length) {
+ const items = Array.prototype.slice
+ .call(this.nodeList, start, end)
+ .map(item => this.walker._getOrCreateNodeActor(item));
+ return this.walker.attachElements(items);
+ },
+
+ release: function() {},
+});
+
+exports.NodeActor = NodeActor;
+exports.NodeListActor = NodeListActor;
diff --git a/devtools/server/actors/inspector/utils.js b/devtools/server/actors/inspector/utils.js
new file mode 100644
index 0000000000..bb2f1322ef
--- /dev/null
+++ b/devtools/server/actors/inspector/utils.js
@@ -0,0 +1,587 @@
+/* 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";
+
+const { Cu, Ci } = require("chrome");
+
+loader.lazyRequireGetter(this, "colorUtils", "devtools/shared/css/color", true);
+loader.lazyRequireGetter(this, "AsyncUtils", "devtools/shared/async-utils");
+loader.lazyRequireGetter(this, "flags", "devtools/shared/flags");
+loader.lazyRequireGetter(
+ this,
+ "DevToolsUtils",
+ "devtools/shared/DevToolsUtils"
+);
+loader.lazyRequireGetter(
+ this,
+ "nodeFilterConstants",
+ "devtools/shared/dom-node-filter-constants"
+);
+loader.lazyRequireGetter(
+ this,
+ ["isNativeAnonymous", "getAdjustedQuads"],
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getBackgroundFor",
+ "devtools/server/actors/accessibility/audit/contrast",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["loadSheetForBackgroundCalculation", "removeSheetForBackgroundCalculation"],
+ "devtools/server/actors/utils/accessibility",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getTextProperties",
+ "devtools/shared/accessibility",
+ true
+);
+
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
+const IMAGE_FETCHING_TIMEOUT = 500;
+
+/**
+ * Returns the properly cased version of the node's tag name, which can be
+ * used when displaying said name in the UI.
+ *
+ * @param {Node} rawNode
+ * Node for which we want the display name
+ * @return {String}
+ * Properly cased version of the node tag name
+ */
+const getNodeDisplayName = function(rawNode) {
+ if (rawNode.nodeName && !rawNode.localName) {
+ // The localName & prefix APIs have been moved from the Node interface to the Element
+ // interface. Use Node.nodeName as a fallback.
+ return rawNode.nodeName;
+ }
+ return (rawNode.prefix ? rawNode.prefix + ":" : "") + rawNode.localName;
+};
+
+/**
+ * Returns flex and grid information about a DOM node.
+ * In particular is it a grid flex/container and/or item?
+ *
+ * @param {DOMNode} node
+ * The node for which then information is required
+ * @return {Object}
+ * An object like { grid: { isContainer, isItem }, flex: { isContainer, isItem } }
+ */
+function getNodeGridFlexType(node) {
+ return {
+ grid: getNodeGridType(node),
+ flex: getNodeFlexType(node),
+ };
+}
+
+function getNodeFlexType(node) {
+ return {
+ isContainer: node.getAsFlexContainer && !!node.getAsFlexContainer(),
+ isItem: !!node.parentFlexElement,
+ };
+}
+
+function getNodeGridType(node) {
+ return {
+ isContainer: node.hasGridFragments && node.hasGridFragments(),
+ isItem: !!findGridParentContainerForNode(node),
+ };
+}
+
+function nodeDocument(node) {
+ if (Cu.isDeadWrapper(node)) {
+ return null;
+ }
+ return (
+ node.ownerDocument || (node.nodeType == Node.DOCUMENT_NODE ? node : null)
+ );
+}
+
+function isNodeDead(node) {
+ return !node || !node.rawNode || Cu.isDeadWrapper(node.rawNode);
+}
+
+function isInXULDocument(el) {
+ const doc = nodeDocument(el);
+ return doc?.documentElement && doc.documentElement.namespaceURI === XUL_NS;
+}
+
+/**
+ * This DeepTreeWalker filter skips whitespace text nodes and anonymous
+ * content with the exception of ::marker, ::before, and ::after, plus anonymous
+ * content in XUL document (needed to show all elements in the browser toolbox).
+ */
+function standardTreeWalkerFilter(node) {
+ // ::marker, ::before, and ::after are native anonymous content, but we always
+ // want to show them
+ if (
+ node.nodeName === "_moz_generated_content_marker" ||
+ node.nodeName === "_moz_generated_content_before" ||
+ node.nodeName === "_moz_generated_content_after"
+ ) {
+ return nodeFilterConstants.FILTER_ACCEPT;
+ }
+
+ // Ignore empty whitespace text nodes that do not impact the layout.
+ if (isWhitespaceTextNode(node)) {
+ return nodeHasSize(node)
+ ? nodeFilterConstants.FILTER_ACCEPT
+ : nodeFilterConstants.FILTER_SKIP;
+ }
+
+ // Ignore all native anonymous content inside a non-XUL document.
+ // We need to do this to skip things like form controls, scrollbars,
+ // video controls, etc (see bug 1187482).
+ if (!isInXULDocument(node) && isNativeAnonymous(node)) {
+ return nodeFilterConstants.FILTER_SKIP;
+ }
+
+ return nodeFilterConstants.FILTER_ACCEPT;
+}
+
+/**
+ * This DeepTreeWalker filter ignores anonymous content.
+ */
+function noAnonymousContentTreeWalkerFilter(node) {
+ // Ignore all native anonymous content inside a non-XUL document.
+ // We need to do this to skip things like form controls, scrollbars,
+ // video controls, etc (see bug 1187482).
+ if (!isInXULDocument(node) && isNativeAnonymous(node)) {
+ return nodeFilterConstants.FILTER_SKIP;
+ }
+
+ return nodeFilterConstants.FILTER_ACCEPT;
+}
+/**
+ * This DeepTreeWalker filter is like standardTreeWalkerFilter except that
+ * it also includes all anonymous content (like internal form controls).
+ */
+function allAnonymousContentTreeWalkerFilter(node) {
+ // Ignore empty whitespace text nodes that do not impact the layout.
+ if (isWhitespaceTextNode(node)) {
+ return nodeHasSize(node)
+ ? nodeFilterConstants.FILTER_ACCEPT
+ : nodeFilterConstants.FILTER_SKIP;
+ }
+ return nodeFilterConstants.FILTER_ACCEPT;
+}
+
+/**
+ * This DeepTreeWalker filter only accepts <scrollbar> anonymous content.
+ */
+function scrollbarTreeWalkerFilter(node) {
+ if (node.nodeName === "scrollbar" && nodeHasSize(node)) {
+ return nodeFilterConstants.FILTER_ACCEPT;
+ }
+
+ return nodeFilterConstants.FILTER_SKIP;
+}
+
+/**
+ * Is the given node a text node composed of whitespace only?
+ * @param {DOMNode} node
+ * @return {Boolean}
+ */
+function isWhitespaceTextNode(node) {
+ return node.nodeType == Node.TEXT_NODE && !/[^\s]/.exec(node.nodeValue);
+}
+
+/**
+ * Does the given node have non-0 width and height?
+ * @param {DOMNode} node
+ * @return {Boolean}
+ */
+function nodeHasSize(node) {
+ if (!node.getBoxQuads) {
+ return false;
+ }
+
+ const quads = node.getBoxQuads({
+ createFramesForSuppressedWhitespace: false,
+ });
+ return quads.some(quad => {
+ const bounds = quad.getBounds();
+ return bounds.width && bounds.height;
+ });
+}
+
+/**
+ * Returns a promise that is settled once the given HTMLImageElement has
+ * finished loading.
+ *
+ * @param {HTMLImageElement} image - The image element.
+ * @param {Number} timeout - Maximum amount of time the image is allowed to load
+ * before the waiting is aborted. Ignored if flags.testing is set.
+ *
+ * @return {Promise} that is fulfilled once the image has loaded. If the image
+ * fails to load or the load takes too long, the promise is rejected.
+ */
+function ensureImageLoaded(image, timeout) {
+ const { HTMLImageElement } = image.ownerGlobal;
+ if (!(image instanceof HTMLImageElement)) {
+ return Promise.reject("image must be an HTMLImageELement");
+ }
+
+ if (image.complete) {
+ // The image has already finished loading.
+ return Promise.resolve();
+ }
+
+ // This image is still loading.
+ const onLoad = AsyncUtils.listenOnce(image, "load");
+
+ // Reject if loading fails.
+ const onError = AsyncUtils.listenOnce(image, "error").then(() => {
+ return Promise.reject("Image '" + image.src + "' failed to load.");
+ });
+
+ // Don't timeout when testing. This is never settled.
+ let onAbort = new Promise(() => {});
+
+ if (!flags.testing) {
+ // Tests are not running. Reject the promise after given timeout.
+ onAbort = DevToolsUtils.waitForTime(timeout).then(() => {
+ return Promise.reject("Image '" + image.src + "' took too long to load.");
+ });
+ }
+
+ // See which happens first.
+ return Promise.race([onLoad, onError, onAbort]);
+}
+
+/**
+ * Given an <img> or <canvas> element, return the image data-uri. If @param node
+ * is an <img> element, the method waits a while for the image to load before
+ * the data is generated. If the image does not finish loading in a reasonable
+ * time (IMAGE_FETCHING_TIMEOUT milliseconds) the process aborts.
+ *
+ * @param {HTMLImageElement|HTMLCanvasElement} node - The <img> or <canvas>
+ * element, or Image() object. Other types cause the method to reject.
+ * @param {Number} maxDim - Optionally pass a maximum size you want the longest
+ * side of the image to be resized to before getting the image data.
+
+ * @return {Promise} A promise that is fulfilled with an object containing the
+ * data-uri and size-related information:
+ * { data: "...",
+ * size: {
+ * naturalWidth: 400,
+ * naturalHeight: 300,
+ * resized: true }
+ * }.
+ *
+ * If something goes wrong, the promise is rejected.
+ */
+const imageToImageData = async function(node, maxDim) {
+ const { HTMLCanvasElement, HTMLImageElement } = node.ownerGlobal;
+
+ const isImg = node instanceof HTMLImageElement;
+ const isCanvas = node instanceof HTMLCanvasElement;
+
+ if (!isImg && !isCanvas) {
+ throw new Error("node is not a <canvas> or <img> element.");
+ }
+
+ if (isImg) {
+ // Ensure that the image is ready.
+ await ensureImageLoaded(node, IMAGE_FETCHING_TIMEOUT);
+ }
+
+ // Get the image resize ratio if a maxDim was provided
+ let resizeRatio = 1;
+ const imgWidth = node.naturalWidth || node.width;
+ const imgHeight = node.naturalHeight || node.height;
+ const imgMax = Math.max(imgWidth, imgHeight);
+ if (maxDim && imgMax > maxDim) {
+ resizeRatio = maxDim / imgMax;
+ }
+
+ // Extract the image data
+ let imageData;
+ // The image may already be a data-uri, in which case, save ourselves the
+ // trouble of converting via the canvas.drawImage.toDataURL method, but only
+ // if the image doesn't need resizing
+ if (isImg && node.src.startsWith("data:") && resizeRatio === 1) {
+ imageData = node.src;
+ } else {
+ // Create a canvas to copy the rawNode into and get the imageData from
+ const canvas = node.ownerDocument.createElementNS(XHTML_NS, "canvas");
+ canvas.width = imgWidth * resizeRatio;
+ canvas.height = imgHeight * resizeRatio;
+ const ctx = canvas.getContext("2d");
+
+ // Copy the rawNode image or canvas in the new canvas and extract data
+ ctx.drawImage(node, 0, 0, canvas.width, canvas.height);
+ imageData = canvas.toDataURL("image/png");
+ }
+
+ return {
+ data: imageData,
+ size: {
+ naturalWidth: imgWidth,
+ naturalHeight: imgHeight,
+ resized: resizeRatio !== 1,
+ },
+ };
+};
+
+/**
+ * Finds the computed background color of the closest parent with a set background color.
+ *
+ * @param {DOMNode} node
+ * Node for which we want to find closest background color.
+ * @return {String}
+ * String with the background color of the form rgba(r, g, b, a). Defaults to
+ * rgba(255, 255, 255, 1) if no background color is found.
+ */
+function getClosestBackgroundColor(node) {
+ let current = node;
+
+ while (current) {
+ const computedStyle = CssLogic.getComputedStyle(current);
+ if (computedStyle) {
+ const currentStyle = computedStyle.getPropertyValue("background-color");
+ if (colorUtils.isValidCSSColor(currentStyle)) {
+ const currentCssColor = new colorUtils.CssColor(currentStyle);
+ if (!currentCssColor.isTransparent()) {
+ return currentCssColor.rgba;
+ }
+ }
+ }
+
+ current = current.parentNode;
+ }
+
+ return "rgba(255, 255, 255, 1)";
+}
+
+/**
+ * Finds the background image of the closest parent where it is set.
+ *
+ * @param {DOMNode} node
+ * Node for which we want to find the background image.
+ * @return {String}
+ * String with the value of the background iamge property. Defaults to "none" if
+ * no background image is found.
+ */
+function getClosestBackgroundImage(node) {
+ let current = node;
+
+ while (current) {
+ const computedStyle = CssLogic.getComputedStyle(current);
+ if (computedStyle) {
+ const currentBackgroundImage = computedStyle.getPropertyValue(
+ "background-image"
+ );
+ if (currentBackgroundImage !== "none") {
+ return currentBackgroundImage;
+ }
+ }
+
+ current = current.parentNode;
+ }
+
+ return "none";
+}
+
+/**
+ * If the provided node is a grid item, then return its parent grid.
+ *
+ * @param {DOMNode} node
+ * The node that is supposedly a grid item.
+ * @return {DOMNode|null}
+ * The parent grid if found, null otherwise.
+ */
+function findGridParentContainerForNode(node) {
+ try {
+ while ((node = node.parentNode)) {
+ const display = node.ownerGlobal.getComputedStyle(node).display;
+
+ if (display.includes("grid")) {
+ return node;
+ } else if (display === "contents") {
+ // Continue walking up the tree since the parent node is a content element.
+ continue;
+ }
+
+ break;
+ }
+ } catch (e) {
+ // Getting the parentNode can fail when the supplied node is in shadow DOM.
+ }
+
+ return null;
+}
+
+/**
+ * Finds the background color range for the parent of a single text node
+ * (i.e. for multi-colored backgrounds with gradients, images) or a single
+ * background color for single-colored backgrounds. Defaults to the closest
+ * background color if an error is encountered.
+ *
+ * @param {Object}
+ * Node actor containing the following properties:
+ * {DOMNode} rawNode
+ * Node for which we want to calculate the color contrast.
+ * {WalkerActor} walker
+ * Walker actor used to check whether the node is the parent elm of a single text node.
+ * @return {Object}
+ * Object with one or more of the following properties:
+ * {Array|null} value
+ * RGBA array for single-colored background. Null for multi-colored backgrounds.
+ * {Array|null} min
+ * RGBA array for the min luminance color in a multi-colored background.
+ * Null for single-colored backgrounds.
+ * {Array|null} max
+ * RGBA array for the max luminance color in a multi-colored background.
+ * Null for single-colored backgrounds.
+ */
+async function getBackgroundColor({ rawNode: node, walker }) {
+ // Fall back to calculating contrast against closest bg if:
+ // - not element node
+ // - more than one child
+ // Avoid calculating bounds and creating doc walker by returning early.
+ if (
+ node.nodeType != Node.ELEMENT_NODE ||
+ node.childNodes.length > 1 ||
+ !node.firstChild
+ ) {
+ return {
+ value: colorUtils.colorToRGBA(
+ getClosestBackgroundColor(node),
+ true,
+ true
+ ),
+ };
+ }
+
+ const bounds = getAdjustedQuads(
+ node.ownerGlobal,
+ node.firstChild,
+ "content"
+ )[0].bounds;
+
+ // Fall back to calculating contrast against closest bg if there are no bounds for text node.
+ // Avoid creating doc walker by returning early.
+ if (!bounds) {
+ return {
+ value: colorUtils.colorToRGBA(
+ getClosestBackgroundColor(node),
+ true,
+ true
+ ),
+ };
+ }
+
+ const docWalker = walker.getDocumentWalker(node);
+ const firstChild = docWalker.firstChild();
+
+ // Fall back to calculating contrast against closest bg if:
+ // - more than one child
+ // - unique child is not a text node
+ if (
+ !firstChild ||
+ docWalker.nextSibling() ||
+ firstChild.nodeType !== Node.TEXT_NODE
+ ) {
+ return {
+ value: colorUtils.colorToRGBA(
+ getClosestBackgroundColor(node),
+ true,
+ true
+ ),
+ };
+ }
+
+ // Try calculating complex backgrounds for node
+ const win = node.ownerGlobal;
+ loadSheetForBackgroundCalculation(win);
+ const computedStyle = CssLogic.getComputedStyle(node);
+ const props = computedStyle ? getTextProperties(computedStyle) : null;
+
+ // Fall back to calculating contrast against closest bg if there are no text props.
+ if (!props) {
+ return {
+ value: colorUtils.colorToRGBA(
+ getClosestBackgroundColor(node),
+ true,
+ true
+ ),
+ };
+ }
+
+ const bgColor = await getBackgroundFor(node, {
+ bounds,
+ win,
+ convertBoundsRelativeToViewport: false,
+ size: props.size,
+ isBoldText: props.isBoldText,
+ });
+ removeSheetForBackgroundCalculation(win);
+
+ return (
+ bgColor || {
+ value: colorUtils.colorToRGBA(
+ getClosestBackgroundColor(node),
+ true,
+ true
+ ),
+ }
+ );
+}
+
+/**
+ * Indicates if a document is ready (i.e. if it's not loading anymore)
+ *
+ * @param {HTMLDocument} document: The document we want to check
+ * @returns {Boolean}
+ */
+function isDocumentReady(document) {
+ if (!document) {
+ return false;
+ }
+
+ const { readyState } = document;
+ if (readyState == "interactive" || readyState == "complete") {
+ return true;
+ }
+
+ // A document might stay forever in unitialized state.
+ // If the target actor is not currently loading a document,
+ // assume the document is ready.
+ const webProgress = document.defaultView.docShell.QueryInterface(
+ Ci.nsIWebProgress
+ );
+ return !webProgress.isLoadingDocument;
+}
+
+module.exports = {
+ allAnonymousContentTreeWalkerFilter,
+ isDocumentReady,
+ isWhitespaceTextNode,
+ findGridParentContainerForNode,
+ getBackgroundColor,
+ getClosestBackgroundColor,
+ getClosestBackgroundImage,
+ getNodeDisplayName,
+ getNodeGridFlexType,
+ imageToImageData,
+ isNodeDead,
+ nodeDocument,
+ scrollbarTreeWalkerFilter,
+ standardTreeWalkerFilter,
+ noAnonymousContentTreeWalkerFilter,
+};
diff --git a/devtools/server/actors/inspector/walker.js b/devtools/server/actors/inspector/walker.js
new file mode 100644
index 0000000000..cd1fbdf2b5
--- /dev/null
+++ b/devtools/server/actors/inspector/walker.js
@@ -0,0 +1,2879 @@
+/* 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";
+
+const { Ci, Cu } = require("chrome");
+
+const Services = require("Services");
+const protocol = require("devtools/shared/protocol");
+const { walkerSpec } = require("devtools/shared/specs/walker");
+const { LongStringActor } = require("devtools/server/actors/string");
+const InspectorUtils = require("InspectorUtils");
+const {
+ EXCLUDED_LISTENER,
+} = require("devtools/server/actors/inspector/constants");
+const {
+ TYPES,
+ getResourceWatcher,
+} = require("devtools/server/actors/resources/index");
+
+loader.lazyRequireGetter(
+ this,
+ [
+ "getFrameElement",
+ "isAfterPseudoElement",
+ "isAnonymous",
+ "isBeforePseudoElement",
+ "isDirectShadowHostChild",
+ "isMarkerPseudoElement",
+ "isNativeAnonymous",
+ "isRemoteFrame",
+ "isShadowHost",
+ "isShadowRoot",
+ "isTemplateElement",
+ "loadSheet",
+ ],
+ "devtools/shared/layout/utils",
+ true
+);
+
+loader.lazyRequireGetter(this, "throttle", "devtools/shared/throttle", true);
+
+loader.lazyRequireGetter(
+ this,
+ [
+ "allAnonymousContentTreeWalkerFilter",
+ "findGridParentContainerForNode",
+ "isDocumentReady",
+ "isNodeDead",
+ "noAnonymousContentTreeWalkerFilter",
+ "nodeDocument",
+ "standardTreeWalkerFilter",
+ ],
+ "devtools/server/actors/inspector/utils",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "CustomElementWatcher",
+ "devtools/server/actors/inspector/custom-element-watcher",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["DocumentWalker", "SKIP_TO_SIBLING"],
+ "devtools/server/actors/inspector/document-walker",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["NodeActor", "NodeListActor"],
+ "devtools/server/actors/inspector/node",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "NodePicker",
+ "devtools/server/actors/inspector/node-picker",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "LayoutActor",
+ "devtools/server/actors/layout",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["getLayoutChangesObserver", "releaseLayoutChangesObserver"],
+ "devtools/server/actors/reflow",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WalkerSearch",
+ "devtools/server/actors/utils/walker-search",
+ true
+);
+
+// ContentDOMReference requires ChromeUtils, which isn't available in worker context.
+if (!isWorker) {
+ loader.lazyRequireGetter(
+ this,
+ "ContentDOMReference",
+ "resource://gre/modules/ContentDOMReference.jsm",
+ true
+ );
+}
+
+loader.lazyServiceGetter(
+ this,
+ "eventListenerService",
+ "@mozilla.org/eventlistenerservice;1",
+ "nsIEventListenerService"
+);
+
+// Minimum delay between two "new-mutations" events.
+const MUTATIONS_THROTTLING_DELAY = 100;
+// List of mutation types that should -not- be throttled.
+const IMMEDIATE_MUTATIONS = ["pseudoClassLock"];
+
+const HIDDEN_CLASS = "__fx-devtools-hide-shortcut__";
+
+// The possible completions to a ':' with added score to give certain values
+// some preference.
+const PSEUDO_SELECTORS = [
+ [":active", 1],
+ [":hover", 1],
+ [":focus", 1],
+ [":visited", 0],
+ [":link", 0],
+ [":first-letter", 0],
+ [":first-child", 2],
+ [":before", 2],
+ [":after", 2],
+ [":lang(", 0],
+ [":not(", 3],
+ [":first-of-type", 0],
+ [":last-of-type", 0],
+ [":only-of-type", 0],
+ [":only-child", 2],
+ [":nth-child(", 3],
+ [":nth-last-child(", 0],
+ [":nth-of-type(", 0],
+ [":nth-last-of-type(", 0],
+ [":last-child", 2],
+ [":root", 0],
+ [":empty", 0],
+ [":target", 0],
+ [":enabled", 0],
+ [":disabled", 0],
+ [":checked", 1],
+ ["::selection", 0],
+ ["::marker", 0],
+];
+
+const HELPER_SHEET =
+ "data:text/css;charset=utf-8," +
+ encodeURIComponent(`
+ .__fx-devtools-hide-shortcut__ {
+ visibility: hidden !important;
+ }
+
+ :-moz-devtools-highlighted {
+ outline: 2px dashed #F06!important;
+ outline-offset: -2px !important;
+ }
+`);
+
+/**
+ * We only send nodeValue up to a certain size by default. This stuff
+ * controls that size.
+ */
+exports.DEFAULT_VALUE_SUMMARY_LENGTH = 50;
+var gValueSummaryLength = exports.DEFAULT_VALUE_SUMMARY_LENGTH;
+
+exports.getValueSummaryLength = function() {
+ return gValueSummaryLength;
+};
+
+exports.setValueSummaryLength = function(val) {
+ gValueSummaryLength = val;
+};
+
+/**
+ * Server side of the DOM walker.
+ */
+var WalkerActor = protocol.ActorClassWithSpec(walkerSpec, {
+ /**
+ * Create the WalkerActor
+ * @param {DevToolsServerConnection} conn
+ * The server connection.
+ * @param {TargetActor} targetActor
+ * The top-level Actor for this tab.
+ * @param {Object} options
+ * - {Boolean} showAllAnonymousContent: Show all native anonymous content
+ */
+ initialize: function(conn, targetActor, options) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ this.rootWin = targetActor.window;
+ this.rootDoc = this.rootWin.document;
+
+ // Map of already created node actors, keyed by their corresponding DOMNode.
+ this._nodeActorsMap = new Map();
+
+ this._pendingMutations = [];
+ this._activePseudoClassLocks = new Set();
+ this._mutationBreakpoints = new WeakMap();
+ this.customElementWatcher = new CustomElementWatcher(
+ targetActor.chromeEventHandler
+ );
+
+ // In this map, the key-value pairs are the overflow causing elements and their
+ // respective ancestor scrollable node actor.
+ this.overflowCausingElementsMap = new Map();
+
+ this.showAllAnonymousContent = options.showAllAnonymousContent;
+
+ this.walkerSearch = new WalkerSearch(this);
+
+ // Nodes which have been removed from the client's known
+ // ownership tree are considered "orphaned", and stored in
+ // this set.
+ this._orphaned = new Set();
+
+ // The client can tell the walker that it is interested in a node
+ // even when it is orphaned with the `retainNode` method. This
+ // list contains orphaned nodes that were so retained.
+ this._retainedOrphans = new Set();
+
+ this.onNodeInserted = this.onNodeInserted.bind(this);
+ this.onNodeInserted[EXCLUDED_LISTENER] = true;
+ this.onNodeRemoved = this.onNodeRemoved.bind(this);
+ this.onNodeRemoved[EXCLUDED_LISTENER] = true;
+ this.onAttributeModified = this.onAttributeModified.bind(this);
+ this.onAttributeModified[EXCLUDED_LISTENER] = true;
+
+ this.onMutations = this.onMutations.bind(this);
+ this.onSlotchange = this.onSlotchange.bind(this);
+ this.onShadowrootattached = this.onShadowrootattached.bind(this);
+ this.onFrameLoad = this.onFrameLoad.bind(this);
+ this.onFrameUnload = this.onFrameUnload.bind(this);
+ this.onCustomElementDefined = this.onCustomElementDefined.bind(this);
+ this._throttledEmitNewMutations = throttle(
+ this._emitNewMutations.bind(this),
+ MUTATIONS_THROTTLING_DELAY
+ );
+
+ targetActor.on("will-navigate", this.onFrameUnload);
+ targetActor.on("window-ready", this.onFrameLoad);
+
+ this.customElementWatcher.on(
+ "element-defined",
+ this.onCustomElementDefined
+ );
+
+ // Keep a reference to the chromeEventHandler for the current targetActor, to make
+ // sure we will be able to remove the listener during the WalkerActor destroy().
+ this.chromeEventHandler = targetActor.chromeEventHandler;
+ // shadowrootattached is a chrome-only event.
+ this.chromeEventHandler.addEventListener(
+ "shadowrootattached",
+ this.onShadowrootattached
+ );
+
+ // Ensure that the root document node actor is ready and
+ // managed.
+ this.rootNode = this.document();
+
+ this.layoutChangeObserver = getLayoutChangesObserver(this.targetActor);
+ this._onReflows = this._onReflows.bind(this);
+ this.layoutChangeObserver.on("reflows", this._onReflows);
+ this._onResize = this._onResize.bind(this);
+ this.layoutChangeObserver.on("resize", this._onResize);
+
+ this._onEventListenerChange = this._onEventListenerChange.bind(this);
+ eventListenerService.addListenerChangeListener(this._onEventListenerChange);
+ },
+
+ get nodePicker() {
+ if (!this._nodePicker) {
+ this._nodePicker = new NodePicker(this, this.targetActor);
+ }
+
+ return this._nodePicker;
+ },
+
+ watchRootNode() {
+ if (this.rootNode && isDocumentReady(this.rootDoc)) {
+ this.emit("root-available", this.rootNode);
+ }
+ },
+
+ /**
+ * Callback for eventListenerService.addListenerChangeListener
+ * @param nsISimpleEnumerator changesEnum
+ * enumerator of nsIEventListenerChange
+ */
+ _onEventListenerChange: function(changesEnum) {
+ for (const current of changesEnum.enumerate(Ci.nsIEventListenerChange)) {
+ const target = current.target;
+
+ if (this._nodeActorsMap.has(target)) {
+ const actor = this.getNode(target);
+ const mutation = {
+ type: "events",
+ target: actor.actorID,
+ hasEventListeners: actor._hasEventListeners,
+ };
+ this.queueMutation(mutation);
+ }
+ }
+ },
+
+ // Returns the JSON representation of this object over the wire.
+ form: function() {
+ return {
+ actor: this.actorID,
+ root: this.rootNode.form(),
+ traits: {},
+ };
+ },
+
+ toString: function() {
+ return "[WalkerActor " + this.actorID + "]";
+ },
+
+ getAnonymousDocumentWalker: function(node, whatToShow, skipTo) {
+ // Allow native anon content (like <video> controls) if preffed on
+ const filter = this.showAllAnonymousContent
+ ? allAnonymousContentTreeWalkerFilter
+ : standardTreeWalkerFilter;
+
+ return new DocumentWalker(node, this.rootWin, {
+ whatToShow,
+ filter,
+ skipTo,
+ showAnonymousContent: true,
+ });
+ },
+
+ getNonAnonymousDocumentWalker: function(node, whatToShow, skipTo) {
+ const nodeFilter = standardTreeWalkerFilter;
+
+ return new DocumentWalker(node, this.rootWin, {
+ whatToShow,
+ nodeFilter,
+ skipTo,
+ showAnonymousContent: false,
+ });
+ },
+
+ /**
+ * Will first try to create a regular anonymous document walker. If it fails, will fall
+ * back on a non-anonymous walker.
+ */
+ getDocumentWalker: function(node, whatToShow, skipTo) {
+ try {
+ return this.getAnonymousDocumentWalker(node, whatToShow, skipTo);
+ } catch (e) {
+ return this.getNonAnonymousDocumentWalker(node, whatToShow, skipTo);
+ }
+ },
+
+ destroy: function() {
+ if (this._destroyed) {
+ return;
+ }
+ this._destroyed = true;
+ protocol.Actor.prototype.destroy.call(this);
+ try {
+ this.clearPseudoClassLocks();
+ this._activePseudoClassLocks = null;
+
+ this.overflowCausingElementsMap.clear();
+ this.overflowCausingElementsMap = null;
+
+ this._hoveredNode = null;
+ this.rootWin = null;
+ this.rootDoc = null;
+ this.rootNode = null;
+ this.layoutHelpers = null;
+ this._orphaned = null;
+ this._retainedOrphans = null;
+ this._nodeActorsMap = null;
+
+ this.targetActor.off("will-navigate", this.onFrameUnload);
+ this.targetActor.off("window-ready", this.onFrameLoad);
+ this.customElementWatcher.off(
+ "element-defined",
+ this.onCustomElementDefined
+ );
+
+ this.chromeEventHandler.removeEventListener(
+ "shadowrootattached",
+ this.onShadowrootattached
+ );
+
+ this.onFrameLoad = null;
+ this.onFrameUnload = null;
+
+ this.customElementWatcher.destroy();
+ this.customElementWatcher = null;
+
+ this.walkerSearch.destroy();
+
+ if (this._nodePicker) {
+ this._nodePicker.destroy();
+ this._nodePicker = null;
+ }
+
+ this.layoutChangeObserver.off("reflows", this._onReflows);
+ this.layoutChangeObserver.off("resize", this._onResize);
+ this.layoutChangeObserver = null;
+ releaseLayoutChangesObserver(this.targetActor);
+
+ eventListenerService.removeListenerChangeListener(
+ this._onEventListenerChange
+ );
+
+ this.onMutations = null;
+
+ this.layoutActor = null;
+ this.targetActor = null;
+ this.chromeEventHandler = null;
+
+ this.emit("destroyed");
+ } catch (e) {
+ console.error(e);
+ }
+ },
+
+ release: function() {},
+
+ unmanage: function(actor) {
+ if (actor instanceof NodeActor) {
+ if (
+ this._activePseudoClassLocks &&
+ this._activePseudoClassLocks.has(actor)
+ ) {
+ this.clearPseudoClassLocks(actor);
+ }
+
+ this.customElementWatcher.unmanageNode(actor);
+
+ this._nodeActorsMap.delete(actor.rawNode);
+ }
+ protocol.Actor.prototype.unmanage.call(this, actor);
+ },
+
+ /**
+ * Determine if the walker has come across this DOM node before.
+ * @param {DOMNode} rawNode
+ * @return {Boolean}
+ */
+ hasNode: function(rawNode) {
+ return this._nodeActorsMap.has(rawNode);
+ },
+
+ /**
+ * If the walker has come across this DOM node before, then get the
+ * corresponding node actor.
+ * @param {DOMNode} rawNode
+ * @return {NodeActor}
+ */
+ getNode: function(rawNode) {
+ return this._nodeActorsMap.get(rawNode);
+ },
+
+ /**
+ * Internal helper that will either retrieve the existing NodeActor for the
+ * provided node or create the actor on the fly if it doesn't exist.
+ * This method should only be called when we are sure that the node should be
+ * known by the client and that the parent node is already known.
+ *
+ * Otherwise prefer `getNode` to only retrieve known actors or `attachElement`
+ * to create node actors recursively.
+ *
+ * @param {DOMNode} node
+ * The node for which we want to create or get an actor
+ * @return {NodeActor} The corresponding NodeActor
+ */
+ _getOrCreateNodeActor: function(node) {
+ let actor = this.getNode(node);
+ if (actor) {
+ return actor;
+ }
+
+ actor = new NodeActor(this, node);
+
+ // Add the node actor as a child of this walker actor, assigning
+ // it an actorID.
+ this.manage(actor);
+ this._nodeActorsMap.set(node, actor);
+
+ if (node.nodeType === Node.DOCUMENT_NODE) {
+ actor.watchDocument(node, this.onMutations);
+ }
+
+ if (isShadowRoot(actor.rawNode)) {
+ actor.watchDocument(node.ownerDocument, this.onMutations);
+ actor.watchSlotchange(this.onSlotchange);
+ }
+
+ this.customElementWatcher.manageNode(actor);
+
+ return actor;
+ },
+
+ /**
+ * When a custom element is defined, send a customElementDefined mutation for all the
+ * NodeActors using this tag name.
+ */
+ onCustomElementDefined: function({ name, actors }) {
+ actors.forEach(actor =>
+ this.queueMutation({
+ target: actor.actorID,
+ type: "customElementDefined",
+ customElementLocation: actor.getCustomElementLocation(),
+ })
+ );
+ },
+
+ _onReflows: function(reflows) {
+ // Going through the nodes the walker knows about, see which ones have had their
+ // display, scrollable or overflow state changed and send events if any.
+ const displayTypeChanges = [];
+ const scrollableStateChanges = [];
+
+ const currentOverflowCausingElementsMap = new Map();
+
+ for (const [node, actor] of this._nodeActorsMap) {
+ if (Cu.isDeadWrapper(node)) {
+ continue;
+ }
+
+ const displayType = actor.displayType;
+ const isDisplayed = actor.isDisplayed;
+
+ if (
+ displayType !== actor.currentDisplayType ||
+ isDisplayed !== actor.wasDisplayed
+ ) {
+ displayTypeChanges.push(actor);
+
+ // Updating the original value
+ actor.currentDisplayType = displayType;
+ actor.wasDisplayed = isDisplayed;
+ }
+
+ const isScrollable = actor.isScrollable;
+ if (isScrollable !== actor.wasScrollable) {
+ scrollableStateChanges.push(actor);
+ actor.wasScrollable = isScrollable;
+ }
+
+ if (isScrollable) {
+ this.updateOverflowCausingElements(
+ actor,
+ currentOverflowCausingElementsMap
+ );
+ }
+ }
+
+ // Get the NodeActor for each node in the symmetric difference of
+ // currentOverflowCausingElementsMap and this.overflowCausingElementsMap
+ const overflowStateChanges = [...currentOverflowCausingElementsMap.keys()]
+ .filter(node => !this.overflowCausingElementsMap.has(node))
+ .concat(
+ [...this.overflowCausingElementsMap.keys()].filter(
+ node => !currentOverflowCausingElementsMap.has(node)
+ )
+ )
+ .filter(node => this.hasNode(node))
+ .map(node => this.getNode(node));
+
+ this.overflowCausingElementsMap = currentOverflowCausingElementsMap;
+
+ if (overflowStateChanges.length) {
+ this.emit("overflow-change", overflowStateChanges);
+ }
+
+ if (displayTypeChanges.length) {
+ this.emit("display-change", displayTypeChanges);
+ }
+
+ if (scrollableStateChanges.length) {
+ this.emit("scrollable-change", scrollableStateChanges);
+ }
+ },
+
+ /**
+ * When the browser window gets resized, relay the event to the front.
+ */
+ _onResize: function() {
+ this.emit("resize");
+ },
+
+ /**
+ * Ensures that the node is attached and it can be accessed from the root.
+ *
+ * @param {(Node|NodeActor)} nodes The nodes
+ * @return {Object} An object compatible with the disconnectedNode type.
+ */
+ attachElement: function(node) {
+ const { nodes, newParents } = this.attachElements([node]);
+ return {
+ node: nodes[0],
+ newParents: newParents,
+ };
+ },
+
+ /**
+ * Ensures that the nodes are attached and they can be accessed from the root.
+ *
+ * @param {(Node[]|NodeActor[])} nodes The nodes
+ * @return {Object} An object compatible with the disconnectedNodeArray type.
+ */
+ attachElements: function(nodes) {
+ const nodeActors = [];
+ const newParents = new Set();
+ for (let node of nodes) {
+ if (!(node instanceof NodeActor)) {
+ // If an anonymous node was passed in and we aren't supposed to know
+ // about it, then consult with the document walker as the source of
+ // truth about which elements exist.
+ if (!this.showAllAnonymousContent && isAnonymous(node)) {
+ node = this.getDocumentWalker(node).currentNode;
+ }
+
+ node = this._getOrCreateNodeActor(node);
+ }
+
+ this.ensurePathToRoot(node, newParents);
+ // If nodes may be an array of raw nodes, we're sure to only have
+ // NodeActors with the following array.
+ nodeActors.push(node);
+ }
+
+ return {
+ nodes: nodeActors,
+ newParents: [...newParents],
+ };
+ },
+
+ /**
+ * Return the document node that contains the given node,
+ * or the root node if no node is specified.
+ * @param NodeActor node
+ * The node whose document is needed, or null to
+ * return the root.
+ */
+ document: function(node) {
+ const doc = isNodeDead(node) ? this.rootDoc : nodeDocument(node.rawNode);
+ return this._getOrCreateNodeActor(doc);
+ },
+
+ /**
+ * Return the documentElement for the document containing the
+ * given node.
+ * @param NodeActor node
+ * The node whose documentElement is requested, or null
+ * to use the root document.
+ */
+ documentElement: function(node) {
+ const elt = isNodeDead(node)
+ ? this.rootDoc.documentElement
+ : nodeDocument(node.rawNode).documentElement;
+ return this._getOrCreateNodeActor(elt);
+ },
+
+ parentNode: function(node) {
+ const parent = this.rawParentNode(node);
+ if (parent) {
+ return this._getOrCreateNodeActor(parent);
+ }
+
+ return null;
+ },
+
+ rawParentNode: function(node) {
+ let parent;
+ try {
+ // If the node is the child of a shadow host, we can not use an anonymous walker to
+ // get the shadow host parent.
+ const walker = isDirectShadowHostChild(node.rawNode)
+ ? this.getNonAnonymousDocumentWalker(node.rawNode)
+ : this.getAnonymousDocumentWalker(node.rawNode);
+ parent = walker.parentNode();
+ } catch (e) {
+ // When getting the parent node for a child of a non-slotted shadow host child,
+ // walker.parentNode() will throw if the walker is anonymous, because non-slotted
+ // shadow host children are not accessible anywhere in the anonymous tree.
+ const walker = this.getNonAnonymousDocumentWalker(node.rawNode);
+ parent = walker.parentNode();
+ }
+
+ return parent;
+ },
+
+ /**
+ * If the given NodeActor only has a single text node as a child with a text
+ * content small enough to be inlined, return that child's NodeActor.
+ *
+ * @param NodeActor node
+ */
+ inlineTextChild: function({ rawNode }) {
+ // Quick checks to prevent creating a new walker if possible.
+ if (
+ isMarkerPseudoElement(rawNode) ||
+ isBeforePseudoElement(rawNode) ||
+ isAfterPseudoElement(rawNode) ||
+ isShadowHost(rawNode) ||
+ rawNode.nodeType != Node.ELEMENT_NODE ||
+ rawNode.children.length > 0 ||
+ isRemoteFrame(rawNode)
+ ) {
+ return undefined;
+ }
+
+ const walker = this.getDocumentWalker(rawNode);
+ const firstChild = walker.firstChild();
+
+ // Bail out if:
+ // - more than one child
+ // - unique child is not a text node
+ // - unique child is a text node, but is too long to be inlined
+ // - we are a slot -> these are always represented on their own lines with
+ // a link to the original node.
+ // - we are a flex item -> these are always shown on their own lines so they can be
+ // selected by the flexbox inspector.
+ const isAssignedSlot =
+ !!firstChild &&
+ rawNode.nodeName === "SLOT" &&
+ isDirectShadowHostChild(firstChild);
+
+ const isFlexItem = !!firstChild?.parentFlexElement;
+
+ if (
+ !firstChild ||
+ walker.nextSibling() ||
+ firstChild.nodeType !== Node.TEXT_NODE ||
+ firstChild.nodeValue.length > gValueSummaryLength ||
+ isAssignedSlot ||
+ isFlexItem
+ ) {
+ return undefined;
+ }
+
+ return this._getOrCreateNodeActor(firstChild);
+ },
+
+ /**
+ * Mark a node as 'retained'.
+ *
+ * A retained node is not released when `releaseNode` is called on its
+ * parent, or when a parent is released with the `cleanup` option to
+ * `getMutations`.
+ *
+ * When a retained node's parent is released, a retained mode is added to
+ * the walker's "retained orphans" list.
+ *
+ * Retained nodes can be deleted by providing the `force` option to
+ * `releaseNode`. They will also be released when their document
+ * has been destroyed.
+ *
+ * Retaining a node makes no promise about its children; They can
+ * still be removed by normal means.
+ */
+ retainNode: function(node) {
+ node.retained = true;
+ },
+
+ /**
+ * Remove the 'retained' mark from a node. If the node was a
+ * retained orphan, release it.
+ */
+ unretainNode: function(node) {
+ node.retained = false;
+ if (this._retainedOrphans.has(node)) {
+ this._retainedOrphans.delete(node);
+ this.releaseNode(node);
+ }
+ },
+
+ /**
+ * Release actors for a node and all child nodes.
+ */
+ releaseNode: function(node, options = {}) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ if (node.retained && !options.force) {
+ this._retainedOrphans.add(node);
+ return;
+ }
+
+ if (node.retained) {
+ // Forcing a retained node to go away.
+ this._retainedOrphans.delete(node);
+ }
+
+ const walker = this.getDocumentWalker(node.rawNode);
+
+ let child = walker.firstChild();
+ while (child) {
+ const childActor = this.getNode(child);
+ if (childActor) {
+ this.releaseNode(childActor, options);
+ }
+ child = walker.nextSibling();
+ }
+
+ node.destroy();
+ },
+
+ /**
+ * Add any nodes between `node` and the walker's root node that have not
+ * yet been seen by the client.
+ */
+ ensurePathToRoot: function(node, newParents = new Set()) {
+ if (!node) {
+ return newParents;
+ }
+ let parent = this.rawParentNode(node);
+ while (parent) {
+ let parentActor = this.getNode(parent);
+ if (parentActor) {
+ // This parent did exist, so the client knows about it.
+ return newParents;
+ }
+ // This parent didn't exist, so hasn't been seen by the client yet.
+ parentActor = this._getOrCreateNodeActor(parent);
+ newParents.add(parentActor);
+ parent = this.rawParentNode(parentActor);
+ }
+ return newParents;
+ },
+
+ /**
+ * Return the number of children under the provided NodeActor.
+ *
+ * @param NodeActor node
+ * See JSDoc for children()
+ * @param object options
+ * See JSDoc for children()
+ * @return Number the number of children
+ */
+ countChildren: function(node, options = {}) {
+ return this._getChildren(node, options).nodes.length;
+ },
+
+ /**
+ * Return children of the given node. By default this method will return
+ * all children of the node, but there are options that can restrict this
+ * to a more manageable subset.
+ *
+ * @param NodeActor node
+ * The node whose children you're curious about.
+ * @param object options
+ * Named options:
+ * `maxNodes`: The set of nodes returned by the method will be no longer
+ * than maxNodes.
+ * `start`: If a node is specified, the list of nodes will start
+ * with the given child. Mutally exclusive with `center`.
+ * `center`: If a node is specified, the given node will be as centered
+ * as possible in the list, given how close to the ends of the child
+ * list it is. Mutually exclusive with `start`.
+ * `whatToShow`: A bitmask of node types that should be included. See
+ * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter.
+ *
+ * @returns an object with three items:
+ * hasFirst: true if the first child of the node is included in the list.
+ * hasLast: true if the last child of the node is included in the list.
+ * nodes: Array of NodeActor representing the nodes returned by the request.
+ */
+ children: function(node, options = {}) {
+ const { hasFirst, hasLast, nodes } = this._getChildren(node, options);
+ return {
+ hasFirst,
+ hasLast,
+ nodes: nodes.map(n => this._getOrCreateNodeActor(n)),
+ };
+ },
+
+ /**
+ * Return chidlren of the given node. Contrary to children children(), this method only
+ * returns DOMNodes. Therefore it will not create NodeActor wrappers and will not
+ * update the nodeActors map for the discovered nodes either. This makes this method
+ * safe to call when you are not sure if the discovered nodes will be communicated to
+ * the client.
+ *
+ * @param NodeActor node
+ * See JSDoc for children()
+ * @param object options
+ * See JSDoc for children()
+ * @return an object with three items:
+ * hasFirst: true if the first child of the node is included in the list.
+ * hasLast: true if the last child of the node is included in the list.
+ * nodes: Array of DOMNodes.
+ */
+ // eslint-disable-next-line complexity
+ _getChildren: function(node, options = {}) {
+ if (isNodeDead(node)) {
+ return { hasFirst: true, hasLast: true, nodes: [] };
+ }
+
+ if (options.center && options.start) {
+ throw Error("Can't specify both 'center' and 'start' options.");
+ }
+ let maxNodes = options.maxNodes || -1;
+ if (maxNodes == -1) {
+ maxNodes = Number.MAX_VALUE;
+ }
+
+ const directShadowHostChild = isDirectShadowHostChild(node.rawNode);
+ const shadowHost = isShadowHost(node.rawNode);
+ const shadowRoot = isShadowRoot(node.rawNode);
+
+ // UA Widgets are internal Firefox widgets such as videocontrols implemented
+ // using shadow DOM. By default, their shadow root should be hidden for web
+ // developers.
+ const isUAWidget =
+ shadowHost && node.rawNode.openOrClosedShadowRoot.isUAWidget();
+ const hideShadowRoot = isUAWidget && !this.showAllAnonymousContent;
+ const showNativeAnonymousChildren =
+ isUAWidget && this.showAllAnonymousContent;
+
+ const templateElement = isTemplateElement(node.rawNode);
+ if (templateElement) {
+ // <template> tags should have a single child pointing to the element's template
+ // content.
+ const documentFragment = node.rawNode.content;
+ const nodes = [documentFragment];
+ return { hasFirst: true, hasLast: true, nodes };
+ }
+
+ // Detect special case of unslotted shadow host children that cannot rely on a
+ // regular anonymous walker.
+ let isUnslottedHostChild = false;
+ if (directShadowHostChild) {
+ try {
+ this.getDocumentWalker(
+ node.rawNode,
+ options.whatToShow,
+ SKIP_TO_SIBLING
+ );
+ } catch (e) {
+ isUnslottedHostChild = true;
+ }
+ }
+
+ const useNonAnonymousWalker =
+ shadowRoot || shadowHost || isUnslottedHostChild;
+
+ // We're going to create a few document walkers with the same filter,
+ // make it easier.
+ const getFilteredWalker = documentWalkerNode => {
+ const { whatToShow } = options;
+
+ // Use SKIP_TO_SIBLING to force the walker to use a sibling of the provided node
+ // in case this one is incompatible with the walker's filter function.
+ const skipTo = SKIP_TO_SIBLING;
+
+ if (useNonAnonymousWalker) {
+ // Do not use an anonymous walker for :
+ // - shadow roots: if the host element has an ::after pseudo element, a walker on
+ // the last child of the shadow root will jump to the ::after element, which is
+ // not a child of the shadow root.
+ // TODO: For this case, should rather use an anonymous walker with a new
+ // dedicated filter.
+ // - shadow hosts: anonymous children of host elements make up the shadow dom,
+ // while we want to return the direct children of the shadow host.
+ // - unslotted host child: if a shadow host child is not slotted, it is not part
+ // of any anonymous tree and cannot be used with anonymous tree walkers.
+ return this.getNonAnonymousDocumentWalker(
+ documentWalkerNode,
+ whatToShow,
+ skipTo
+ );
+ }
+ return this.getDocumentWalker(documentWalkerNode, whatToShow, skipTo);
+ };
+
+ // Need to know the first and last child.
+ const rawNode = node.rawNode;
+ const firstChild = getFilteredWalker(rawNode).firstChild();
+ const lastChild = getFilteredWalker(rawNode).lastChild();
+
+ if (!firstChild && !shadowHost) {
+ // No children, we're done.
+ return { hasFirst: true, hasLast: true, nodes: [] };
+ }
+
+ let nodes = [];
+
+ if (firstChild) {
+ let start;
+ if (options.center) {
+ start = options.center.rawNode;
+ } else if (options.start) {
+ start = options.start.rawNode;
+ } else {
+ start = firstChild;
+ }
+
+ // If we are using a non anonymous walker, we cannot start on:
+ // - a shadow root
+ // - a native anonymous node
+ if (
+ useNonAnonymousWalker &&
+ (isShadowRoot(start) || isNativeAnonymous(start))
+ ) {
+ start = firstChild;
+ }
+
+ // Start by reading backward from the starting point if we're centering...
+ const backwardWalker = getFilteredWalker(start);
+ if (backwardWalker.currentNode != firstChild && options.center) {
+ backwardWalker.previousSibling();
+ const backwardCount = Math.floor(maxNodes / 2);
+ const backwardNodes = this._readBackward(backwardWalker, backwardCount);
+ nodes = backwardNodes;
+ }
+
+ // Then read forward by any slack left in the max children...
+ const forwardWalker = getFilteredWalker(start);
+ const forwardCount = maxNodes - nodes.length;
+ nodes = nodes.concat(this._readForward(forwardWalker, forwardCount));
+
+ // If there's any room left, it means we've run all the way to the end.
+ // If we're centering, check if there are more items to read at the front.
+ const remaining = maxNodes - nodes.length;
+ if (options.center && remaining > 0 && nodes[0].rawNode != firstChild) {
+ const firstNodes = this._readBackward(backwardWalker, remaining);
+
+ // Then put it all back together.
+ nodes = firstNodes.concat(nodes);
+ }
+ }
+
+ let hasFirst, hasLast;
+ if (nodes.length > 0) {
+ // Compare first/last with expected nodes before modifying the nodes array in case
+ // this is a shadow host.
+ hasFirst = nodes[0] == firstChild;
+ hasLast = nodes[nodes.length - 1] == lastChild;
+ } else {
+ // If nodes is still an empty array, we are on a host element with a shadow root but
+ // no direct children.
+ hasFirst = hasLast = true;
+ }
+
+ if (shadowHost) {
+ // Use anonymous walkers to fetch ::marker / ::before / ::after pseudo
+ // elements
+ const firstChildWalker = this.getDocumentWalker(node.rawNode);
+ const first = firstChildWalker.firstChild();
+ const hasMarker =
+ first && first.nodeName === "_moz_generated_content_marker";
+ const maybeBeforeNode = hasMarker
+ ? firstChildWalker.nextSibling()
+ : first;
+ const hasBefore =
+ maybeBeforeNode &&
+ maybeBeforeNode.nodeName === "_moz_generated_content_before";
+
+ const lastChildWalker = this.getDocumentWalker(node.rawNode);
+ const last = lastChildWalker.lastChild();
+ const hasAfter = last && last.nodeName === "_moz_generated_content_after";
+
+ nodes = [
+ // #shadow-root
+ ...(hideShadowRoot ? [] : [node.rawNode.openOrClosedShadowRoot]),
+ // ::marker
+ ...(hasMarker ? [first] : []),
+ // ::before
+ ...(hasBefore ? [maybeBeforeNode] : []),
+ // shadow host direct children
+ ...nodes,
+ // native anonymous content for UA widgets
+ ...(showNativeAnonymousChildren
+ ? this.getNativeAnonymousChildren(node.rawNode)
+ : []),
+ // ::after
+ ...(hasAfter ? [last] : []),
+ ];
+ }
+
+ return { hasFirst, hasLast, nodes };
+ },
+
+ getNativeAnonymousChildren: function(rawNode) {
+ // Get an anonymous walker and start on the first child.
+ const walker = this.getDocumentWalker(rawNode);
+ let node = walker.firstChild();
+
+ const nodes = [];
+ while (node) {
+ // We only want native anonymous content here.
+ if (isNativeAnonymous(node)) {
+ nodes.push(node);
+ }
+ node = walker.nextSibling();
+ }
+ return nodes;
+ },
+
+ /**
+ * Get the next sibling of a given node. Getting nodes one at a time
+ * might be inefficient, be careful.
+ *
+ * @param object options
+ * Named options:
+ * `whatToShow`: A bitmask of node types that should be included. See
+ * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter.
+ */
+ nextSibling: function(node, options = {}) {
+ if (isNodeDead(node)) {
+ return null;
+ }
+
+ const walker = this.getDocumentWalker(node.rawNode, options.whatToShow);
+ const sibling = walker.nextSibling();
+ return sibling ? this._getOrCreateNodeActor(sibling) : null;
+ },
+
+ /**
+ * Get the previous sibling of a given node. Getting nodes one at a time
+ * might be inefficient, be careful.
+ *
+ * @param object options
+ * Named options:
+ * `whatToShow`: A bitmask of node types that should be included. See
+ * https://developer.mozilla.org/en-US/docs/Web/API/NodeFilter.
+ */
+ previousSibling: function(node, options = {}) {
+ if (isNodeDead(node)) {
+ return null;
+ }
+
+ const walker = this.getDocumentWalker(node.rawNode, options.whatToShow);
+ const sibling = walker.previousSibling();
+ return sibling ? this._getOrCreateNodeActor(sibling) : null;
+ },
+
+ /**
+ * Helper function for the `children` method: Read forward in the sibling
+ * list into an array with `count` items, including the current node.
+ */
+ _readForward: function(walker, count) {
+ const ret = [];
+
+ let node = walker.currentNode;
+ do {
+ if (!walker.isSkippedNode(node)) {
+ // The walker can be on a node that would be filtered out if it didn't find any
+ // other node to fallback to.
+ ret.push(node);
+ }
+ node = walker.nextSibling();
+ } while (node && --count);
+ return ret;
+ },
+
+ /**
+ * Helper function for the `children` method: Read backward in the sibling
+ * list into an array with `count` items, including the current node.
+ */
+ _readBackward: function(walker, count) {
+ const ret = [];
+
+ let node = walker.currentNode;
+ do {
+ if (!walker.isSkippedNode(node)) {
+ // The walker can be on a node that would be filtered out if it didn't find any
+ // other node to fallback to.
+ ret.push(node);
+ }
+ node = walker.previousSibling();
+ } while (node && --count);
+ ret.reverse();
+ return ret;
+ },
+
+ /**
+ * Return the first node in the document that matches the given selector.
+ * See https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelector
+ *
+ * @param NodeActor baseNode
+ * @param string selector
+ */
+ querySelector: function(baseNode, selector) {
+ if (isNodeDead(baseNode)) {
+ return {};
+ }
+
+ const node = baseNode.rawNode.querySelector(selector);
+ if (!node) {
+ return {};
+ }
+
+ return this.attachElement(node);
+ },
+
+ /**
+ * Return a NodeListActor with all nodes that match the given selector.
+ * See https://developer.mozilla.org/en-US/docs/Web/API/Element.querySelectorAll
+ *
+ * @param NodeActor baseNode
+ * @param string selector
+ */
+ querySelectorAll: function(baseNode, selector) {
+ let nodeList = null;
+
+ try {
+ nodeList = baseNode.rawNode.querySelectorAll(selector);
+ } catch (e) {
+ // Bad selector. Do nothing as the selector can come from a searchbox.
+ }
+
+ return new NodeListActor(this, nodeList);
+ },
+
+ /**
+ * Get a list of nodes that match the given selector in all known frames of
+ * the current content page.
+ * @param {String} selector.
+ * @return {Array}
+ */
+ _multiFrameQuerySelectorAll: function(selector) {
+ let nodes = [];
+
+ for (const { document } of this.targetActor.windows) {
+ try {
+ nodes = [...nodes, ...document.querySelectorAll(selector)];
+ } catch (e) {
+ // Bad selector. Do nothing as the selector can come from a searchbox.
+ }
+ }
+
+ return nodes;
+ },
+
+ /**
+ * Return a NodeListActor with all nodes that match the given selector in all
+ * frames of the current content page.
+ * @param {String} selector
+ */
+ multiFrameQuerySelectorAll: function(selector) {
+ return new NodeListActor(this, this._multiFrameQuerySelectorAll(selector));
+ },
+
+ /**
+ * Get a list of nodes that match the given XPath in all known frames of
+ * the current content page.
+ * @param {String} xPath.
+ * @return {Array}
+ */
+ _multiFrameXPath: function(xPath) {
+ const nodes = [];
+
+ for (const window of this.targetActor.windows) {
+ const document = window.document;
+ try {
+ const result = document.evaluate(
+ xPath,
+ document.documentElement,
+ null,
+ window.XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,
+ null
+ );
+
+ for (let i = 0; i < result.snapshotLength; i++) {
+ nodes.push(result.snapshotItem(i));
+ }
+ } catch (e) {
+ // Bad XPath. Do nothing as the XPath can come from a searchbox.
+ }
+ }
+
+ return nodes;
+ },
+
+ /**
+ * Return a NodeListActor with all nodes that match the given XPath in all
+ * frames of the current content page.
+ * @param {String} xPath
+ */
+ multiFrameXPath: function(xPath) {
+ return new NodeListActor(this, this._multiFrameXPath(xPath));
+ },
+
+ /**
+ * Search the document for a given string.
+ * Results will be searched with the walker-search module (searches through
+ * tag names, attribute names and values, and text contents).
+ *
+ * @returns {searchresult}
+ * - {NodeList} list
+ * - {Array<Object>} metadata. Extra information with indices that
+ * match up with node list.
+ */
+ search: function(query) {
+ const results = this.walkerSearch.search(query);
+ const nodeList = new NodeListActor(
+ this,
+ results.map(r => r.node)
+ );
+
+ return {
+ list: nodeList,
+ metadata: [],
+ };
+ },
+
+ /**
+ * Returns a list of matching results for CSS selector autocompletion.
+ *
+ * @param string query
+ * The selector query being completed
+ * @param string completing
+ * The exact token being completed out of the query
+ * @param string selectorState
+ * One of "pseudo", "id", "tag", "class", "null"
+ */
+ // eslint-disable-next-line complexity
+ getSuggestionsForQuery: function(query, completing, selectorState) {
+ const sugs = {
+ classes: new Map(),
+ tags: new Map(),
+ ids: new Map(),
+ };
+ let result = [];
+ let nodes = null;
+ // Filtering and sorting the results so that protocol transfer is miminal.
+ switch (selectorState) {
+ case "pseudo":
+ result = PSEUDO_SELECTORS.filter(item => {
+ return item[0].startsWith(":" + completing);
+ });
+ break;
+
+ case "class":
+ if (!query) {
+ nodes = this._multiFrameQuerySelectorAll("[class]");
+ } else {
+ nodes = this._multiFrameQuerySelectorAll(query);
+ }
+ for (const node of nodes) {
+ for (const className of node.classList) {
+ sugs.classes.set(className, (sugs.classes.get(className) | 0) + 1);
+ }
+ }
+ sugs.classes.delete("");
+ sugs.classes.delete(HIDDEN_CLASS);
+ for (const [className, count] of sugs.classes) {
+ if (className.startsWith(completing)) {
+ result.push(["." + CSS.escape(className), count, selectorState]);
+ }
+ }
+ break;
+
+ case "id":
+ if (!query) {
+ nodes = this._multiFrameQuerySelectorAll("[id]");
+ } else {
+ nodes = this._multiFrameQuerySelectorAll(query);
+ }
+ for (const node of nodes) {
+ sugs.ids.set(node.id, (sugs.ids.get(node.id) | 0) + 1);
+ }
+ for (const [id, count] of sugs.ids) {
+ if (id.startsWith(completing) && id !== "") {
+ result.push(["#" + CSS.escape(id), count, selectorState]);
+ }
+ }
+ break;
+
+ case "tag":
+ if (!query) {
+ nodes = this._multiFrameQuerySelectorAll("*");
+ } else {
+ nodes = this._multiFrameQuerySelectorAll(query);
+ }
+ for (const node of nodes) {
+ const tag = node.localName;
+ sugs.tags.set(tag, (sugs.tags.get(tag) | 0) + 1);
+ }
+ for (const [tag, count] of sugs.tags) {
+ if (new RegExp("^" + completing + ".*", "i").test(tag)) {
+ result.push([tag, count, selectorState]);
+ }
+ }
+
+ // For state 'tag' (no preceding # or .) and when there's no query (i.e.
+ // only one word) then search for the matching classes and ids
+ if (!query) {
+ result = [
+ ...result,
+ ...this.getSuggestionsForQuery(null, completing, "class")
+ .suggestions,
+ ...this.getSuggestionsForQuery(null, completing, "id").suggestions,
+ ];
+ }
+
+ break;
+
+ case "null":
+ nodes = this._multiFrameQuerySelectorAll(query);
+ for (const node of nodes) {
+ sugs.ids.set(node.id, (sugs.ids.get(node.id) | 0) + 1);
+ const tag = node.localName;
+ sugs.tags.set(tag, (sugs.tags.get(tag) | 0) + 1);
+ for (const className of node.classList) {
+ sugs.classes.set(className, (sugs.classes.get(className) | 0) + 1);
+ }
+ }
+ for (const [tag, count] of sugs.tags) {
+ tag && result.push([tag, count]);
+ }
+ for (const [id, count] of sugs.ids) {
+ id && result.push(["#" + id, count]);
+ }
+ sugs.classes.delete("");
+ sugs.classes.delete(HIDDEN_CLASS);
+ for (const [className, count] of sugs.classes) {
+ className && result.push(["." + className, count]);
+ }
+ }
+
+ // Sort by count (desc) and name (asc)
+ result = result.sort((a, b) => {
+ // Computed a sortable string with first the inverted count, then the name
+ let sortA = 10000 - a[1] + a[0];
+ let sortB = 10000 - b[1] + b[0];
+
+ // Prefixing ids, classes and tags, to group results
+ const firstA = a[0].substring(0, 1);
+ const firstB = b[0].substring(0, 1);
+
+ if (firstA === "#") {
+ sortA = "2" + sortA;
+ } else if (firstA === ".") {
+ sortA = "1" + sortA;
+ } else {
+ sortA = "0" + sortA;
+ }
+
+ if (firstB === "#") {
+ sortB = "2" + sortB;
+ } else if (firstB === ".") {
+ sortB = "1" + sortB;
+ } else {
+ sortB = "0" + sortB;
+ }
+
+ // String compare
+ return sortA.localeCompare(sortB);
+ });
+
+ result = result.slice(0, 25);
+
+ return {
+ query: query,
+ suggestions: result,
+ };
+ },
+
+ /**
+ * Add a pseudo-class lock to a node.
+ *
+ * @param NodeActor node
+ * @param string pseudo
+ * A pseudoclass: ':hover', ':active', ':focus', ':focus-within'
+ * @param options
+ * Options object:
+ * `parents`: True if the pseudo-class should be added
+ * to parent nodes.
+ * `enabled`: False if the pseudo-class should be locked
+ * to 'off'. Defaults to true.
+ *
+ * @returns An empty packet. A "pseudoClassLock" mutation will
+ * be queued for any changed nodes.
+ */
+ addPseudoClassLock: function(node, pseudo, options = {}) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ // There can be only one node locked per pseudo, so dismiss all existing
+ // ones
+ for (const locked of this._activePseudoClassLocks) {
+ if (InspectorUtils.hasPseudoClassLock(locked.rawNode, pseudo)) {
+ this._removePseudoClassLock(locked, pseudo);
+ }
+ }
+
+ const enabled = options.enabled === undefined || options.enabled;
+ this._addPseudoClassLock(node, pseudo, enabled);
+
+ if (!options.parents) {
+ return;
+ }
+
+ const walker = this.getDocumentWalker(node.rawNode);
+ let cur;
+ while ((cur = walker.parentNode())) {
+ const curNode = this._getOrCreateNodeActor(cur);
+ this._addPseudoClassLock(curNode, pseudo, enabled);
+ }
+ },
+
+ _queuePseudoClassMutation: function(node) {
+ this.queueMutation({
+ target: node.actorID,
+ type: "pseudoClassLock",
+ pseudoClassLocks: node.writePseudoClassLocks(),
+ });
+ },
+
+ _addPseudoClassLock: function(node, pseudo, enabled) {
+ if (node.rawNode.nodeType !== Node.ELEMENT_NODE) {
+ return false;
+ }
+ InspectorUtils.addPseudoClassLock(node.rawNode, pseudo, enabled);
+ this._activePseudoClassLocks.add(node);
+ this._queuePseudoClassMutation(node);
+ return true;
+ },
+
+ hideNode: function(node) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ loadSheet(node.rawNode.ownerGlobal, HELPER_SHEET);
+ node.rawNode.classList.add(HIDDEN_CLASS);
+ },
+
+ unhideNode: function(node) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ node.rawNode.classList.remove(HIDDEN_CLASS);
+ },
+
+ /**
+ * Remove a pseudo-class lock from a node.
+ *
+ * @param NodeActor node
+ * @param string pseudo
+ * A pseudoclass: ':hover', ':active', ':focus', ':focus-within'
+ * @param options
+ * Options object:
+ * `parents`: True if the pseudo-class should be removed
+ * from parent nodes.
+ *
+ * @returns An empty response. "pseudoClassLock" mutations
+ * will be emitted for any changed nodes.
+ */
+ removePseudoClassLock: function(node, pseudo, options = {}) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ this._removePseudoClassLock(node, pseudo);
+
+ // Remove pseudo class for children as we don't want to allow
+ // turning it on for some childs without setting it on some parents
+ for (const locked of this._activePseudoClassLocks) {
+ if (
+ node.rawNode.contains(locked.rawNode) &&
+ InspectorUtils.hasPseudoClassLock(locked.rawNode, pseudo)
+ ) {
+ this._removePseudoClassLock(locked, pseudo);
+ }
+ }
+
+ if (!options.parents) {
+ return;
+ }
+
+ const walker = this.getDocumentWalker(node.rawNode);
+ let cur;
+ while ((cur = walker.parentNode())) {
+ const curNode = this._getOrCreateNodeActor(cur);
+ this._removePseudoClassLock(curNode, pseudo);
+ }
+ },
+
+ _removePseudoClassLock: function(node, pseudo) {
+ if (node.rawNode.nodeType != Node.ELEMENT_NODE) {
+ return false;
+ }
+ InspectorUtils.removePseudoClassLock(node.rawNode, pseudo);
+ if (!node.writePseudoClassLocks()) {
+ this._activePseudoClassLocks.delete(node);
+ }
+
+ this._queuePseudoClassMutation(node);
+ return true;
+ },
+
+ /**
+ * Clear all the pseudo-classes on a given node or all nodes.
+ * @param {NodeActor} node Optional node to clear pseudo-classes on
+ */
+ clearPseudoClassLocks: function(node) {
+ if (node && isNodeDead(node)) {
+ return;
+ }
+
+ if (node) {
+ InspectorUtils.clearPseudoClassLocks(node.rawNode);
+ this._activePseudoClassLocks.delete(node);
+ this._queuePseudoClassMutation(node);
+ } else {
+ for (const locked of this._activePseudoClassLocks) {
+ InspectorUtils.clearPseudoClassLocks(locked.rawNode);
+ this._activePseudoClassLocks.delete(locked);
+ this._queuePseudoClassMutation(locked);
+ }
+ }
+ },
+
+ /**
+ * Get a node's innerHTML property.
+ */
+ innerHTML: function(node) {
+ let html = "";
+ if (!isNodeDead(node)) {
+ html = node.rawNode.innerHTML;
+ }
+ return LongStringActor(this.conn, html);
+ },
+
+ /**
+ * Set a node's innerHTML property.
+ *
+ * @param {NodeActor} node The node.
+ * @param {string} value The piece of HTML content.
+ */
+ setInnerHTML: function(node, value) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ const rawNode = node.rawNode;
+ if (
+ rawNode.nodeType !== rawNode.ownerDocument.ELEMENT_NODE &&
+ rawNode.nodeType !== rawNode.ownerDocument.DOCUMENT_FRAGMENT_NODE
+ ) {
+ throw new Error("Can only change innerHTML to element or fragment nodes");
+ }
+ // eslint-disable-next-line no-unsanitized/property
+ rawNode.innerHTML = value;
+ },
+
+ /**
+ * Get a node's outerHTML property.
+ *
+ * @param {NodeActor} node The node.
+ */
+ outerHTML: function(node) {
+ let outerHTML = "";
+ if (!isNodeDead(node)) {
+ outerHTML = node.rawNode.outerHTML;
+ }
+ return LongStringActor(this.conn, outerHTML);
+ },
+
+ /**
+ * Set a node's outerHTML property.
+ *
+ * @param {NodeActor} node The node.
+ * @param {string} value The piece of HTML content.
+ */
+ setOuterHTML: function(node, value) {
+ if (isNodeDead(node)) {
+ return;
+ }
+
+ const rawNode = node.rawNode;
+ const doc = nodeDocument(rawNode);
+ const win = doc.defaultView;
+ let parser;
+ if (!win) {
+ throw new Error("The window object shouldn't be null");
+ } else {
+ // We create DOMParser under window object because we want a content
+ // DOMParser, which means all the DOM objects created by this DOMParser
+ // will be in the same DocGroup as rawNode.parentNode. Then the newly
+ // created nodes can be adopted into rawNode.parentNode.
+ parser = new win.DOMParser();
+ }
+ const parsedDOM = parser.parseFromString(value, "text/html");
+ const parentNode = rawNode.parentNode;
+
+ // Special case for head and body. Setting document.body.outerHTML
+ // creates an extra <head> tag, and document.head.outerHTML creates
+ // an extra <body>. So instead we will call replaceChild with the
+ // parsed DOM, assuming that they aren't trying to set both tags at once.
+ if (rawNode.tagName === "BODY") {
+ if (parsedDOM.head.innerHTML === "") {
+ parentNode.replaceChild(parsedDOM.body, rawNode);
+ } else {
+ // eslint-disable-next-line no-unsanitized/property
+ rawNode.outerHTML = value;
+ }
+ } else if (rawNode.tagName === "HEAD") {
+ if (parsedDOM.body.innerHTML === "") {
+ parentNode.replaceChild(parsedDOM.head, rawNode);
+ } else {
+ // eslint-disable-next-line no-unsanitized/property
+ rawNode.outerHTML = value;
+ }
+ } else if (node.isDocumentElement()) {
+ // Unable to set outerHTML on the document element. Fall back by
+ // setting attributes manually, then replace the body and head elements.
+ const finalAttributeModifications = [];
+ const attributeModifications = {};
+ for (const attribute of rawNode.attributes) {
+ attributeModifications[attribute.name] = null;
+ }
+ for (const attribute of parsedDOM.documentElement.attributes) {
+ attributeModifications[attribute.name] = attribute.value;
+ }
+ for (const key in attributeModifications) {
+ finalAttributeModifications.push({
+ attributeName: key,
+ newValue: attributeModifications[key],
+ });
+ }
+ node.modifyAttributes(finalAttributeModifications);
+ rawNode.replaceChild(parsedDOM.head, rawNode.querySelector("head"));
+ rawNode.replaceChild(parsedDOM.body, rawNode.querySelector("body"));
+ } else {
+ // eslint-disable-next-line no-unsanitized/property
+ rawNode.outerHTML = value;
+ }
+ },
+
+ /**
+ * Insert adjacent HTML to a node.
+ *
+ * @param {Node} node
+ * @param {string} position One of "beforeBegin", "afterBegin", "beforeEnd",
+ * "afterEnd" (see Element.insertAdjacentHTML).
+ * @param {string} value The HTML content.
+ */
+ insertAdjacentHTML: function(node, position, value) {
+ if (isNodeDead(node)) {
+ return { node: [], newParents: [] };
+ }
+
+ const rawNode = node.rawNode;
+ const isInsertAsSibling =
+ position === "beforeBegin" || position === "afterEnd";
+
+ // Don't insert anything adjacent to the document element.
+ if (isInsertAsSibling && node.isDocumentElement()) {
+ throw new Error("Can't insert adjacent element to the root.");
+ }
+
+ const rawParentNode = rawNode.parentNode;
+ if (!rawParentNode && isInsertAsSibling) {
+ throw new Error("Can't insert as sibling without parent node.");
+ }
+
+ // We can't use insertAdjacentHTML, because we want to return the nodes
+ // being created (so the front can remove them if the user undoes
+ // the change). So instead, use Range.createContextualFragment().
+ const range = rawNode.ownerDocument.createRange();
+ if (position === "beforeBegin" || position === "afterEnd") {
+ range.selectNode(rawNode);
+ } else {
+ range.selectNodeContents(rawNode);
+ }
+ // eslint-disable-next-line no-unsanitized/method
+ const docFrag = range.createContextualFragment(value);
+ const newRawNodes = Array.from(docFrag.childNodes);
+ switch (position) {
+ case "beforeBegin":
+ rawParentNode.insertBefore(docFrag, rawNode);
+ break;
+ case "afterEnd":
+ // Note: if the second argument is null, rawParentNode.insertBefore
+ // behaves like rawParentNode.appendChild.
+ rawParentNode.insertBefore(docFrag, rawNode.nextSibling);
+ break;
+ case "afterBegin":
+ rawNode.insertBefore(docFrag, rawNode.firstChild);
+ break;
+ case "beforeEnd":
+ rawNode.appendChild(docFrag);
+ break;
+ default:
+ throw new Error(
+ "Invalid position value. Must be either " +
+ "'beforeBegin', 'beforeEnd', 'afterBegin' or 'afterEnd'."
+ );
+ }
+
+ return this.attachElements(newRawNodes);
+ },
+
+ /**
+ * Duplicate a specified node
+ *
+ * @param {NodeActor} node The node to duplicate.
+ */
+ duplicateNode: function({ rawNode }) {
+ const clonedNode = rawNode.cloneNode(true);
+ rawNode.parentNode.insertBefore(clonedNode, rawNode.nextSibling);
+ },
+
+ /**
+ * Test whether a node is a document or a document element.
+ *
+ * @param {NodeActor} node The node to remove.
+ * @return {boolean} True if the node is a document or a document element.
+ */
+ isDocumentOrDocumentElementNode: function(node) {
+ return (
+ (node.rawNode.ownerDocument &&
+ node.rawNode.ownerDocument.documentElement === this.rawNode) ||
+ node.rawNode.nodeType === Node.DOCUMENT_NODE
+ );
+ },
+
+ /**
+ * Removes a node from its parent node.
+ *
+ * @param {NodeActor} node The node to remove.
+ * @returns The node's nextSibling before it was removed.
+ */
+ removeNode: function(node) {
+ if (isNodeDead(node) || this.isDocumentOrDocumentElementNode(node)) {
+ throw Error("Cannot remove document, document elements or dead nodes.");
+ }
+
+ const nextSibling = this.nextSibling(node);
+ node.rawNode.remove();
+ // Mutation events will take care of the rest.
+ return nextSibling;
+ },
+
+ /**
+ * Removes an array of nodes from their parent node.
+ *
+ * @param {NodeActor[]} nodes The nodes to remove.
+ */
+ removeNodes: function(nodes) {
+ // Check that all nodes are valid before processing the removals.
+ for (const node of nodes) {
+ if (isNodeDead(node) || this.isDocumentOrDocumentElementNode(node)) {
+ throw Error("Cannot remove document, document elements or dead nodes");
+ }
+ }
+
+ for (const node of nodes) {
+ node.rawNode.remove();
+ // Mutation events will take care of the rest.
+ }
+ },
+
+ /**
+ * Insert a node into the DOM.
+ */
+ insertBefore: function(node, parent, sibling) {
+ if (
+ isNodeDead(node) ||
+ isNodeDead(parent) ||
+ (sibling && isNodeDead(sibling))
+ ) {
+ return;
+ }
+
+ const rawNode = node.rawNode;
+ const rawParent = parent.rawNode;
+ const rawSibling = sibling ? sibling.rawNode : null;
+
+ // Don't bother inserting a node if the document position isn't going
+ // to change. This prevents needless iframes reloading and mutations.
+ if (rawNode.parentNode === rawParent) {
+ let currentNextSibling = this.nextSibling(node);
+ currentNextSibling = currentNextSibling
+ ? currentNextSibling.rawNode
+ : null;
+
+ if (rawNode === rawSibling || currentNextSibling === rawSibling) {
+ return;
+ }
+ }
+
+ rawParent.insertBefore(rawNode, rawSibling);
+ },
+
+ /**
+ * Editing a node's tagname actually means creating a new node with the same
+ * attributes, removing the node and inserting the new one instead.
+ * This method does not return anything as mutation events are taking care of
+ * informing the consumers about changes.
+ */
+ editTagName: function(node, tagName) {
+ if (isNodeDead(node)) {
+ return null;
+ }
+
+ const oldNode = node.rawNode;
+
+ // Create a new element with the same attributes as the current element and
+ // prepare to replace the current node with it.
+ let newNode;
+ try {
+ newNode = nodeDocument(oldNode).createElement(tagName);
+ } catch (x) {
+ // Failed to create a new element with that tag name, ignore the change,
+ // and signal the error to the front.
+ return Promise.reject(
+ new Error("Could not change node's tagName to " + tagName)
+ );
+ }
+
+ const attrs = oldNode.attributes;
+ for (let i = 0; i < attrs.length; i++) {
+ newNode.setAttribute(attrs[i].name, attrs[i].value);
+ }
+
+ // Insert the new node, and transfer the old node's children.
+ oldNode.parentNode.insertBefore(newNode, oldNode);
+ while (oldNode.firstChild) {
+ newNode.appendChild(oldNode.firstChild);
+ }
+
+ oldNode.remove();
+ return null;
+ },
+
+ /**
+ * Gets the state of the mutation breakpoint types for this actor.
+ *
+ * @param {NodeActor} node The node to get breakpoint info for.
+ */
+ getMutationBreakpoints(node) {
+ let bps;
+ if (!isNodeDead(node)) {
+ bps = this._breakpointInfoForNode(node.rawNode);
+ }
+
+ return (
+ bps || {
+ subtree: false,
+ removal: false,
+ attribute: false,
+ }
+ );
+ },
+
+ /**
+ * Set the state of some subset of mutation breakpoint types for this actor.
+ *
+ * @param {NodeActor} node The node to set breakpoint info for.
+ * @param {Object} bps A subset of the breakpoints for this actor that
+ * should be updated to new states.
+ */
+ setMutationBreakpoints(node, bps) {
+ if (isNodeDead(node)) {
+ return;
+ }
+ const rawNode = node.rawNode;
+
+ if (rawNode.ownerDocument && !rawNode.ownerDocument.contains(rawNode)) {
+ // We only allow watching for mutations on nodes that are attached to
+ // documents. That allows us to clean up our mutation listeners when all
+ // of the watched nodes have been removed from the document.
+ return;
+ }
+
+ // This argument has nullable fields so we want to only update boolean
+ // field values.
+ const bpsForNode = Object.keys(bps).reduce((obj, bp) => {
+ if (typeof bps[bp] === "boolean") {
+ obj[bp] = bps[bp];
+ }
+ return obj;
+ }, {});
+
+ this._updateMutationBreakpointState("api", rawNode, {
+ ...this.getMutationBreakpoints(node),
+ ...bpsForNode,
+ });
+ },
+
+ /**
+ * Update the mutation breakpoint state for the given DOM node.
+ *
+ * @param {Node} rawNode The DOM node.
+ * @param {Object} bpsForNode The state of each mutation bp type we support.
+ */
+ _updateMutationBreakpointState(mutationReason, rawNode, bpsForNode) {
+ const rawDoc = rawNode.ownerDocument || rawNode;
+
+ const docMutationBreakpoints = this._mutationBreakpointsForDoc(
+ rawDoc,
+ true /* createIfNeeded */
+ );
+ let originalBpsForNode = this._breakpointInfoForNode(rawNode);
+
+ if (!bpsForNode && !originalBpsForNode) {
+ return;
+ }
+
+ bpsForNode = bpsForNode || {};
+ originalBpsForNode = originalBpsForNode || {};
+
+ if (Object.values(bpsForNode).some(Boolean)) {
+ docMutationBreakpoints.nodes.set(rawNode, bpsForNode);
+ } else {
+ docMutationBreakpoints.nodes.delete(rawNode);
+ }
+ if (originalBpsForNode.subtree && !bpsForNode.subtree) {
+ docMutationBreakpoints.counts.subtree -= 1;
+ } else if (!originalBpsForNode.subtree && bpsForNode.subtree) {
+ docMutationBreakpoints.counts.subtree += 1;
+ }
+
+ if (originalBpsForNode.removal && !bpsForNode.removal) {
+ docMutationBreakpoints.counts.removal -= 1;
+ } else if (!originalBpsForNode.removal && bpsForNode.removal) {
+ docMutationBreakpoints.counts.removal += 1;
+ }
+
+ if (originalBpsForNode.attribute && !bpsForNode.attribute) {
+ docMutationBreakpoints.counts.attribute -= 1;
+ } else if (!originalBpsForNode.attribute && bpsForNode.attribute) {
+ docMutationBreakpoints.counts.attribute += 1;
+ }
+
+ this._updateDocumentMutationListeners(rawDoc);
+
+ const actor = this.getNode(rawNode);
+ if (actor) {
+ this.queueMutation({
+ target: actor.actorID,
+ type: "mutationBreakpoint",
+ mutationBreakpoints: this.getMutationBreakpoints(actor),
+ mutationReason,
+ });
+ }
+ },
+
+ /**
+ * Controls whether this DOM document has event listeners attached for
+ * handling of DOM mutation breakpoints.
+ *
+ * @param {Document} rawDoc The DOM document.
+ */
+ _updateDocumentMutationListeners(rawDoc) {
+ const docMutationBreakpoints = this._mutationBreakpointsForDoc(rawDoc);
+ if (!docMutationBreakpoints) {
+ return;
+ }
+
+ const origFlag = rawDoc.dontWarnAboutMutationEventsAndAllowSlowDOMMutations;
+ rawDoc.dontWarnAboutMutationEventsAndAllowSlowDOMMutations = true;
+
+ if (docMutationBreakpoints.counts.subtree > 0) {
+ eventListenerService.addSystemEventListener(
+ rawDoc,
+ "DOMNodeInserted",
+ this.onNodeInserted,
+ true /* capture */
+ );
+ } else {
+ eventListenerService.removeSystemEventListener(
+ rawDoc,
+ "DOMNodeInserted",
+ this.onNodeInserted,
+ true /* capture */
+ );
+ }
+
+ if (
+ docMutationBreakpoints.counts.subtree > 0 ||
+ docMutationBreakpoints.counts.removal > 0 ||
+ docMutationBreakpoints.counts.attribute > 0
+ ) {
+ eventListenerService.addSystemEventListener(
+ rawDoc,
+ "DOMNodeRemoved",
+ this.onNodeRemoved,
+ true /* capture */
+ );
+ } else {
+ eventListenerService.removeSystemEventListener(
+ rawDoc,
+ "DOMNodeRemoved",
+ this.onNodeRemoved,
+ true /* capture */
+ );
+ }
+
+ if (docMutationBreakpoints.counts.attribute > 0) {
+ eventListenerService.addSystemEventListener(
+ rawDoc,
+ "DOMAttrModified",
+ this.onAttributeModified,
+ true /* capture */
+ );
+ } else {
+ eventListenerService.removeSystemEventListener(
+ rawDoc,
+ "DOMAttrModified",
+ this.onAttributeModified,
+ true /* capture */
+ );
+ }
+
+ rawDoc.dontWarnAboutMutationEventsAndAllowSlowDOMMutations = origFlag;
+ },
+
+ _breakOnMutation: function(mutationType, targetNode, ancestorNode, action) {
+ this.targetActor.threadActor.pauseForMutationBreakpoint(
+ mutationType,
+ targetNode,
+ ancestorNode,
+ action
+ );
+ },
+
+ _mutationBreakpointsForDoc(rawDoc, createIfNeeded = false) {
+ let docMutationBreakpoints = this._mutationBreakpoints.get(rawDoc);
+ if (!docMutationBreakpoints && createIfNeeded) {
+ docMutationBreakpoints = {
+ counts: {
+ subtree: 0,
+ removal: 0,
+ attribute: 0,
+ },
+ nodes: new Map(),
+ };
+ this._mutationBreakpoints.set(rawDoc, docMutationBreakpoints);
+ }
+ return docMutationBreakpoints;
+ },
+
+ _breakpointInfoForNode: function(target) {
+ const docMutationBreakpoints = this._mutationBreakpointsForDoc(
+ target.ownerDocument || target
+ );
+ return (
+ (docMutationBreakpoints && docMutationBreakpoints.nodes.get(target)) ||
+ null
+ );
+ },
+
+ onNodeInserted: function(evt) {
+ this.onSubtreeModified(evt, "add");
+ },
+
+ onNodeRemoved: function(evt) {
+ const mutationBpInfo = this._breakpointInfoForNode(evt.target);
+ const hasNodeRemovalEvent = mutationBpInfo?.removal;
+
+ this._clearMutationBreakpointsFromSubtree(evt.target);
+
+ if (hasNodeRemovalEvent) {
+ this._breakOnMutation("nodeRemoved", evt.target);
+ } else {
+ this.onSubtreeModified(evt, "remove");
+ }
+ },
+
+ onAttributeModified: function(evt) {
+ const mutationBpInfo = this._breakpointInfoForNode(evt.target);
+ if (mutationBpInfo?.attribute) {
+ this._breakOnMutation("attributeModified", evt.target);
+ }
+ },
+
+ onSubtreeModified: function(evt, action) {
+ let node = evt.target;
+ while ((node = node.parentNode) !== null) {
+ const mutationBpInfo = this._breakpointInfoForNode(node);
+ if (mutationBpInfo?.subtree) {
+ this._breakOnMutation("subtreeModified", evt.target, node, action);
+ break;
+ }
+ }
+ },
+
+ _clearMutationBreakpointsFromSubtree: function(targetNode) {
+ const targetDoc = targetNode.ownerDocument || targetNode;
+ const docMutationBreakpoints = this._mutationBreakpointsForDoc(targetDoc);
+ if (!docMutationBreakpoints || docMutationBreakpoints.nodes.size === 0) {
+ // Bail early for performance. If the doc has no mutation BPs, there is
+ // no reason to iterate through the children looking for things to detach.
+ return;
+ }
+
+ // The walker is not limited to the subtree of the argument node, so we
+ // need to ensure that we stop walking when we leave the subtree.
+ const nextWalkerSibling = this._getNextTraversalSibling(targetNode);
+
+ const walker = new DocumentWalker(targetNode, this.rootWin, {
+ filter: noAnonymousContentTreeWalkerFilter,
+ skipTo: SKIP_TO_SIBLING,
+ });
+
+ do {
+ this._updateMutationBreakpointState("detach", walker.currentNode, null);
+ } while (walker.nextNode() && walker.currentNode !== nextWalkerSibling);
+ },
+
+ _getNextTraversalSibling(targetNode) {
+ const walker = new DocumentWalker(targetNode, this.rootWin, {
+ filter: noAnonymousContentTreeWalkerFilter,
+ skipTo: SKIP_TO_SIBLING,
+ });
+
+ while (!walker.nextSibling()) {
+ if (!walker.parentNode()) {
+ // If we try to step past the walker root, there is no next sibling.
+ return null;
+ }
+ }
+ return walker.currentNode;
+ },
+
+ /**
+ * Get any pending mutation records. Must be called by the client after
+ * the `new-mutations` notification is received. Returns an array of
+ * mutation records.
+ *
+ * Mutation records have a basic structure:
+ *
+ * {
+ * type: attributes|characterData|childList,
+ * target: <domnode actor ID>,
+ * }
+ *
+ * And additional attributes based on the mutation type:
+ *
+ * `attributes` type:
+ * attributeName: <string> - the attribute that changed
+ * attributeNamespace: <string> - the attribute's namespace URI, if any.
+ * newValue: <string> - The new value of the attribute, if any.
+ *
+ * `characterData` type:
+ * newValue: <string> - the new nodeValue for the node
+ *
+ * `childList` type is returned when the set of children for a node
+ * has changed. Includes extra data, which can be used by the client to
+ * maintain its ownership subtree.
+ *
+ * added: array of <domnode actor ID> - The list of actors *previously
+ * seen by the client* that were added to the target node.
+ * removed: array of <domnode actor ID> The list of actors *previously
+ * seen by the client* that were removed from the target node.
+ * inlineTextChild: If the node now has a single text child, it will
+ * be sent here.
+ *
+ * Actors that are included in a MutationRecord's `removed` but
+ * not in an `added` have been removed from the client's ownership
+ * tree (either by being moved under a node the client has seen yet
+ * or by being removed from the tree entirely), and is considered
+ * 'orphaned'.
+ *
+ * Keep in mind that if a node that the client hasn't seen is moved
+ * into or out of the target node, it will not be included in the
+ * removedNodes and addedNodes list, so if the client is interested
+ * in the new set of children it needs to issue a `children` request.
+ */
+ getMutations: function(options = {}) {
+ const pending = this._pendingMutations || [];
+ this._pendingMutations = [];
+ this._waitingForGetMutations = false;
+
+ if (options.cleanup) {
+ for (const node of this._orphaned) {
+ // Release the orphaned node. Nodes or children that have been
+ // retained will be moved to this._retainedOrphans.
+ this.releaseNode(node);
+ }
+ this._orphaned = new Set();
+ }
+
+ return pending;
+ },
+
+ queueMutation: function(mutation) {
+ if (!this.actorID || this._destroyed) {
+ // We've been destroyed, don't bother queueing this mutation.
+ return;
+ }
+
+ // Add the mutation to the list of mutations to be retrieved next.
+ this._pendingMutations.push(mutation);
+
+ // Bail out if we already emitted a new-mutations event and are waiting for a client
+ // to retrieve them.
+ if (this._waitingForGetMutations) {
+ return;
+ }
+
+ if (IMMEDIATE_MUTATIONS.includes(mutation.type)) {
+ this._emitNewMutations();
+ } else {
+ /**
+ * If many mutations are fired at the same time, clients might sequentially request
+ * children/siblings for updated nodes, which can be costly. By throttling the calls
+ * to getMutations, duplicated mutations will be ignored.
+ */
+ this._throttledEmitNewMutations();
+ }
+ },
+
+ _emitNewMutations: function() {
+ if (!this.actorID || this._destroyed) {
+ // Bail out if the actor was destroyed after throttling this call.
+ return;
+ }
+
+ if (this._waitingForGetMutations || this._pendingMutations.length == 0) {
+ // Bail out if we already fired the new-mutation event or if no mutations are
+ // waiting to be retrieved.
+ return;
+ }
+
+ this._waitingForGetMutations = true;
+ this.emit("new-mutations");
+ },
+
+ /**
+ * Handles mutations from the DOM mutation observer API.
+ *
+ * @param array[MutationRecord] mutations
+ * See https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationRecord
+ */
+ onMutations: function(mutations) {
+ // Notify any observers that want *all* mutations (even on nodes that aren't
+ // referenced). This is not sent over the protocol so can only be used by
+ // scripts running in the server process.
+ this.emit("any-mutation");
+
+ for (const change of mutations) {
+ const targetActor = this.getNode(change.target);
+ if (!targetActor) {
+ continue;
+ }
+ const targetNode = change.target;
+ const type = change.type;
+ const mutation = {
+ type: type,
+ target: targetActor.actorID,
+ };
+
+ if (type === "attributes") {
+ mutation.attributeName = change.attributeName;
+ mutation.attributeNamespace = change.attributeNamespace || undefined;
+ mutation.newValue = targetNode.hasAttribute(mutation.attributeName)
+ ? targetNode.getAttribute(mutation.attributeName)
+ : null;
+ } else if (type === "characterData") {
+ mutation.newValue = targetNode.nodeValue;
+ this._maybeQueueInlineTextChildMutation(change, targetNode);
+ } else if (type === "childList" || type === "nativeAnonymousChildList") {
+ // Get the list of removed and added actors that the client has seen
+ // so that it can keep its ownership tree up to date.
+ const removedActors = [];
+ const addedActors = [];
+ for (const removed of change.removedNodes) {
+ const removedActor = this.getNode(removed);
+ if (!removedActor) {
+ // If the client never encountered this actor we don't need to
+ // mention that it was removed.
+ continue;
+ }
+ // While removed from the tree, nodes are saved as orphaned.
+ this._orphaned.add(removedActor);
+ removedActors.push(removedActor.actorID);
+ }
+ for (const added of change.addedNodes) {
+ const addedActor = this.getNode(added);
+ if (!addedActor) {
+ // If the client never encounted this actor we don't need to tell
+ // it about its addition for ownership tree purposes - if the
+ // client wants to see the new nodes it can ask for children.
+ continue;
+ }
+ // The actor is reconnected to the ownership tree, unorphan
+ // it and let the client know so that its ownership tree is up
+ // to date.
+ this._orphaned.delete(addedActor);
+ addedActors.push(addedActor.actorID);
+ }
+
+ mutation.numChildren = targetActor.numChildren;
+ mutation.removed = removedActors;
+ mutation.added = addedActors;
+
+ const inlineTextChild = this.inlineTextChild(targetActor);
+ if (inlineTextChild) {
+ mutation.inlineTextChild = inlineTextChild.form();
+ }
+ }
+ this.queueMutation(mutation);
+ }
+ },
+
+ /**
+ * Check if the provided mutation could change the way the target element is
+ * inlined with its parent node. If it might, a custom mutation of type
+ * "inlineTextChild" will be queued.
+ *
+ * @param {MutationRecord} mutation
+ * A characterData type mutation
+ */
+ _maybeQueueInlineTextChildMutation: function(mutation) {
+ const { oldValue, target } = mutation;
+ const newValue = target.nodeValue;
+ const limit = gValueSummaryLength;
+
+ if (
+ (oldValue.length <= limit && newValue.length <= limit) ||
+ (oldValue.length > limit && newValue.length > limit)
+ ) {
+ // Bail out if the new & old values are both below/above the size limit.
+ return;
+ }
+
+ const parentActor = this.getNode(target.parentNode);
+ if (!parentActor || parentActor.rawNode.children.length > 0) {
+ // If the parent node has other children, a character data mutation will
+ // not change anything regarding inlining text nodes.
+ return;
+ }
+
+ const inlineTextChild = this.inlineTextChild(parentActor);
+ this.queueMutation({
+ type: "inlineTextChild",
+ target: parentActor.actorID,
+ inlineTextChild: inlineTextChild ? inlineTextChild.form() : undefined,
+ });
+ },
+
+ onSlotchange: function(event) {
+ const target = event.target;
+ const targetActor = this.getNode(target);
+ if (!targetActor) {
+ return;
+ }
+
+ this.queueMutation({
+ type: "slotchange",
+ target: targetActor.actorID,
+ });
+ },
+
+ onShadowrootattached: function(event) {
+ const actor = this.getNode(event.target);
+ if (!actor) {
+ return;
+ }
+
+ const mutation = {
+ type: "shadowRootAttached",
+ target: actor.actorID,
+ };
+ this.queueMutation(mutation);
+ },
+
+ onFrameLoad: function({ window, isTopLevel }) {
+ const { readyState } = window.document;
+ if (readyState != "interactive" && readyState != "complete") {
+ // The document is not loaded, so we want to register to fire again when the
+ // DOM has been loaded.
+ window.addEventListener(
+ "DOMContentLoaded",
+ this.onFrameLoad.bind(this, { window, isTopLevel }),
+ { once: true }
+ );
+ return;
+ }
+
+ if (isTopLevel) {
+ // If we initialize the inspector while the document is loading,
+ // we may already have a root document set in the constructor.
+ if (
+ this.rootDoc &&
+ this.rootDoc !== window.document &&
+ !Cu.isDeadWrapper(this.rootDoc) &&
+ this.rootDoc.defaultView
+ ) {
+ this.onFrameUnload({ window: this.rootDoc.defaultView });
+ }
+ // Update all DOM objects references to target the new document.
+ this.rootWin = window;
+ this.rootDoc = window.document;
+ this.rootNode = this.document();
+ this.emit("root-available", this.rootNode);
+ } else {
+ const frame = getFrameElement(window);
+ const frameActor = this.getNode(frame);
+ if (frameActor) {
+ // If the parent frame is in the map of known node actors, create the
+ // actor for the new document and emit a root-available event.
+ const documentActor = this._getOrCreateNodeActor(window.document);
+ this.emit("root-available", documentActor);
+ }
+ }
+ },
+
+ // Returns true if domNode is in window or a subframe.
+ _childOfWindow: function(window, domNode) {
+ let win = nodeDocument(domNode).defaultView;
+ while (win) {
+ if (win === window) {
+ return true;
+ }
+ win = getFrameElement(win);
+ }
+ return false;
+ },
+
+ onFrameUnload: function({ window }) {
+ // Any retained orphans that belong to this document
+ // or its children need to be released, and a mutation sent
+ // to notify of that.
+ const releasedOrphans = [];
+
+ for (const retained of this._retainedOrphans) {
+ if (
+ Cu.isDeadWrapper(retained.rawNode) ||
+ this._childOfWindow(window, retained.rawNode)
+ ) {
+ this._retainedOrphans.delete(retained);
+ releasedOrphans.push(retained.actorID);
+ this.releaseNode(retained, { force: true });
+ }
+ }
+
+ if (releasedOrphans.length > 0) {
+ this.queueMutation({
+ target: this.rootNode.actorID,
+ type: "unretained",
+ nodes: releasedOrphans,
+ });
+ }
+
+ const doc = window.document;
+ const documentActor = this.getNode(doc);
+ if (!documentActor) {
+ return;
+ }
+
+ // Removing a frame also removes any mutation breakpoints set on that
+ // document so that clients can clear their set of active breakpoints.
+ const mutationBps = this._mutationBreakpointsForDoc(doc);
+ const nodes = mutationBps ? Array.from(mutationBps.nodes.keys()) : [];
+ for (const node of nodes) {
+ this._updateMutationBreakpointState("unload", node, null);
+ }
+
+ this.emit("root-destroyed", documentActor);
+
+ // Cleanup root doc references if we just unloaded the top level root
+ // document.
+ if (this.rootDoc === doc) {
+ this.rootDoc = null;
+ this.rootNode = null;
+ }
+
+ // Release the actor for the unloaded document.
+ this.releaseNode(documentActor, { force: true });
+ },
+
+ /**
+ * Check if a node is attached to the DOM tree of the current page.
+ * @param {Node} rawNode
+ * @return {Boolean} false if the node is removed from the tree or within a
+ * document fragment
+ */
+ _isInDOMTree: function(rawNode) {
+ const walker = this.getDocumentWalker(rawNode);
+ let current = walker.currentNode;
+
+ // Reaching the top of tree
+ while (walker.parentNode()) {
+ current = walker.currentNode;
+ }
+
+ // The top of the tree is a fragment or is not rootDoc, hence rawNode isn't
+ // attached
+ if (
+ current.nodeType === Node.DOCUMENT_FRAGMENT_NODE ||
+ current !== this.rootDoc
+ ) {
+ return false;
+ }
+
+ // Otherwise the top of the tree is rootDoc, hence rawNode is in rootDoc
+ return true;
+ },
+
+ /**
+ * @see _isInDomTree
+ */
+ isInDOMTree: function(node) {
+ if (isNodeDead(node)) {
+ return false;
+ }
+ return this._isInDOMTree(node.rawNode);
+ },
+
+ /**
+ * Given a windowID return the NodeActor for the corresponding frameElement,
+ * unless it's the root window
+ */
+ getNodeActorFromWindowID: function(windowID) {
+ let win;
+
+ try {
+ win = Services.wm.getOuterWindowWithId(windowID);
+ } catch (e) {
+ // ignore
+ }
+
+ if (!win) {
+ return {
+ error: "noWindow",
+ message: "The related docshell is destroyed or not found",
+ };
+ } else if (!win.frameElement) {
+ // the frame element of the root document is privileged & thus
+ // inaccessible, so return the document body/element instead
+ return this.attachElement(
+ win.document.body || win.document.documentElement
+ );
+ }
+
+ return this.attachElement(win.frameElement);
+ },
+
+ /**
+ * Given a contentDomReference return the NodeActor for the corresponding frameElement.
+ */
+ getNodeActorFromContentDomReference: function(contentDomReference) {
+ let rawNode = ContentDOMReference.resolve(contentDomReference);
+ if (!rawNode || !this._isInDOMTree(rawNode)) {
+ return null;
+ }
+
+ // This is a special case for the document object whereby it is considered
+ // as document.documentElement (the <html> node)
+ if (rawNode.defaultView && rawNode === rawNode.defaultView.document) {
+ rawNode = rawNode.documentElement;
+ }
+
+ return this.attachElement(rawNode);
+ },
+
+ /**
+ * Given a StyleSheetActor (identified by its ID), commonly used in the
+ * style-editor, get its ownerNode and return the corresponding walker's
+ * NodeActor.
+ * Note that getNodeFromActor was added later and can now be used instead.
+ */
+ getStyleSheetOwnerNode: function(resourceId) {
+ const watcher = getResourceWatcher(this.targetActor, TYPES.STYLESHEET);
+ if (watcher) {
+ const ownerNode = watcher.getOwnerNode(resourceId);
+ return this.attachElement(ownerNode);
+ }
+
+ // Following code can be removed once we enable STYLESHEET resource on the watcher/server
+ // side by default. For now it is being preffed off and we have to support the two
+ // codepaths. Once enabled we will only support the stylesheet watcher codepath.
+ const actorBasedNode = this.getNodeFromActor(resourceId, ["ownerNode"]);
+ return actorBasedNode;
+ },
+
+ /**
+ * This method can be used to retrieve NodeActor for DOM nodes from other
+ * actors in a way that they can later be highlighted in the page, or
+ * selected in the inspector.
+ * If an actor has a reference to a DOM node, and the UI needs to know about
+ * this DOM node (and possibly select it in the inspector), the UI should
+ * first retrieve a reference to the walkerFront:
+ *
+ * // Make sure the inspector/walker have been initialized first.
+ * const inspectorFront = await toolbox.target.getFront("inspector");
+ * // Retrieve the walker.
+ * const walker = inspectorFront.walker;
+ *
+ * And then call this method:
+ *
+ * // Get the nodeFront from my actor, passing the ID and properties path.
+ * walker.getNodeFromActor(myActorID, ["element"]).then(nodeFront => {
+ * // Use the nodeFront, e.g. select the node in the inspector.
+ * toolbox.getPanel("inspector").selection.setNodeFront(nodeFront);
+ * });
+ *
+ * @param {String} actorID The ID for the actor that has a reference to the
+ * DOM node.
+ * @param {Array} path Where, on the actor, is the DOM node stored. If in the
+ * scope of the actor, the node is available as `this.data.node`, then this
+ * should be ["data", "node"].
+ * @return {NodeActor} The attached NodeActor, or null if it couldn't be
+ * found.
+ */
+ getNodeFromActor: function(actorID, path) {
+ const actor = this.conn.getActor(actorID);
+ if (!actor) {
+ return null;
+ }
+
+ let obj = actor;
+ for (const name of path) {
+ if (!(name in obj)) {
+ return null;
+ }
+ obj = obj[name];
+ }
+
+ return this.attachElement(obj);
+ },
+
+ /**
+ * Returns an instance of the LayoutActor that is used to retrieve CSS layout-related
+ * information.
+ *
+ * @return {LayoutActor}
+ */
+ getLayoutInspector: function() {
+ if (!this.layoutActor) {
+ this.layoutActor = new LayoutActor(this.conn, this.targetActor, this);
+ }
+
+ return this.layoutActor;
+ },
+
+ /**
+ * Returns the parent grid DOMNode of the given node if it exists, otherwise, it
+ * returns null.
+ */
+ getParentGridNode: function(node) {
+ if (isNodeDead(node)) {
+ return null;
+ }
+
+ const parentGridNode = findGridParentContainerForNode(node.rawNode);
+ return parentGridNode ? this._getOrCreateNodeActor(parentGridNode) : null;
+ },
+
+ /**
+ * Returns the offset parent DOMNode of the given node if it exists, otherwise, it
+ * returns null.
+ */
+ getOffsetParent: function(node) {
+ if (isNodeDead(node)) {
+ return null;
+ }
+
+ const offsetParent = node.rawNode.offsetParent;
+
+ if (!offsetParent) {
+ return null;
+ }
+
+ return this._getOrCreateNodeActor(offsetParent);
+ },
+
+ getEmbedderElement(browsingContextID) {
+ const browsingContext = BrowsingContext.get(browsingContextID);
+ let rawNode = browsingContext.embedderElement;
+ if (!this._isInDOMTree(rawNode)) {
+ return null;
+ }
+
+ // This is a special case for the document object whereby it is considered
+ // as document.documentElement (the <html> node)
+ if (rawNode.defaultView && rawNode === rawNode.defaultView.document) {
+ rawNode = rawNode.documentElement;
+ }
+
+ return this.attachElement(rawNode);
+ },
+
+ pick(doFocus) {
+ this.nodePicker.pick(doFocus);
+ },
+
+ cancelPick() {
+ this.nodePicker.cancelPick();
+ },
+
+ /**
+ * Given a scrollable node, find its descendants which are causing overflow in it and
+ * add their raw nodes to the map as keys with the scrollable element as the values.
+ *
+ * @param {NodeActor} scrollableNode A scrollable node.
+ * @param {Map} map The map to which the overflow causing elements are added.
+ */
+ updateOverflowCausingElements: function(scrollableNode, map) {
+ if (
+ isNodeDead(scrollableNode) ||
+ scrollableNode.rawNode.nodeType !== Node.ELEMENT_NODE
+ ) {
+ return;
+ }
+
+ const overflowCausingChildren = [
+ ...InspectorUtils.getOverflowingChildrenOfElement(scrollableNode.rawNode),
+ ];
+
+ for (let overflowCausingChild of overflowCausingChildren) {
+ // overflowCausingChild is a Node, but not necessarily an Element.
+ // So, get the containing Element
+ if (overflowCausingChild.nodeType !== Node.ELEMENT_NODE) {
+ overflowCausingChild = overflowCausingChild.parentElement;
+ }
+ map.set(overflowCausingChild, scrollableNode);
+ }
+ },
+
+ /**
+ * Returns an array of the overflow causing elements' NodeActor for the given node.
+ *
+ * @param {NodeActor} node The scrollable node.
+ * @return {Array<NodeActor>} An array of the overflow causing elements.
+ */
+ getOverflowCausingElements: function(node) {
+ if (
+ isNodeDead(node) ||
+ node.rawNode.nodeType !== Node.ELEMENT_NODE ||
+ !node.isScrollable
+ ) {
+ return [];
+ }
+
+ const overflowCausingElements = [
+ ...InspectorUtils.getOverflowingChildrenOfElement(node.rawNode),
+ ].map(overflowCausingChild => {
+ if (overflowCausingChild.nodeType !== Node.ELEMENT_NODE) {
+ overflowCausingChild = overflowCausingChild.parentElement;
+ }
+
+ return overflowCausingChild;
+ });
+
+ return this.attachElements(overflowCausingElements);
+ },
+
+ /**
+ * Return the scrollable ancestor node which has overflow because of the given node.
+ *
+ * @param {NodeActor} overflowCausingNode
+ */
+ getScrollableAncestorNode: function(overflowCausingNode) {
+ if (
+ isNodeDead(overflowCausingNode) ||
+ !this.overflowCausingElementsMap.has(overflowCausingNode.rawNode)
+ ) {
+ return null;
+ }
+
+ return this.overflowCausingElementsMap.get(overflowCausingNode.rawNode);
+ },
+});
+
+exports.WalkerActor = WalkerActor;
diff --git a/devtools/server/actors/layout.js b/devtools/server/actors/layout.js
new file mode 100644
index 0000000000..1330683e57
--- /dev/null
+++ b/devtools/server/actors/layout.js
@@ -0,0 +1,521 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const Services = require("Services");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const {
+ flexboxSpec,
+ flexItemSpec,
+ gridSpec,
+ layoutSpec,
+} = require("devtools/shared/specs/layout");
+const {
+ getStringifiableFragments,
+} = require("devtools/server/actors/utils/css-grid-utils");
+
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "findGridParentContainerForNode",
+ "devtools/server/actors/inspector/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getCSSStyleRules",
+ "devtools/shared/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isCssPropertyKnown",
+ "devtools/server/actors/css-properties",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "parseDeclarations",
+ "devtools/shared/css/parsing-utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "nodeConstants",
+ "devtools/shared/dom-node-constants"
+);
+
+const SUBGRID_ENABLED = Services.prefs.getBoolPref(
+ "layout.css.grid-template-subgrid-value.enabled"
+);
+
+/**
+ * Set of actors the expose the CSS layout information to the devtools protocol clients.
+ *
+ * The |Layout| actor is the main entry point. It is used to get various CSS
+ * layout-related information from the document.
+ *
+ * The |Flexbox| actor provides the container node information to inspect the flexbox
+ * container. It is also used to return an array of |FlexItem| actors which provide the
+ * flex item information.
+ *
+ * The |Grid| actor provides the grid fragment information to inspect the grid container.
+ */
+
+const FlexboxActor = ActorClassWithSpec(flexboxSpec, {
+ /**
+ * @param {LayoutActor} layoutActor
+ * The LayoutActor instance.
+ * @param {DOMNode} containerEl
+ * The flex container element.
+ */
+ initialize(layoutActor, containerEl) {
+ Actor.prototype.initialize.call(this, layoutActor.conn);
+
+ this.containerEl = containerEl;
+ this.walker = layoutActor.walker;
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ this.containerEl = null;
+ this.walker = null;
+ },
+
+ form() {
+ const styles = CssLogic.getComputedStyle(this.containerEl);
+
+ const form = {
+ actor: this.actorID,
+ // The computed style properties of the flex container.
+ properties: {
+ "align-content": styles.alignContent,
+ "align-items": styles.alignItems,
+ "flex-direction": styles.flexDirection,
+ "flex-wrap": styles.flexWrap,
+ "justify-content": styles.justifyContent,
+ },
+ };
+
+ // If the WalkerActor already knows the container element, then also return its
+ // ActorID so we avoid the client from doing another round trip to get it in many
+ // cases.
+ if (this.walker.hasNode(this.containerEl)) {
+ form.containerNodeActorID = this.walker.getNode(this.containerEl).actorID;
+ }
+
+ return form;
+ },
+
+ /**
+ * Returns an array of FlexItemActor objects for all the flex item elements contained
+ * in the flex container element.
+ *
+ * @return {Array}
+ * An array of FlexItemActor objects.
+ */
+ getFlexItems() {
+ if (isNodeDead(this.containerEl)) {
+ return [];
+ }
+
+ const flex = this.containerEl.getAsFlexContainer();
+ if (!flex) {
+ return [];
+ }
+
+ const flexItemActors = [];
+ const { crossAxisDirection, mainAxisDirection } = flex;
+
+ for (const line of flex.getLines()) {
+ for (const item of line.getItems()) {
+ flexItemActors.push(
+ new FlexItemActor(this, item.node, {
+ crossAxisDirection,
+ mainAxisDirection,
+ crossMaxSize: item.crossMaxSize,
+ crossMinSize: item.crossMinSize,
+ mainBaseSize: item.mainBaseSize,
+ mainDeltaSize: item.mainDeltaSize,
+ mainMaxSize: item.mainMaxSize,
+ mainMinSize: item.mainMinSize,
+ lineGrowthState: line.growthState,
+ clampState: item.clampState,
+ })
+ );
+ }
+ }
+
+ return flexItemActors;
+ },
+});
+
+/**
+ * The FlexItemActor provides information about a flex items' data.
+ */
+const FlexItemActor = ActorClassWithSpec(flexItemSpec, {
+ /**
+ * @param {FlexboxActor} flexboxActor
+ * The FlexboxActor instance.
+ * @param {DOMNode} element
+ * The flex item element.
+ * @param {Object} flexItemSizing
+ * The flex item sizing data.
+ */
+ initialize(flexboxActor, element, flexItemSizing) {
+ Actor.prototype.initialize.call(this, flexboxActor.conn);
+
+ this.containerEl = flexboxActor.containerEl;
+ this.element = element;
+ this.flexItemSizing = flexItemSizing;
+ this.walker = flexboxActor.walker;
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ this.containerEl = null;
+ this.element = null;
+ this.flexItemSizing = null;
+ this.walker = null;
+ },
+
+ form() {
+ const { mainAxisDirection } = this.flexItemSizing;
+ const dimension = mainAxisDirection.startsWith("horizontal")
+ ? "width"
+ : "height";
+
+ // Find the authored sizing properties for this item.
+ const properties = {
+ "flex-basis": "",
+ "flex-grow": "",
+ "flex-shrink": "",
+ [`min-${dimension}`]: "",
+ [`max-${dimension}`]: "",
+ [dimension]: "",
+ };
+
+ const isElementNode = this.element.nodeType === this.element.ELEMENT_NODE;
+
+ if (isElementNode) {
+ for (const name in properties) {
+ const values = [];
+ const cssRules = getCSSStyleRules(this.element);
+
+ for (const rule of cssRules) {
+ // For each rule, go through *all* properties, because there may be several of
+ // them in the same rule and some with !important flags (which would be more
+ // important even if placed before another property with the same name)
+ const declarations = parseDeclarations(
+ isCssPropertyKnown,
+ rule.style.cssText
+ );
+
+ for (const declaration of declarations) {
+ if (declaration.name === name && declaration.value !== "auto") {
+ values.push({
+ value: declaration.value,
+ priority: declaration.priority,
+ });
+ }
+ }
+ }
+
+ // Then go through the element style because it's usually more important, but
+ // might not be if there is a prior !important property
+ if (
+ this.element.style &&
+ this.element.style[name] &&
+ this.element.style[name] !== "auto"
+ ) {
+ values.push({
+ value: this.element.style.getPropertyValue(name),
+ priority: this.element.style.getPropertyPriority(name),
+ });
+ }
+
+ // Now that we have a list of all the property's rule values, go through all the
+ // values and show the property value with the highest priority. Therefore, show
+ // the last !important value. Otherwise, show the last value stored.
+ let rulePropertyValue = "";
+
+ if (values.length) {
+ const lastValueIndex = values.length - 1;
+ rulePropertyValue = values[lastValueIndex].value;
+
+ for (const { priority, value } of values) {
+ if (priority === "important") {
+ rulePropertyValue = `${value} !important`;
+ }
+ }
+ }
+
+ properties[name] = rulePropertyValue;
+ }
+ }
+
+ // Also find some computed sizing properties that will be useful for this item.
+ const { flexGrow, flexShrink } = isElementNode
+ ? CssLogic.getComputedStyle(this.element)
+ : { flexGrow: null, flexShrink: null };
+ const computedStyle = { flexGrow, flexShrink };
+
+ const form = {
+ actor: this.actorID,
+ // The flex item sizing data.
+ flexItemSizing: this.flexItemSizing,
+ // The authored style properties of the flex item.
+ properties,
+ // The computed style properties of the flex item.
+ computedStyle,
+ };
+
+ // If the WalkerActor already knows the flex item element, then also return its
+ // ActorID so we avoid the client from doing another round trip to get it in many
+ // cases.
+ if (this.walker.hasNode(this.element)) {
+ form.nodeActorID = this.walker.getNode(this.element).actorID;
+ }
+
+ return form;
+ },
+});
+
+/**
+ * The GridActor provides information about a given grid's fragment data.
+ */
+const GridActor = ActorClassWithSpec(gridSpec, {
+ /**
+ * @param {LayoutActor} layoutActor
+ * The LayoutActor instance.
+ * @param {DOMNode} containerEl
+ * The grid container element.
+ */
+ initialize(layoutActor, containerEl) {
+ Actor.prototype.initialize.call(this, layoutActor.conn);
+
+ this.containerEl = containerEl;
+ this.walker = layoutActor.walker;
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ this.containerEl = null;
+ this.gridFragments = null;
+ this.walker = null;
+ },
+
+ form() {
+ // Seralize the grid fragment data into JSON so protocol.js knows how to write
+ // and read the data.
+ const gridFragments = this.containerEl.getGridFragments();
+ this.gridFragments = getStringifiableFragments(gridFragments);
+
+ // Record writing mode and text direction for use by the grid outline.
+ const {
+ direction,
+ gridTemplateColumns,
+ gridTemplateRows,
+ writingMode,
+ } = CssLogic.getComputedStyle(this.containerEl);
+
+ const form = {
+ actor: this.actorID,
+ direction,
+ gridFragments: this.gridFragments,
+ writingMode,
+ };
+
+ // If the WalkerActor already knows the container element, then also return its
+ // ActorID so we avoid the client from doing another round trip to get it in many
+ // cases.
+ if (this.walker.hasNode(this.containerEl)) {
+ form.containerNodeActorID = this.walker.getNode(this.containerEl).actorID;
+ }
+
+ if (SUBGRID_ENABLED) {
+ form.isSubgrid =
+ gridTemplateRows.startsWith("subgrid") ||
+ gridTemplateColumns.startsWith("subgrid");
+ }
+
+ return form;
+ },
+});
+
+/**
+ * The CSS layout actor provides layout information for the given document.
+ */
+const LayoutActor = ActorClassWithSpec(layoutSpec, {
+ initialize(conn, targetActor, walker) {
+ Actor.prototype.initialize.call(this, conn);
+
+ this.targetActor = targetActor;
+ this.walker = walker;
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ this.targetActor = null;
+ this.walker = null;
+ },
+
+ /**
+ * Helper function for getAsFlexItem, getCurrentGrid and getCurrentFlexbox. Returns the
+ * grid or flex container (whichever is requested) found by iterating on the given
+ * selected node. The current node can be a grid/flex container or grid/flex item.
+ * If it is a grid/flex item, returns the parent grid/flex container. Otherwise, returns
+ * null if the current or parent node is not a grid/flex container.
+ *
+ * @param {Node|NodeActor} node
+ * The node to start iterating at.
+ * @param {String} type
+ * Can be "grid" or "flex", the display type we are searching for.
+ * @param {Boolean} onlyLookAtContainer
+ * If true, only look at given node's container and iterate from there.
+ * @return {GridActor|FlexboxActor|null}
+ * The GridActor or FlexboxActor of the grid/flex container of the given node.
+ * Otherwise, returns null.
+ */
+ getCurrentDisplay(node, type, onlyLookAtContainer) {
+ if (isNodeDead(node)) {
+ return null;
+ }
+
+ // Given node can either be a Node or a NodeActor.
+ if (node.rawNode) {
+ node = node.rawNode;
+ }
+
+ const flexType = type === "flex";
+ const gridType = type === "grid";
+ const displayType = this.walker.getNode(node).displayType;
+
+ // If the node is an element, check first if it is itself a flex or a grid.
+ if (node.nodeType === node.ELEMENT_NODE) {
+ if (!displayType) {
+ return null;
+ }
+
+ if (flexType && displayType.includes("flex")) {
+ if (!onlyLookAtContainer) {
+ return new FlexboxActor(this, node);
+ }
+
+ const container = node.parentFlexElement;
+ if (container) {
+ return new FlexboxActor(this, container);
+ }
+
+ return null;
+ } else if (gridType && displayType.includes("grid")) {
+ return new GridActor(this, node);
+ }
+ }
+
+ // Otherwise, check if this is a flex/grid item or the parent node is a flex/grid
+ // container.
+ // Note that text nodes that are children of flex/grid containers are wrapped in
+ // anonymous containers, so even if their displayType getter returns null we still
+ // want to walk up the chain to find their container.
+ const parentFlexElement = node.parentFlexElement;
+ if (parentFlexElement && flexType) {
+ return new FlexboxActor(this, parentFlexElement);
+ }
+ const container = findGridParentContainerForNode(node);
+ if (container && gridType) {
+ return new GridActor(this, container);
+ }
+
+ return null;
+ },
+
+ /**
+ * Returns the grid container for a given selected node.
+ * The node itself can be a container, but if not, walk up the DOM to find its
+ * container.
+ * Returns null if no container can be found.
+ *
+ * @param {Node|NodeActor} node
+ * The node to start iterating at.
+ * @return {GridActor|null}
+ * The GridActor of the grid container of the given node. Otherwise, returns
+ * null.
+ */
+ getCurrentGrid(node) {
+ return this.getCurrentDisplay(node, "grid");
+ },
+
+ /**
+ * Returns the flex container for a given selected node.
+ * The node itself can be a container, but if not, walk up the DOM to find its
+ * container.
+ * Returns null if no container can be found.
+ *
+ * @param {Node|NodeActor} node
+ * The node to start iterating at.
+ * @param {Boolean|null} onlyLookAtParents
+ * If true, skip the passed node and only start looking at its parent and up.
+ * @return {FlexboxActor|null}
+ * The FlexboxActor of the flex container of the given node. Otherwise, returns
+ * null.
+ */
+ getCurrentFlexbox(node, onlyLookAtParents) {
+ return this.getCurrentDisplay(node, "flex", onlyLookAtParents);
+ },
+
+ /**
+ * Returns an array of GridActor objects for all the grid elements contained in the
+ * given root node.
+ *
+ * @param {Node|NodeActor} node
+ * The root node for grid elements
+ * @return {Array} An array of GridActor objects.
+ */
+ getGrids(node) {
+ if (isNodeDead(node)) {
+ return [];
+ }
+
+ // Root node can either be a Node or a NodeActor.
+ if (node.rawNode) {
+ node = node.rawNode;
+ }
+
+ // Root node can be a #document object, which does not support getElementsWithGrid.
+ if (node.nodeType === nodeConstants.DOCUMENT_NODE) {
+ node = node.documentElement;
+ }
+
+ const gridElements = node.getElementsWithGrid();
+ let gridActors = gridElements.map(n => new GridActor(this, n));
+
+ const frames = node.querySelectorAll("iframe, frame");
+ for (const frame of frames) {
+ gridActors = gridActors.concat(this.getGrids(frame.contentDocument));
+ }
+
+ return gridActors;
+ },
+});
+
+function isNodeDead(node) {
+ return !node || (node.rawNode && Cu.isDeadWrapper(node.rawNode));
+}
+
+exports.FlexboxActor = FlexboxActor;
+exports.FlexItemActor = FlexItemActor;
+exports.GridActor = GridActor;
+exports.LayoutActor = LayoutActor;
diff --git a/devtools/server/actors/manifest.js b/devtools/server/actors/manifest.js
new file mode 100644
index 0000000000..d7503592b3
--- /dev/null
+++ b/devtools/server/actors/manifest.js
@@ -0,0 +1,38 @@
+/* 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";
+
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { manifestSpec } = require("devtools/shared/specs/manifest");
+
+loader.lazyImporter(
+ this,
+ "ManifestObtainer",
+ "resource://gre/modules/ManifestObtainer.jsm"
+);
+
+/**
+ * An actor for a Web Manifest
+ */
+const ManifestActor = ActorClassWithSpec(manifestSpec, {
+ initialize: function(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ },
+
+ fetchCanonicalManifest: async function() {
+ try {
+ const manifest = await ManifestObtainer.contentObtainManifest(
+ this.targetActor.window,
+ { checkConformance: true }
+ );
+ return { manifest };
+ } catch (error) {
+ return { manifest: null, errorMessage: error.message };
+ }
+ },
+});
+
+exports.ManifestActor = ManifestActor;
diff --git a/devtools/server/actors/media-rule.js b/devtools/server/actors/media-rule.js
new file mode 100644
index 0000000000..3c9d662ef3
--- /dev/null
+++ b/devtools/server/actors/media-rule.js
@@ -0,0 +1,82 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const protocol = require("devtools/shared/protocol");
+const { mediaRuleSpec } = require("devtools/shared/specs/media-rule");
+const InspectorUtils = require("InspectorUtils");
+
+/**
+ * A MediaRuleActor lives on the server and provides access to properties
+ * of a DOM @media rule and emits events when it changes.
+ */
+var MediaRuleActor = protocol.ActorClassWithSpec(mediaRuleSpec, {
+ get window() {
+ return this.parentActor.window;
+ },
+
+ get document() {
+ return this.window.document;
+ },
+
+ get matches() {
+ return this.mql ? this.mql.matches : null;
+ },
+
+ initialize: function(mediaRule, parentActor) {
+ protocol.Actor.prototype.initialize.call(this, parentActor.conn);
+
+ this.rawRule = mediaRule;
+ this.parentActor = parentActor;
+ this.conn = this.parentActor.conn;
+
+ this._matchesChange = this._matchesChange.bind(this);
+
+ this.line = InspectorUtils.getRuleLine(mediaRule);
+ this.column = InspectorUtils.getRuleColumn(mediaRule);
+
+ try {
+ this.mql = this.window.matchMedia(mediaRule.media.mediaText);
+ } catch (e) {
+ // Ignored
+ }
+
+ if (this.mql) {
+ this.mql.addListener(this._matchesChange);
+ }
+ },
+
+ destroy: function() {
+ if (this.mql) {
+ // The content page may already be destroyed and mql be the dead wrapper.
+ if (!Cu.isDeadWrapper(this.mql)) {
+ this.mql.removeListener(this._matchesChange);
+ }
+ this.mql = null;
+ }
+
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ form: function() {
+ const form = {
+ actor: this.actorID, // actorID is set when this is added to a pool
+ mediaText: this.rawRule.media.mediaText,
+ conditionText: this.rawRule.conditionText,
+ matches: this.matches,
+ line: this.line,
+ column: this.column,
+ parentStyleSheet: this.parentActor.actorID,
+ };
+
+ return form;
+ },
+
+ _matchesChange: function() {
+ this.emit("matches-change", this.matches);
+ },
+});
+exports.MediaRuleActor = MediaRuleActor;
diff --git a/devtools/server/actors/memory.js b/devtools/server/actors/memory.js
new file mode 100644
index 0000000000..0bf944a8d5
--- /dev/null
+++ b/devtools/server/actors/memory.js
@@ -0,0 +1,86 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { Memory } = require("devtools/server/performance/memory");
+const { actorBridgeWithSpec } = require("devtools/server/actors/common");
+const { memorySpec } = require("devtools/shared/specs/memory");
+loader.lazyRequireGetter(
+ this,
+ "StackFrameCache",
+ "devtools/server/actors/utils/stack",
+ true
+);
+
+/**
+ * An actor that returns memory usage data for its parent actor's window.
+ * A target-scoped instance of this actor will measure the memory footprint of
+ * the target, such as a tab. A global-scoped instance however, will measure the memory
+ * footprint of the chrome window referenced by the root actor.
+ *
+ * This actor wraps the Memory module at devtools/server/performance/memory.js
+ * and provides RDP definitions.
+ *
+ * @see devtools/server/performance/memory.js for documentation.
+ */
+exports.MemoryActor = protocol.ActorClassWithSpec(memorySpec, {
+ initialize: function(conn, parent, frameCache = new StackFrameCache()) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+
+ this._onGarbageCollection = this._onGarbageCollection.bind(this);
+ this._onAllocations = this._onAllocations.bind(this);
+ this.bridge = new Memory(parent, frameCache);
+ this.bridge.on("garbage-collection", this._onGarbageCollection);
+ this.bridge.on("allocations", this._onAllocations);
+ },
+
+ destroy: function() {
+ this.bridge.off("garbage-collection", this._onGarbageCollection);
+ this.bridge.off("allocations", this._onAllocations);
+ this.bridge.destroy();
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ attach: actorBridgeWithSpec("attach"),
+
+ detach: actorBridgeWithSpec("detach"),
+
+ getState: actorBridgeWithSpec("getState"),
+
+ saveHeapSnapshot: function(boundaries) {
+ return this.bridge.saveHeapSnapshot(boundaries);
+ },
+
+ takeCensus: actorBridgeWithSpec("takeCensus"),
+
+ startRecordingAllocations: actorBridgeWithSpec("startRecordingAllocations"),
+
+ stopRecordingAllocations: actorBridgeWithSpec("stopRecordingAllocations"),
+
+ getAllocationsSettings: actorBridgeWithSpec("getAllocationsSettings"),
+
+ getAllocations: actorBridgeWithSpec("getAllocations"),
+
+ forceGarbageCollection: actorBridgeWithSpec("forceGarbageCollection"),
+
+ forceCycleCollection: actorBridgeWithSpec("forceCycleCollection"),
+
+ measure: actorBridgeWithSpec("measure"),
+
+ residentUnique: actorBridgeWithSpec("residentUnique"),
+
+ _onGarbageCollection: function(data) {
+ if (this.conn.transport) {
+ this.emit("garbage-collection", data);
+ }
+ },
+
+ _onAllocations: function(data) {
+ if (this.conn.transport) {
+ this.emit("allocations", data);
+ }
+ },
+});
diff --git a/devtools/server/actors/moz.build b/devtools/server/actors/moz.build
new file mode 100644
index 0000000000..63dd79c00b
--- /dev/null
+++ b/devtools/server/actors/moz.build
@@ -0,0 +1,94 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "accessibility",
+ "addon",
+ "compatibility",
+ "descriptors",
+ "emulation",
+ "highlighters",
+ "inspector",
+ "network-monitor",
+ "object",
+ "resources",
+ "targets",
+ "utils",
+ "watcher",
+ "webconsole",
+ "worker",
+]
+
+DevToolsModules(
+ "animation-type-longhand.js",
+ "animation.js",
+ "array-buffer.js",
+ "breakpoint-list.js",
+ "breakpoint.js",
+ "changes.js",
+ "common.js",
+ "css-properties.js",
+ "device.js",
+ "environment.js",
+ "errordocs.js",
+ "frame.js",
+ "framerate.js",
+ "heap-snapshot-file.js",
+ "highlighters.css",
+ "highlighters.js",
+ "layout.js",
+ "manifest.js",
+ "media-rule.js",
+ "memory.js",
+ "object.js",
+ "page-style.js",
+ "pause-scoped.js",
+ "perf.js",
+ "performance-recording.js",
+ "performance.js",
+ "preference.js",
+ "process.js",
+ "reflow.js",
+ "root.js",
+ "screenshot.js",
+ "source.js",
+ "storage.js",
+ "string.js",
+ "style-rule.js",
+ "style-sheet.js",
+ "style-sheets.js",
+ "thread.js",
+ "watcher.js",
+ "webbrowser.js",
+ "webconsole.js",
+)
+
+with Files("animation.js"):
+ BUG_COMPONENT = ("DevTools", "Inspector: Animations")
+
+with Files("breakpoint.js"):
+ BUG_COMPONENT = ("DevTools", "Debugger")
+
+with Files("css-properties.js"):
+ BUG_COMPONENT = ("DevTools", "Inspector: Rules")
+
+with Files("memory.js"):
+ BUG_COMPONENT = ("DevTools", "Memory")
+
+with Files("performance*"):
+ BUG_COMPONENT = ("DevTools", "Performance Tools (Profiler/Timeline)")
+
+with Files("source.js"):
+ BUG_COMPONENT = ("DevTools", "Debugger")
+
+with Files("storage.js"):
+ BUG_COMPONENT = ("DevTools", "Storage Inspector")
+
+with Files("stylesheets.js"):
+ BUG_COMPONENT = ("DevTools", "Style Editor")
+
+with Files("webconsole.js"):
+ BUG_COMPONENT = ("DevTools", "Console")
diff --git a/devtools/server/actors/network-monitor/channel-event-sink.js b/devtools/server/actors/network-monitor/channel-event-sink.js
new file mode 100644
index 0000000000..fa4448b896
--- /dev/null
+++ b/devtools/server/actors/network-monitor/channel-event-sink.js
@@ -0,0 +1,101 @@
+/* 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";
+
+const { Cc, Ci, Cm, Cr, components } = require("chrome");
+const ChromeUtils = require("ChromeUtils");
+const { ComponentUtils } = require("resource://gre/modules/ComponentUtils.jsm");
+const Services = require("Services");
+
+/**
+ * This is a nsIChannelEventSink implementation that monitors channel redirects and
+ * informs the registered StackTraceCollector about the old and new channels.
+ */
+const SINK_CLASS_DESCRIPTION = "NetworkMonitor Channel Event Sink";
+const SINK_CLASS_ID = components.ID("{e89fa076-c845-48a8-8c45-2604729eba1d}");
+const SINK_CONTRACT_ID = "@mozilla.org/network/monitor/channeleventsink;1";
+const SINK_CATEGORY_NAME = "net-channel-event-sinks";
+
+function ChannelEventSink() {
+ this.wrappedJSObject = this;
+ this.collectors = new Set();
+}
+
+ChannelEventSink.prototype = {
+ QueryInterface: ChromeUtils.generateQI(["nsIChannelEventSink"]),
+
+ registerCollector(collector) {
+ this.collectors.add(collector);
+ },
+
+ unregisterCollector(collector) {
+ this.collectors.delete(collector);
+
+ if (this.collectors.size == 0) {
+ ChannelEventSinkFactory.unregister();
+ }
+ },
+
+ // eslint-disable-next-line no-shadow
+ asyncOnChannelRedirect(oldChannel, newChannel, flags, callback) {
+ for (const collector of this.collectors) {
+ try {
+ collector.onChannelRedirect(oldChannel, newChannel, flags);
+ } catch (ex) {
+ console.error(
+ "StackTraceCollector.onChannelRedirect threw an exception",
+ ex
+ );
+ }
+ }
+ callback.onRedirectVerifyCallback(Cr.NS_OK);
+ },
+};
+
+const ChannelEventSinkFactory = ComponentUtils.generateSingletonFactory(
+ ChannelEventSink
+);
+
+ChannelEventSinkFactory.register = function() {
+ const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
+ if (registrar.isCIDRegistered(SINK_CLASS_ID)) {
+ return;
+ }
+
+ registrar.registerFactory(
+ SINK_CLASS_ID,
+ SINK_CLASS_DESCRIPTION,
+ SINK_CONTRACT_ID,
+ ChannelEventSinkFactory
+ );
+
+ Services.catMan.addCategoryEntry(
+ SINK_CATEGORY_NAME,
+ SINK_CONTRACT_ID,
+ SINK_CONTRACT_ID,
+ false,
+ true
+ );
+};
+
+ChannelEventSinkFactory.unregister = function() {
+ const registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
+ registrar.unregisterFactory(SINK_CLASS_ID, ChannelEventSinkFactory);
+
+ Services.catMan.deleteCategoryEntry(
+ SINK_CATEGORY_NAME,
+ SINK_CONTRACT_ID,
+ false
+ );
+};
+
+ChannelEventSinkFactory.getService = function() {
+ // Make sure the ChannelEventSink service is registered before accessing it
+ ChannelEventSinkFactory.register();
+
+ return Cc[SINK_CONTRACT_ID].getService(Ci.nsIChannelEventSink)
+ .wrappedJSObject;
+};
+exports.ChannelEventSinkFactory = ChannelEventSinkFactory;
diff --git a/devtools/server/actors/network-monitor/eventsource-actor.js b/devtools/server/actors/network-monitor/eventsource-actor.js
new file mode 100644
index 0000000000..3ac12c304d
--- /dev/null
+++ b/devtools/server/actors/network-monitor/eventsource-actor.js
@@ -0,0 +1,86 @@
+/* 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";
+
+const { Cc, Ci } = require("chrome");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { eventSourceSpec } = require("devtools/shared/specs/eventsource");
+const { LongStringActor } = require("devtools/server/actors/string");
+
+const eventSourceEventService = Cc[
+ "@mozilla.org/eventsourceevent/service;1"
+].getService(Ci.nsIEventSourceEventService);
+
+/**
+ * This actor intercepts EventSource traffic for a specific window.
+ * @see devtools/shared/spec/eventsource.js for documentation.
+ */
+const EventSourceActor = ActorClassWithSpec(eventSourceSpec, {
+ initialize(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+
+ this.targetActor = targetActor;
+ this.innerWindowID = null;
+
+ // Register for backend events.
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.targetActor.on("window-ready", this.onWindowReady);
+ },
+
+ onWindowReady({ isTopLevel }) {
+ if (isTopLevel) {
+ this.startListening();
+ }
+ },
+
+ destroy: function() {
+ this.targetActor.off("window-ready", this.onWindowReady);
+
+ this.stopListening();
+ Actor.prototype.destroy.call(this);
+ },
+
+ // Actor API.
+
+ startListening: function() {
+ this.stopListening();
+ this.innerWindowID = this.targetActor.window.windowGlobalChild.innerWindowId;
+ eventSourceEventService.addListener(this.innerWindowID, this);
+ },
+
+ stopListening() {
+ if (!this.innerWindowID) {
+ return;
+ }
+ if (eventSourceEventService.hasListenerFor(this.innerWindowID)) {
+ eventSourceEventService.removeListener(this.innerWindowID, this);
+ }
+
+ this.innerWindowID = null;
+ },
+
+ // Implement functions of nsIEventSourceEventService.
+
+ eventSourceConnectionOpened(httpChannelId) {},
+
+ eventSourceConnectionClosed(httpChannelId) {
+ this.emit("serverEventSourceConnectionClosed", httpChannelId);
+ },
+
+ eventReceived(httpChannelId, eventName, lastEventId, data, retry, timeStamp) {
+ let payload = new LongStringActor(this.conn, data);
+ this.manage(payload);
+ payload = payload.form();
+ this.emit("serverEventReceived", httpChannelId, {
+ payload,
+ eventName,
+ lastEventId,
+ retry,
+ timeStamp,
+ });
+ },
+});
+
+exports.EventSourceActor = EventSourceActor;
diff --git a/devtools/server/actors/network-monitor/moz.build b/devtools/server/actors/network-monitor/moz.build
new file mode 100644
index 0000000000..3e05148e78
--- /dev/null
+++ b/devtools/server/actors/network-monitor/moz.build
@@ -0,0 +1,23 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "utils",
+]
+
+DevToolsModules(
+ "channel-event-sink.js",
+ "eventsource-actor.js",
+ "network-content.js",
+ "network-event-actor.js",
+ "network-event.js",
+ "network-monitor.js",
+ "network-observer.js",
+ "network-parent.js",
+ "network-response-listener.js",
+ "stack-trace-collector.js",
+ "websocket-actor.js",
+)
diff --git a/devtools/server/actors/network-monitor/network-content.js b/devtools/server/actors/network-monitor/network-content.js
new file mode 100644
index 0000000000..a852105de4
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-content.js
@@ -0,0 +1,144 @@
+/* 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";
+
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { networkContentSpec } = require("devtools/shared/specs/network-content");
+
+const { Cc, Ci } = require("chrome");
+
+loader.lazyRequireGetter(
+ this,
+ "NetUtil",
+ "resource://gre/modules/NetUtil.jsm",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "stringToCauseType",
+ "devtools/server/actors/network-monitor/network-observer",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "WebConsoleUtils",
+ "devtools/server/actors/webconsole/utils",
+ true
+);
+
+const {
+ TYPES: { NETWORK_EVENT_STACKTRACE },
+ getResourceWatcher,
+} = require("devtools/server/actors/resources/index");
+
+/**
+ * This actor manages all network functionality runnning
+ * in the content process.
+ *
+ * @constructor
+ *
+ */
+const NetworkContentActor = ActorClassWithSpec(networkContentSpec, {
+ initialize(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ },
+
+ destroy(conn) {
+ Actor.prototype.destroy.call(this, conn);
+ },
+
+ get networkEventStackTraceWatcher() {
+ return getResourceWatcher(this.targetActor, NETWORK_EVENT_STACKTRACE);
+ },
+
+ /**
+ * Send an HTTP request
+ *
+ * @param {Object} request
+ * The details of the HTTP Request.
+ * @return {Number}
+ * The channel id for the request
+ */
+ async sendHTTPRequest(request) {
+ const { url, method, headers, body, cause } = request;
+ // Set the loadingNode and loadGroup to the target document - otherwise the
+ // request won't show up in the opened netmonitor.
+ const doc = this.targetActor.window.document;
+
+ const channel = NetUtil.newChannel({
+ uri: NetUtil.newURI(url),
+ loadingNode: doc,
+ securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
+ contentPolicyType:
+ stringToCauseType(cause.type) || Ci.nsIContentPolicy.TYPE_OTHER,
+ });
+
+ channel.QueryInterface(Ci.nsIHttpChannel);
+
+ channel.loadGroup = doc.documentLoadGroup;
+ channel.loadFlags |=
+ Ci.nsIRequest.LOAD_BYPASS_CACHE |
+ Ci.nsIRequest.INHIBIT_CACHING |
+ Ci.nsIRequest.LOAD_ANONYMOUS;
+
+ channel.requestMethod = method;
+ if (headers) {
+ for (const { name, value } of headers) {
+ if (name.toLowerCase() == "referer") {
+ // The referer header and referrerInfo object should always match. So
+ // if we want to set the header from privileged context, we should set
+ // referrerInfo. The referrer header will get set internally.
+ channel.setNewReferrerInfo(
+ value,
+ Ci.nsIReferrerInfo.UNSAFE_URL,
+ true
+ );
+ } else {
+ channel.setRequestHeader(name, value, false);
+ }
+ }
+ }
+
+ if (body) {
+ channel.QueryInterface(Ci.nsIUploadChannel2);
+ const bodyStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+ bodyStream.setData(body, body.length);
+ channel.explicitSetUploadStream(bodyStream, null, -1, method, false);
+ }
+
+ return new Promise(resolve => {
+ // Make sure the fetch has completed before sending the channel id,
+ // so that there is a higher possibilty that the request get into the
+ // redux store beforehand (but this does not gurantee that).
+ NetUtil.asyncFetch(channel, () =>
+ resolve({ channelId: channel.channelId })
+ );
+ });
+ },
+
+ /**
+ * Gets the stacktrace for the specified network resource.
+ * @param {Number} resourceId
+ * The id for the network resource
+ * @return {Object}
+ * The response packet - stack trace.
+ */
+ getStackTrace(resourceId) {
+ if (!this.networkEventStackTraceWatcher) {
+ throw new Error("Not listening for network event stacktraces");
+ }
+ const stacktrace = this.networkEventStackTraceWatcher.getStackTrace(
+ resourceId
+ );
+ return WebConsoleUtils.removeFramesAboveDebuggerEval(stacktrace);
+ },
+});
+
+exports.NetworkContentActor = NetworkContentActor;
diff --git a/devtools/server/actors/network-monitor/network-event-actor.js b/devtools/server/actors/network-monitor/network-event-actor.js
new file mode 100644
index 0000000000..86bb7b9ea9
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-event-actor.js
@@ -0,0 +1,550 @@
+/* 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";
+
+const {
+ TYPES: { NETWORK_EVENT },
+} = require("devtools/server/actors/resources/index");
+
+const protocol = require("devtools/shared/protocol");
+const { networkEventSpec } = require("devtools/shared/specs/network-event");
+const { LongStringActor } = require("devtools/server/actors/string");
+
+/**
+ * Creates an actor for a network event.
+ *
+ * @constructor
+ * @param object networkEventWatcher
+ * The parent NetworkEventWatcher instance for this object.
+ * @param object options
+ * Dictionary object with the following attributes:
+ * - onNetworkEventUpdate: optional function
+ * Listener for updates for the network event
+ */
+const NetworkEventActor = protocol.ActorClassWithSpec(networkEventSpec, {
+ initialize(
+ networkEventWatcher,
+ { onNetworkEventUpdate, onNetworkEventDestroy },
+ networkEvent
+ ) {
+ this.networkEventWatcher = networkEventWatcher;
+ this.conn = this.networkEventWatcher.watcherActor.conn;
+ this.onNetworkEventUpdate = onNetworkEventUpdate;
+ this.onNetworkEventDestroy = onNetworkEventDestroy;
+
+ this.asResource = this.asResource.bind(this);
+
+ // Necessary to get the events to work
+ protocol.Actor.prototype.initialize.call(this, this.conn);
+
+ this._request = {
+ method: networkEvent.method || null,
+ url: networkEvent.url || null,
+ httpVersion: networkEvent.httpVersion || null,
+ headers: [],
+ cookies: [],
+ headersSize: networkEvent.headersSize || null,
+ postData: {},
+ };
+
+ this._response = {
+ headers: [],
+ cookies: [],
+ content: {},
+ };
+
+ this._timings = {};
+ this._serverTimings = [];
+ // Stack trace info isn't sent automatically. The client
+ // needs to request it explicitly using getStackTrace
+ // packet. NetmonitorActor may pass just a boolean instead of the stack
+ // when the actor is in parent process and stack is in the content process.
+ this._stackTrace = false;
+
+ this._discardRequestBody = !!networkEvent.discardRequestBody;
+ this._discardResponseBody = !!networkEvent.discardResponseBody;
+
+ this._startedDateTime = networkEvent.startedDateTime;
+ this._isXHR = networkEvent.isXHR;
+
+ this._cause = networkEvent.cause;
+ // Lets remove the last frame here as
+ // it is passed from the the server by the NETWORK_EVENT_STACKTRACE
+ // resource type. This done here for backward compatibility.
+ if (this._cause.lastFrame) {
+ delete this._cause.lastFrame;
+ }
+
+ this._fromCache = networkEvent.fromCache;
+ this._fromServiceWorker = networkEvent.fromServiceWorker;
+ this._isThirdPartyTrackingResource =
+ networkEvent.isThirdPartyTrackingResource;
+ this._referrerPolicy = networkEvent.referrerPolicy;
+ this._channelId = networkEvent.channelId;
+ this._serial = networkEvent.serial;
+ this._blockedReason = networkEvent.blockedReason;
+ this._blockingExtension = networkEvent.blockingExtension;
+
+ this._truncated = false;
+ this._private = networkEvent.private;
+ },
+
+ /**
+ * Returns a grip for this actor.
+ */
+ asResource() {
+ return {
+ resourceType: NETWORK_EVENT,
+ // The browsingContextID is used by the ResourceWatcher on the client
+ // to find the related Target Front.
+ browsingContextID: this.networkEventWatcher.watcherActor.browserElement
+ .browsingContext.id,
+ resourceId: this._channelId,
+ actor: this.actorID,
+ startedDateTime: this._startedDateTime,
+ timeStamp: Date.parse(this._startedDateTime),
+ url: this._request.url,
+ method: this._request.method,
+ isXHR: this._isXHR,
+ cause: this._cause,
+ timings: {},
+ fromCache: this._fromCache,
+ fromServiceWorker: this._fromServiceWorker,
+ private: this._private,
+ isThirdPartyTrackingResource: this._isThirdPartyTrackingResource,
+ referrerPolicy: this._referrerPolicy,
+ blockedReason: this._blockedReason,
+ blockingExtension: this._blockingExtension,
+ // For websocket requests the serial is used instead of the channel id.
+ stacktraceResourceId:
+ this._cause.type == "websocket" ? this._serial : this._channelId,
+ };
+ },
+
+ /**
+ * Releases this actor from the pool.
+ */
+ destroy(conn) {
+ if (!this.networkEventWatcher) {
+ return;
+ }
+ if (this._channelId) {
+ this.onNetworkEventDestroy(this._channelId);
+ }
+
+ this.networkEventWatcher = null;
+ protocol.Actor.prototype.destroy.call(this, conn);
+ },
+
+ release() {
+ // Per spec, destroy is automatically going to be called after this request
+ },
+
+ /**
+ * The "getRequestHeaders" packet type handler.
+ *
+ * @return object
+ * The response packet - network request headers.
+ */
+ getRequestHeaders() {
+ return {
+ headers: this._request.headers,
+ headersSize: this._request.headersSize,
+ rawHeaders: this._request.rawHeaders,
+ };
+ },
+
+ /**
+ * The "getRequestCookies" packet type handler.
+ *
+ * @return object
+ * The response packet - network request cookies.
+ */
+ getRequestCookies() {
+ return {
+ cookies: this._request.cookies,
+ };
+ },
+
+ /**
+ * The "getRequestPostData" packet type handler.
+ *
+ * @return object
+ * The response packet - network POST data.
+ */
+ getRequestPostData() {
+ return {
+ postData: this._request.postData,
+ postDataDiscarded: this._discardRequestBody,
+ };
+ },
+
+ /**
+ * The "getSecurityInfo" packet type handler.
+ *
+ * @return object
+ * The response packet - connection security information.
+ */
+ getSecurityInfo() {
+ return {
+ securityInfo: this._securityInfo,
+ };
+ },
+
+ /**
+ * The "getResponseHeaders" packet type handler.
+ *
+ * @return object
+ * The response packet - network response headers.
+ */
+ getResponseHeaders() {
+ return {
+ headers: this._response.headers,
+ headersSize: this._response.headersSize,
+ rawHeaders: this._response.rawHeaders,
+ };
+ },
+
+ /**
+ * The "getResponseCache" packet type handler.
+ *
+ * @return object
+ * The cache packet - network cache information.
+ */
+ getResponseCache: function() {
+ return {
+ cache: this._response.responseCache,
+ };
+ },
+
+ /**
+ * The "getResponseCookies" packet type handler.
+ *
+ * @return object
+ * The response packet - network response cookies.
+ */
+ getResponseCookies() {
+ return {
+ cookies: this._response.cookies,
+ };
+ },
+
+ /**
+ * The "getResponseContent" packet type handler.
+ *
+ * @return object
+ * The response packet - network response content.
+ */
+ getResponseContent() {
+ return {
+ content: this._response.content,
+ contentDiscarded: this._discardResponseBody,
+ };
+ },
+
+ /**
+ * The "getEventTimings" packet type handler.
+ *
+ * @return object
+ * The response packet - network event timings.
+ */
+ getEventTimings() {
+ return {
+ timings: this._timings,
+ totalTime: this._totalTime,
+ offsets: this._offsets,
+ serverTimings: this._serverTimings,
+ };
+ },
+
+ /** ****************************************************************
+ * Listeners for new network event data coming from NetworkMonitor.
+ ******************************************************************/
+
+ /**
+ * Add network request headers.
+ *
+ * @param array headers
+ * The request headers array.
+ * @param string rawHeaders
+ * The raw headers source.
+ */
+ addRequestHeaders(headers, rawHeaders) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._request.headers = headers;
+ this._prepareHeaders(headers);
+
+ if (rawHeaders) {
+ rawHeaders = new LongStringActor(this.conn, rawHeaders);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(rawHeaders);
+ rawHeaders = rawHeaders.form();
+ }
+ this._request.rawHeaders = rawHeaders;
+
+ this._onEventUpdate("requestHeaders", {
+ headers: headers.length,
+ headersSize: this._request.headersSize,
+ });
+ },
+
+ /**
+ * Add network request cookies.
+ *
+ * @param array cookies
+ * The request cookies array.
+ */
+ addRequestCookies(cookies) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._request.cookies = cookies;
+ this._prepareHeaders(cookies);
+
+ this._onEventUpdate("requestCookies", { cookies: cookies.length });
+ },
+
+ /**
+ * Add network request POST data.
+ *
+ * @param object postData
+ * The request POST data.
+ */
+ addRequestPostData(postData) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._request.postData = postData;
+ postData.text = new LongStringActor(this.conn, postData.text);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(postData.text);
+ postData.text = postData.text.form();
+
+ this._onEventUpdate("requestPostData", {});
+ },
+
+ /**
+ * Add the initial network response information.
+ *
+ * @param object info
+ * The response information.
+ * @param string rawHeaders
+ * The raw headers source.
+ */
+ addResponseStart(info, rawHeaders) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ rawHeaders = new LongStringActor(this.conn, rawHeaders);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(rawHeaders);
+ this._response.rawHeaders = rawHeaders.form();
+
+ this._response.httpVersion = info.httpVersion;
+ this._response.status = info.status;
+ this._response.statusText = info.statusText;
+ this._response.headersSize = info.headersSize;
+ this._response.waitingTime = info.waitingTime;
+ // Consider as not discarded if info.discardResponseBody is undefined
+ this._discardResponseBody = !!info.discardResponseBody;
+
+ this._onEventUpdate("responseStart", { ...info });
+ },
+
+ /**
+ * Add connection security information.
+ *
+ * @param object info
+ * The object containing security information.
+ */
+ addSecurityInfo(info, isRacing) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._securityInfo = info;
+
+ this._onEventUpdate("securityInfo", {
+ state: info.state,
+ isRacing: isRacing,
+ });
+ },
+
+ /**
+ * Add network response headers.
+ *
+ * @param array headers
+ * The response headers array.
+ */
+ addResponseHeaders(headers) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._response.headers = headers;
+ this._prepareHeaders(headers);
+
+ this._onEventUpdate("responseHeaders", {
+ headers: headers.length,
+ headersSize: this._response.headersSize,
+ });
+ },
+
+ /**
+ * Add network response cookies.
+ *
+ * @param array cookies
+ * The response cookies array.
+ */
+ addResponseCookies(cookies) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._response.cookies = cookies;
+ this._prepareHeaders(cookies);
+
+ this._onEventUpdate("responseCookies", { cookies: cookies.length });
+ },
+
+ /**
+ * Add network response content.
+ *
+ * @param object content
+ * The response content.
+ * @param object
+ * - boolean discardedResponseBody
+ * Tells if the response content was recorded or not.
+ * - boolean truncated
+ * Tells if the some of the response content is missing.
+ */
+ addResponseContent(
+ content,
+ { discardResponseBody, truncated, blockedReason, blockingExtension }
+ ) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._truncated = truncated;
+ this._response.content = content;
+ content.text = new LongStringActor(this.conn, content.text);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(content.text);
+ content.text = content.text.form();
+
+ this._onEventUpdate("responseContent", {
+ mimeType: content.mimeType,
+ contentSize: content.size,
+ transferredSize: content.transferredSize,
+ blockedReason,
+ blockingExtension,
+ });
+ },
+
+ addResponseCache: function(content) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+ this._response.responseCache = content.responseCache;
+ this._onEventUpdate("responseCache", {});
+ },
+
+ /**
+ * Add network event timing information.
+ *
+ * @param number total
+ * The total time of the network event.
+ * @param object timings
+ * Timing details about the network event.
+ * @param object offsets
+ * @param object serverTimings
+ * Timing details extracted from the Server-Timing header.
+ */
+ addEventTimings(total, timings, offsets, serverTimings) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._totalTime = total;
+ this._timings = timings;
+ this._offsets = offsets;
+
+ if (serverTimings) {
+ this._serverTimings = serverTimings;
+ }
+
+ this._onEventUpdate("eventTimings", { totalTime: total });
+ },
+
+ /**
+ * Store server timing information. They will be merged together
+ * with network event timing data when they are available and
+ * notification sent to the client.
+ * See `addEventTimnings`` above for more information.
+ *
+ * @param object serverTimings
+ * Timing details extracted from the Server-Timing header.
+ */
+ addServerTimings(serverTimings) {
+ if (serverTimings) {
+ this._serverTimings = serverTimings;
+ }
+ },
+
+ /**
+ * Prepare the headers array to be sent to the client by using the
+ * LongStringActor for the header values, when needed.
+ *
+ * @private
+ * @param array aHeaders
+ */
+ _prepareHeaders(headers) {
+ for (const header of headers) {
+ header.value = new LongStringActor(this.conn, header.value);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(header.value);
+ header.value = header.value.form();
+ }
+ },
+ /**
+ * Sends the updated event data to the client
+ *
+ * @private
+ * @param string updateType
+ * @param object data
+ * The properties that have changed for the event
+ */
+ _onEventUpdate(updateType, data) {
+ this.onNetworkEventUpdate({
+ resourceId: this._channelId,
+ updateType,
+ ...data,
+ });
+ },
+});
+
+exports.NetworkEventActor = NetworkEventActor;
diff --git a/devtools/server/actors/network-monitor/network-event.js b/devtools/server/actors/network-monitor/network-event.js
new file mode 100644
index 0000000000..9fa46c81ca
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-event.js
@@ -0,0 +1,594 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { networkEventSpec } = require("devtools/shared/specs/network-event");
+const { LongStringActor } = require("devtools/server/actors/string");
+
+/**
+ * Creates an actor for a network event.
+ *
+ * @constructor
+ * @param object netMonitorActor
+ * The parent NetworkMonitorActor instance for this object.
+ */
+const NetworkEventActor = protocol.ActorClassWithSpec(networkEventSpec, {
+ initialize(netMonitorActor) {
+ // Necessary to get the events to work
+ protocol.Actor.prototype.initialize.call(this, netMonitorActor.conn);
+
+ this.netMonitorActor = netMonitorActor;
+ this.conn = this.netMonitorActor.conn;
+
+ this._request = {
+ method: null,
+ url: null,
+ httpVersion: null,
+ headers: [],
+ cookies: [],
+ headersSize: null,
+ postData: {},
+ };
+
+ this._response = {
+ headers: [],
+ cookies: [],
+ content: {},
+ };
+
+ this._timings = {};
+ this._serverTimings = [];
+ this._stackTrace = {};
+
+ this._discardRequestBody = false;
+ this._discardResponseBody = false;
+ },
+
+ _request: null,
+ _response: null,
+ _timings: null,
+ _serverTimings: null,
+
+ /**
+ * Returns a grip for this actor for returning in a protocol message.
+ */
+ form() {
+ return {
+ actor: this.actorID,
+ startedDateTime: this._startedDateTime,
+ timeStamp: Date.parse(this._startedDateTime),
+ url: this._request.url,
+ method: this._request.method,
+ isXHR: this._isXHR,
+ cause: this._cause,
+ fromCache: this._fromCache,
+ fromServiceWorker: this._fromServiceWorker,
+ private: this._private,
+ isThirdPartyTrackingResource: this._isThirdPartyTrackingResource,
+ referrerPolicy: this._referrerPolicy,
+ blockedReason: this._blockedReason,
+ blockingExtension: this._blockingExtension,
+ channelId: this._channelId,
+ };
+ },
+
+ /**
+ * Releases this actor from the pool.
+ */
+ destroy(conn) {
+ if (!this.netMonitorActor) {
+ return;
+ }
+ if (this._request.url) {
+ this.netMonitorActor._networkEventActorsByURL.delete(this._request.url);
+ }
+ if (this.channel) {
+ this.netMonitorActor._netEvents.delete(this.channel);
+ }
+
+ this.netMonitorActor = null;
+ protocol.Actor.prototype.destroy.call(this, conn);
+ },
+
+ release() {
+ // Per spec, destroy is automatically going to be called after this request
+ },
+
+ /**
+ * Set the properties of this actor based on it's corresponding
+ * network event.
+ *
+ * @param object networkEvent
+ * The network event associated with this actor.
+ */
+ init(networkEvent) {
+ this._startedDateTime = networkEvent.startedDateTime;
+ this._isXHR = networkEvent.isXHR;
+ this._cause = networkEvent.cause;
+ this._fromCache = networkEvent.fromCache;
+ this._fromServiceWorker = networkEvent.fromServiceWorker;
+ this._isThirdPartyTrackingResource =
+ networkEvent.isThirdPartyTrackingResource;
+ this._referrerPolicy = networkEvent.referrerPolicy;
+ this._channelId = networkEvent.channelId;
+
+ // Stack trace info isn't sent automatically. The client
+ // needs to request it explicitly using getStackTrace
+ // packet. NetmonitorActor may pass just a boolean instead of the stack
+ // when the actor is in parent process and stack is in the content process.
+ this._stackTrace = networkEvent.cause.stacktrace;
+ delete networkEvent.cause.stacktrace;
+ networkEvent.cause.stacktraceAvailable = !!(
+ this._stackTrace &&
+ (typeof this._stackTrace == "boolean" || this._stackTrace.length)
+ );
+
+ for (const prop of ["method", "url", "httpVersion", "headersSize"]) {
+ this._request[prop] = networkEvent[prop];
+ }
+
+ // Consider as not discarded if networkEvent.discard*Body is undefined
+ this._discardRequestBody = !!networkEvent.discardRequestBody;
+ this._discardResponseBody = !!networkEvent.discardResponseBody;
+
+ this._blockedReason = networkEvent.blockedReason;
+ this._blockingExtension = networkEvent.blockingExtension;
+
+ this._truncated = false;
+ this._private = networkEvent.private;
+ },
+
+ /**
+ * The "getRequestHeaders" packet type handler.
+ *
+ * @return object
+ * The response packet - network request headers.
+ */
+ getRequestHeaders() {
+ return {
+ headers: this._request.headers,
+ headersSize: this._request.headersSize,
+ rawHeaders: this._request.rawHeaders,
+ };
+ },
+
+ /**
+ * The "getRequestCookies" packet type handler.
+ *
+ * @return object
+ * The response packet - network request cookies.
+ */
+ getRequestCookies() {
+ return {
+ cookies: this._request.cookies,
+ };
+ },
+
+ /**
+ * The "getRequestPostData" packet type handler.
+ *
+ * @return object
+ * The response packet - network POST data.
+ */
+ getRequestPostData() {
+ return {
+ postData: this._request.postData,
+ postDataDiscarded: this._discardRequestBody,
+ };
+ },
+
+ /**
+ * The "getSecurityInfo" packet type handler.
+ *
+ * @return object
+ * The response packet - connection security information.
+ */
+ getSecurityInfo() {
+ return {
+ securityInfo: this._securityInfo,
+ };
+ },
+
+ /**
+ * The "getResponseHeaders" packet type handler.
+ *
+ * @return object
+ * The response packet - network response headers.
+ */
+ getResponseHeaders() {
+ return {
+ headers: this._response.headers,
+ headersSize: this._response.headersSize,
+ rawHeaders: this._response.rawHeaders,
+ };
+ },
+
+ /**
+ * The "getResponseCache" packet type handler.
+ *
+ * @return object
+ * The cache packet - network cache information.
+ */
+ getResponseCache: function() {
+ return {
+ cache: this._response.responseCache,
+ };
+ },
+
+ /**
+ * The "getResponseCookies" packet type handler.
+ *
+ * @return object
+ * The response packet - network response cookies.
+ */
+ getResponseCookies() {
+ return {
+ cookies: this._response.cookies,
+ };
+ },
+
+ /**
+ * The "getResponseContent" packet type handler.
+ *
+ * @return object
+ * The response packet - network response content.
+ */
+ getResponseContent() {
+ return {
+ content: this._response.content,
+ contentDiscarded: this._discardResponseBody,
+ };
+ },
+
+ /**
+ * The "getEventTimings" packet type handler.
+ *
+ * @return object
+ * The response packet - network event timings.
+ */
+ getEventTimings() {
+ return {
+ timings: this._timings,
+ totalTime: this._totalTime,
+ offsets: this._offsets,
+ serverTimings: this._serverTimings,
+ };
+ },
+
+ /**
+ * The "getStackTrace" packet type handler.
+ *
+ * @return object
+ * The response packet - stack trace.
+ */
+ async getStackTrace() {
+ let stacktrace = this._stackTrace;
+ // If _stackTrace was "true", it means we are in parent process
+ // and the stack is available from the content process.
+ // Fetch it lazily from here via the message manager.
+ if (stacktrace && typeof stacktrace == "boolean") {
+ let id;
+ if (this._cause.type == "websocket") {
+ // Convert to a websocket URL, as in onNetworkEvent.
+ id = this._request.url.replace(/^http/, "ws");
+ } else {
+ id = this._channelId;
+ }
+
+ const messageManager = this.netMonitorActor.messageManager;
+ stacktrace = await new Promise(resolve => {
+ const onMessage = ({ data }) => {
+ const { channelId, stack } = data;
+ if (channelId == id) {
+ messageManager.removeMessageListener(
+ "debug:request-stack:response",
+ onMessage
+ );
+ resolve(stack);
+ }
+ };
+ messageManager.addMessageListener(
+ "debug:request-stack:response",
+ onMessage
+ );
+ messageManager.sendAsyncMessage("debug:request-stack:request", id);
+ });
+ this._stackTrace = stacktrace;
+ }
+
+ return {
+ stacktrace,
+ };
+ },
+
+ /** ****************************************************************
+ * Listeners for new network event data coming from NetworkMonitor.
+ ******************************************************************/
+
+ /**
+ * Add network request headers.
+ *
+ * @param array headers
+ * The request headers array.
+ * @param string rawHeaders
+ * The raw headers source.
+ */
+ addRequestHeaders(headers, rawHeaders) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._request.headers = headers;
+ this._prepareHeaders(headers);
+
+ if (rawHeaders) {
+ rawHeaders = new LongStringActor(this.conn, rawHeaders);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(rawHeaders);
+ rawHeaders = rawHeaders.form();
+ }
+ this._request.rawHeaders = rawHeaders;
+
+ this.emit("network-event-update:headers", "requestHeaders", {
+ headers: headers.length,
+ headersSize: this._request.headersSize,
+ });
+ },
+
+ /**
+ * Add network request cookies.
+ *
+ * @param array cookies
+ * The request cookies array.
+ */
+ addRequestCookies(cookies) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._request.cookies = cookies;
+ this._prepareHeaders(cookies);
+
+ this.emit("network-event-update:cookies", "requestCookies", {
+ cookies: cookies.length,
+ });
+ },
+
+ /**
+ * Add network request POST data.
+ *
+ * @param object postData
+ * The request POST data.
+ */
+ addRequestPostData(postData) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._request.postData = postData;
+ postData.text = new LongStringActor(this.conn, postData.text);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(postData.text);
+ const dataSize = postData.size;
+ postData.text = postData.text.form();
+
+ this.emit("network-event-update:post-data", "requestPostData", {
+ dataSize,
+ discardRequestBody: this._discardRequestBody,
+ });
+ },
+
+ /**
+ * Add the initial network response information.
+ *
+ * @param object info
+ * The response information.
+ * @param string rawHeaders
+ * The raw headers source.
+ */
+ addResponseStart(info, rawHeaders) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ rawHeaders = new LongStringActor(this.conn, rawHeaders);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(rawHeaders);
+ this._response.rawHeaders = rawHeaders.form();
+
+ this._response.httpVersion = info.httpVersion;
+ this._response.status = info.status;
+ this._response.statusText = info.statusText;
+ this._response.headersSize = info.headersSize;
+ this._response.waitingTime = info.waitingTime;
+ // Consider as not discarded if info.discardResponseBody is undefined
+ this._discardResponseBody = !!info.discardResponseBody;
+
+ this.emit("network-event-update:response-start", "responseStart", {
+ response: info,
+ });
+ },
+
+ /**
+ * Add connection security information.
+ *
+ * @param object info
+ * The object containing security information.
+ */
+ addSecurityInfo(info, isRacing) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._securityInfo = info;
+ this.emit("network-event-update:security-info", "securityInfo", {
+ state: info.state,
+ isRacing: isRacing,
+ });
+ },
+
+ /**
+ * Add network response headers.
+ *
+ * @param array headers
+ * The response headers array.
+ */
+ addResponseHeaders(headers) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._response.headers = headers;
+ this._prepareHeaders(headers);
+
+ this.emit("network-event-update:headers", "responseHeaders", {
+ headers: headers.length,
+ headersSize: this._response.headersSize,
+ });
+ },
+
+ /**
+ * Add network response cookies.
+ *
+ * @param array cookies
+ * The response cookies array.
+ */
+ addResponseCookies(cookies) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._response.cookies = cookies;
+ this._prepareHeaders(cookies);
+
+ this.emit("network-event-update:cookies", "responseCookies", {
+ cookies: cookies.length,
+ });
+ },
+
+ /**
+ * Add network response content.
+ *
+ * @param object content
+ * The response content.
+ * @param object
+ * - boolean discardedResponseBody
+ * Tells if the response content was recorded or not.
+ * - boolean truncated
+ * Tells if the some of the response content is missing.
+ */
+ addResponseContent(
+ content,
+ { discardResponseBody, truncated, blockedReason, blockingExtension }
+ ) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._truncated = truncated;
+ this._response.content = content;
+ content.text = new LongStringActor(this.conn, content.text);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(content.text);
+ content.text = content.text.form();
+
+ this.emit("network-event-update:response-content", "responseContent", {
+ mimeType: content.mimeType,
+ contentSize: content.size,
+ encoding: content.encoding,
+ transferredSize: content.transferredSize,
+ discardResponseBody,
+ blockedReason,
+ blockingExtension,
+ });
+ },
+
+ addResponseCache: function(content) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._response.responseCache = content.responseCache;
+ this.emit("network-event-update:response-cache", "responseCache");
+ },
+
+ /**
+ * Add network event timing information.
+ *
+ * @param number total
+ * The total time of the network event.
+ * @param object timings
+ * Timing details about the network event.
+ * @param object offsets
+ * @param object serverTimings
+ * Timing details extracted from the Server-Timing header.
+ */
+ addEventTimings(total, timings, offsets, serverTimings) {
+ // Ignore calls when this actor is already destroyed
+ if (this.isDestroyed()) {
+ return;
+ }
+
+ this._totalTime = total;
+ this._timings = timings;
+ this._offsets = offsets;
+
+ if (serverTimings) {
+ this._serverTimings = serverTimings;
+ }
+
+ this.emit("network-event-update:event-timings", "eventTimings", {
+ totalTime: total,
+ });
+ },
+
+ /**
+ * Store server timing information. They will be merged together
+ * with network event timing data when they are available and
+ * notification sent to the client.
+ * See `addEventTimnings`` above for more information.
+ *
+ * @param object serverTimings
+ * Timing details extracted from the Server-Timing header.
+ */
+ addServerTimings(serverTimings) {
+ if (serverTimings) {
+ this._serverTimings = serverTimings;
+ }
+ },
+
+ /**
+ * Prepare the headers array to be sent to the client by using the
+ * LongStringActor for the header values, when needed.
+ *
+ * @private
+ * @param array aHeaders
+ */
+ _prepareHeaders(headers) {
+ for (const header of headers) {
+ header.value = new LongStringActor(this.conn, header.value);
+ // bug 1462561 - Use "json" type and manually manage/marshall actors to woraround
+ // protocol.js performance issue
+ this.manage(header.value);
+ header.value = header.value.form();
+ }
+ },
+});
+
+exports.NetworkEventActor = NetworkEventActor;
diff --git a/devtools/server/actors/network-monitor/network-monitor.js b/devtools/server/actors/network-monitor/network-monitor.js
new file mode 100644
index 0000000000..be50e9b62c
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-monitor.js
@@ -0,0 +1,277 @@
+/* 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";
+
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { networkMonitorSpec } = require("devtools/shared/specs/network-monitor");
+
+loader.lazyRequireGetter(
+ this,
+ "NetworkObserver",
+ "devtools/server/actors/network-monitor/network-observer",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "NetworkEventActor",
+ "devtools/server/actors/network-monitor/network-event",
+ true
+);
+
+const NetworkMonitorActor = ActorClassWithSpec(networkMonitorSpec, {
+ /**
+ * NetworkMonitorActor is instanciated from WebConsoleActor.startListeners
+ * Either in the same process, for debugging service worker requests or when debugging
+ * the parent process itself and tracking chrome requests.
+ * Or in another process, for tracking content requests that are actually done in the
+ * parent process.
+ *
+ * @param object filters
+ * Contains an `browserId` attribute when this is used across processes.
+ * Or a `window` attribute when instanciated in the same process.
+ * @param number parentID (optional)
+ * To be removed, specify the ID of the Web console actor.
+ * This is used to fake emitting an event from it to prevent changing RDP
+ * behavior.
+ * @param nsIMessageManager messageManager
+ * This is the manager to use to communicate with the console actor. When both
+ * netmonitor and console actor runs in the same process, this is an instance
+ * of MockMessageManager instead of a real message manager.
+ */
+ initialize(conn, filters, parentID, messageManager) {
+ Actor.prototype.initialize.call(this, conn);
+
+ // Map of all NetworkEventActor indexed by channel ID
+ this._netEvents = new Map();
+
+ // Map of all NetworkEventActor indexed by URL
+ this._networkEventActorsByURL = new Map();
+
+ this.parentID = parentID;
+ this.messageManager = messageManager;
+
+ // Immediately start watching for new request according to `filters`.
+ // NetworkMonitor will call `onNetworkEvent` method.
+ this.observer = new NetworkObserver(filters, this);
+ this.observer.init();
+
+ this.stackTraces = new Set();
+ this.lastFrames = new Map();
+
+ this.onStackTraceAvailable = this.onStackTraceAvailable.bind(this);
+ this.onSetPreference = this.onSetPreference.bind(this);
+ this.onBlockRequest = this.onBlockRequest.bind(this);
+ this.onUnblockRequest = this.onUnblockRequest.bind(this);
+ this.onSetBlockedUrls = this.onSetBlockedUrls.bind(this);
+ this.onGetBlockedUrls = this.onGetBlockedUrls.bind(this);
+ this.onGetNetworkEventActor = this.onGetNetworkEventActor.bind(this);
+ this.onDestroyMessage = this.onDestroyMessage.bind(this);
+
+ this.startListening();
+ },
+
+ onDestroyMessage({ data }) {
+ if (data.actorID == this.parentID) {
+ this.destroy();
+ }
+ },
+
+ startListening() {
+ this.messageManager.addMessageListener(
+ "debug:request-stack-available",
+ this.onStackTraceAvailable
+ );
+ this.messageManager.addMessageListener(
+ "debug:netmonitor-preference",
+ this.onSetPreference
+ );
+ this.messageManager.addMessageListener(
+ "debug:block-request",
+ this.onBlockRequest
+ );
+ this.messageManager.addMessageListener(
+ "debug:unblock-request",
+ this.onUnblockRequest
+ );
+ this.messageManager.addMessageListener(
+ "debug:set-blocked-urls",
+ this.onSetBlockedUrls
+ );
+ this.messageManager.addMessageListener(
+ "debug:get-blocked-urls",
+ this.onGetBlockedUrls
+ );
+ this.messageManager.addMessageListener(
+ "debug:get-network-event-actor:request",
+ this.onGetNetworkEventActor
+ );
+ this.messageManager.addMessageListener(
+ "debug:destroy-network-monitor",
+ this.onDestroyMessage
+ );
+ },
+
+ stopListening() {
+ this.messageManager.removeMessageListener(
+ "debug:request-stack-available",
+ this.onStackTraceAvailable
+ );
+ this.messageManager.removeMessageListener(
+ "debug:netmonitor-preference",
+ this.onSetPreference
+ );
+ this.messageManager.removeMessageListener(
+ "debug:block-request",
+ this.onBlockRequest
+ );
+ this.messageManager.removeMessageListener(
+ "debug:unblock-request",
+ this.onUnblockRequest
+ );
+ this.messageManager.removeMessageListener(
+ "debug:set-blocked-urls",
+ this.onSetBlockedUrls
+ );
+ this.messageManager.removeMessageListener(
+ "debug:get-blocked-urls",
+ this.onGetBlockedUrls
+ );
+ this.messageManager.removeMessageListener(
+ "debug:get-network-event-actor:request",
+ this.onGetNetworkEventActor
+ );
+ this.messageManager.removeMessageListener(
+ "debug:destroy-network-monitor",
+ this.onDestroyMessage
+ );
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ if (this.observer) {
+ this.observer.destroy();
+ this.observer = null;
+ }
+
+ this.stackTraces.clear();
+ this.lastFrames.clear();
+ if (this.messageManager) {
+ this.stopListening();
+ this.messageManager = null;
+ }
+ },
+
+ onStackTraceAvailable(msg) {
+ const { channelId } = msg.data;
+ if (!msg.data.stacktrace) {
+ this.lastFrames.delete(channelId);
+ this.stackTraces.delete(channelId);
+ } else {
+ if (msg.data.lastFrame) {
+ this.lastFrames.set(channelId, msg.data.lastFrame);
+ }
+ this.stackTraces.add(channelId);
+ }
+ },
+
+ onSetPreference({ data }) {
+ if ("saveRequestAndResponseBodies" in data) {
+ this.observer.saveRequestAndResponseBodies =
+ data.saveRequestAndResponseBodies;
+ }
+ if ("throttleData" in data) {
+ this.observer.throttleData = data.throttleData;
+ }
+ },
+
+ onBlockRequest({ data }) {
+ const { filter } = data;
+ this.observer.blockRequest(filter);
+ this.messageManager.sendAsyncMessage("debug:block-request:response");
+ },
+
+ onUnblockRequest({ data }) {
+ const { filter } = data;
+ this.observer.unblockRequest(filter);
+ this.messageManager.sendAsyncMessage("debug:unblock-request:response");
+ },
+
+ onSetBlockedUrls({ data }) {
+ const { urls } = data;
+ this.observer.setBlockedUrls(urls);
+ this.messageManager.sendAsyncMessage("debug:set-blocked-urls:response");
+ },
+
+ onGetBlockedUrls() {
+ const urls = this.observer.getBlockedUrls();
+ this.messageManager.sendAsyncMessage(
+ "debug:get-blocked-urls:response",
+ urls
+ );
+ },
+
+ onGetNetworkEventActor({ data }) {
+ const actor = this.getNetworkEventActor(data.channelId);
+ this.messageManager.sendAsyncMessage(
+ "debug:get-network-event-actor:response",
+ {
+ channelId: data.channelId,
+ actor: actor.form(),
+ }
+ );
+ },
+
+ getNetworkEventActor(channelId) {
+ let actor = this._netEvents.get(channelId);
+ if (actor) {
+ return actor;
+ }
+
+ actor = new NetworkEventActor(this);
+ this.manage(actor);
+
+ // map channel to actor so we can associate future events with it
+ this._netEvents.set(channelId, actor);
+ return actor;
+ },
+
+ // This method is called by NetworkMonitor instance when a new request is fired
+ onNetworkEvent(event) {
+ const { channelId, cause, url } = event;
+
+ const actor = this.getNetworkEventActor(channelId);
+ this._netEvents.set(channelId, actor);
+
+ // Find the ID which the stack trace collector will use to save this
+ // channel's stack trace.
+ let id;
+ if (cause.type == "websocket") {
+ // Use the URL, but convert from the http URL which this channel uses to
+ // the original websocket URL which triggered this channel's construction.
+ id = url.replace(/^http/, "ws");
+ } else {
+ id = channelId;
+ }
+
+ event.cause.stacktrace = this.stackTraces.has(id);
+ if (event.cause.stacktrace) {
+ this.stackTraces.delete(id);
+ }
+ if (this.lastFrames.has(id)) {
+ event.cause.lastFrame = this.lastFrames.get(id);
+ this.lastFrames.delete(id);
+ }
+ actor.init(event);
+
+ this._networkEventActorsByURL.set(actor._request.url, actor);
+
+ this.conn.sendActorEvent(this.parentID, "networkEvent", {
+ eventActor: actor.form(),
+ });
+ return actor;
+ },
+});
+exports.NetworkMonitorActor = NetworkMonitorActor;
diff --git a/devtools/server/actors/network-monitor/network-observer.js b/devtools/server/actors/network-monitor/network-observer.js
new file mode 100644
index 0000000000..b5c45ab7d2
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-observer.js
@@ -0,0 +1,1721 @@
+/* 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";
+
+/**
+ * NetworkObserver is the main class in DevTools to observe network requests
+ * out of many events fired by the platform code.
+ */
+
+// Enable logging all platform events this module listen to
+const DEBUG_PLATFORM_EVENTS = false;
+
+const { Cc, Ci, Cr, Cu } = require("chrome");
+const Services = require("Services");
+const {
+ wildcardToRegExp,
+} = require("devtools/server/actors/network-monitor/utils/wildcard-to-regexp");
+loader.lazyRequireGetter(
+ this,
+ "ChannelMap",
+ "devtools/server/actors/network-monitor/utils/channel-map",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getErrorCodeString",
+ "devtools/server/actors/network-monitor/utils/error-codes",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "NetworkHelper",
+ "devtools/shared/webconsole/network-helper"
+);
+loader.lazyRequireGetter(
+ this,
+ "DevToolsUtils",
+ "devtools/shared/DevToolsUtils"
+);
+loader.lazyRequireGetter(
+ this,
+ "NetworkThrottleManager",
+ "devtools/shared/webconsole/throttle",
+ true
+);
+loader.lazyServiceGetter(
+ this,
+ "gActivityDistributor",
+ "@mozilla.org/network/http-activity-distributor;1",
+ "nsIHttpActivityDistributor"
+);
+loader.lazyRequireGetter(
+ this,
+ "NetworkResponseListener",
+ "devtools/server/actors/network-monitor/network-response-listener",
+ true
+);
+loader.lazyGetter(
+ this,
+ "WebExtensionPolicy",
+ () => Cu.getGlobalForObject(Cu).WebExtensionPolicy
+);
+
+function logPlatformEvent(eventName, channel, message = "") {
+ if (!DEBUG_PLATFORM_EVENTS) {
+ return;
+ }
+ dump(`[netmonitor] ${channel.channelId} - ${eventName} ${message}\n`);
+}
+
+// The maximum uint32 value.
+const PR_UINT32_MAX = 4294967295;
+
+// HTTP status codes.
+const HTTP_MOVED_PERMANENTLY = 301;
+const HTTP_FOUND = 302;
+const HTTP_SEE_OTHER = 303;
+const HTTP_TEMPORARY_REDIRECT = 307;
+
+/**
+ * Check if a given network request should be logged by a network monitor
+ * based on the specified filters.
+ *
+ * @param nsIHttpChannel channel
+ * Request to check.
+ * @param filters
+ * NetworkObserver filters to match against.
+ * @return boolean
+ * True if the network request should be logged, false otherwise.
+ */
+function matchRequest(channel, filters) {
+ // Log everything if no filter is specified
+ if (!filters.browserId && !filters.window) {
+ return true;
+ }
+
+ // Ignore requests from chrome or add-on code when we are monitoring
+ // content.
+ if (
+ channel.loadInfo &&
+ channel.loadInfo.loadingDocument === null &&
+ (channel.loadInfo.loadingPrincipal ===
+ Services.scriptSecurityManager.getSystemPrincipal() ||
+ channel.loadInfo.isInDevToolsContext)
+ ) {
+ return false;
+ }
+
+ if (filters.window) {
+ // Since frames support, this.window may not be the top level content
+ // frame, so that we can't only compare with win.top.
+ let win = NetworkHelper.getWindowForRequest(channel);
+ while (win) {
+ if (win == filters.window) {
+ return true;
+ }
+ if (win.parent == win) {
+ break;
+ }
+ win = win.parent;
+ }
+ }
+
+ if (filters.browserId) {
+ const topFrame = NetworkHelper.getTopFrameForRequest(channel);
+ // topFrame is typically null for some chrome requests like favicons
+ if (topFrame && topFrame.browsingContext.browserId == filters.browserId) {
+ return true;
+ }
+
+ // If we couldn't get the top frame BrowsingContext from the loadContext,
+ // look for it on channel.loadInfo instead.
+ if (
+ channel.loadInfo &&
+ channel.loadInfo.browsingContext &&
+ channel.loadInfo.browsingContext.browserId == filters.browserId
+ ) {
+ return true;
+ }
+ }
+
+ return false;
+}
+exports.matchRequest = matchRequest;
+
+/**
+ * The network monitor uses the nsIHttpActivityDistributor to monitor network
+ * requests. The nsIObserverService is also used for monitoring
+ * http-on-examine-response notifications. All network request information is
+ * routed to the remote Web Console.
+ *
+ * @constructor
+ * @param object filters
+ * Object with the filters to use for network requests:
+ * - window (nsIDOMWindow): filter network requests by the associated
+ * window object.
+ * - browserId (number): filter requests by their top frame's Browser Element.
+ * Filters are optional. If any of these filters match the request is
+ * logged (OR is applied). If no filter is provided then all requests are
+ * logged.
+ * @param object owner
+ * The network observer owner. This object needs to hold:
+ * - onNetworkEvent(requestInfo)
+ * This method is invoked once for every new network request and it is
+ * given the initial network request information as an argument.
+ * onNetworkEvent() must return an object which holds several add*()
+ * methods which are used to add further network request/response information.
+ */
+function NetworkObserver(filters, owner) {
+ this.filters = filters;
+ this.owner = owner;
+
+ this.openRequests = new ChannelMap();
+ this.openResponses = new ChannelMap();
+
+ this.blockedURLs = [];
+
+ this._httpResponseExaminer = DevToolsUtils.makeInfallible(
+ this._httpResponseExaminer
+ ).bind(this);
+ this._httpModifyExaminer = DevToolsUtils.makeInfallible(
+ this._httpModifyExaminer
+ ).bind(this);
+ this._httpFailedOpening = DevToolsUtils.makeInfallible(
+ this._httpFailedOpening
+ ).bind(this);
+ this._httpStopRequest = DevToolsUtils.makeInfallible(
+ this._httpStopRequest
+ ).bind(this);
+ this._serviceWorkerRequest = this._serviceWorkerRequest.bind(this);
+
+ this._throttleData = null;
+ this._throttler = null;
+}
+
+exports.NetworkObserver = NetworkObserver;
+
+NetworkObserver.prototype = {
+ filters: null,
+
+ httpTransactionCodes: {
+ 0x5001: "REQUEST_HEADER",
+ 0x5002: "REQUEST_BODY_SENT",
+ 0x5003: "RESPONSE_START",
+ 0x5004: "RESPONSE_HEADER",
+ 0x5005: "RESPONSE_COMPLETE",
+ 0x5006: "TRANSACTION_CLOSE",
+
+ 0x804b0003: "STATUS_RESOLVING",
+ 0x804b000b: "STATUS_RESOLVED",
+ 0x804b0007: "STATUS_CONNECTING_TO",
+ 0x804b0004: "STATUS_CONNECTED_TO",
+ 0x804b0005: "STATUS_SENDING_TO",
+ 0x804b000a: "STATUS_WAITING_FOR",
+ 0x804b0006: "STATUS_RECEIVING_FROM",
+ 0x804b000c: "STATUS_TLS_STARTING",
+ 0x804b000d: "STATUS_TLS_ENDING",
+ },
+
+ httpDownloadActivities: [
+ gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_START,
+ gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_HEADER,
+ gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_COMPLETE,
+ gActivityDistributor.ACTIVITY_SUBTYPE_TRANSACTION_CLOSE,
+ ],
+
+ // Network response bodies are piped through a buffer of the given size (in
+ // bytes).
+ responsePipeSegmentSize: null,
+
+ owner: null,
+
+ /**
+ * Whether to save the bodies of network requests and responses.
+ * @type boolean
+ */
+ saveRequestAndResponseBodies: true,
+
+ /**
+ * Object that holds the HTTP activity objects for ongoing requests.
+ */
+ openRequests: null,
+
+ /**
+ * Object that holds response headers coming from this._httpResponseExaminer.
+ */
+ openResponses: null,
+
+ /**
+ * The network monitor initializer.
+ */
+ init: function() {
+ this.responsePipeSegmentSize = Services.prefs.getIntPref(
+ "network.buffer.cache.size"
+ );
+ this.interceptedChannels = new WeakSet();
+
+ if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
+ gActivityDistributor.addObserver(this);
+ Services.obs.addObserver(
+ this._httpResponseExaminer,
+ "http-on-examine-response"
+ );
+ Services.obs.addObserver(
+ this._httpResponseExaminer,
+ "http-on-examine-cached-response"
+ );
+ Services.obs.addObserver(
+ this._httpModifyExaminer,
+ "http-on-modify-request"
+ );
+ Services.obs.addObserver(this._httpStopRequest, "http-on-stop-request");
+ } else {
+ Services.obs.addObserver(
+ this._httpFailedOpening,
+ "http-on-failed-opening-request"
+ );
+ }
+ // In child processes, only watch for service worker requests
+ // everything else only happens in the parent process
+ Services.obs.addObserver(
+ this._serviceWorkerRequest,
+ "service-worker-synthesized-response"
+ );
+ },
+
+ get throttleData() {
+ return this._throttleData;
+ },
+
+ set throttleData(value) {
+ this._throttleData = value;
+ // Clear out any existing throttlers
+ this._throttler = null;
+ },
+
+ _getThrottler: function() {
+ if (this.throttleData !== null && this._throttler === null) {
+ this._throttler = new NetworkThrottleManager(this.throttleData);
+ }
+ return this._throttler;
+ },
+
+ _serviceWorkerRequest: function(subject, topic, data) {
+ const channel = subject.QueryInterface(Ci.nsIHttpChannel);
+
+ if (!matchRequest(channel, this.filters)) {
+ return;
+ }
+
+ logPlatformEvent(topic, channel);
+
+ this.interceptedChannels.add(subject);
+
+ // Service workers never fire http-on-examine-cached-response, so fake one.
+ this._httpResponseExaminer(channel, "http-on-examine-cached-response");
+ },
+
+ /**
+ * Observes for http-on-failed-opening-request notification to catch any
+ * channels for which asyncOpen has synchronously failed. This is the only
+ * place to catch early security check failures.
+ */
+ _httpFailedOpening: function(subject, topic) {
+ if (
+ !this.owner ||
+ topic != "http-on-failed-opening-request" ||
+ !(subject instanceof Ci.nsIHttpChannel)
+ ) {
+ return;
+ }
+
+ const channel = subject.QueryInterface(Ci.nsIHttpChannel);
+ if (!matchRequest(channel, this.filters)) {
+ return;
+ }
+
+ logPlatformEvent(topic, channel);
+
+ // Ignore preload requests to avoid duplicity request entries in
+ // the Network panel. If a preload fails (for whatever reason)
+ // then the platform kicks off another 'real' request.
+ const type = channel.loadInfo.internalContentPolicyType;
+ if (
+ type == Ci.nsIContentPolicy.TYPE_INTERNAL_SCRIPT_PRELOAD ||
+ type == Ci.nsIContentPolicy.TYPE_INTERNAL_MODULE_PRELOAD ||
+ type == Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE_PRELOAD ||
+ type == Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET_PRELOAD ||
+ type == Ci.nsIContentPolicy.TYPE_INTERNAL_FONT_PRELOAD
+ ) {
+ return;
+ }
+
+ const blockedCode = channel.loadInfo.requestBlockingReason;
+ this._httpResponseExaminer(subject, topic, blockedCode);
+ },
+
+ _httpStopRequest: function(subject, topic) {
+ if (
+ !this.owner ||
+ topic != "http-on-stop-request" ||
+ !(subject instanceof Ci.nsIHttpChannel)
+ ) {
+ return;
+ }
+
+ const channel = subject.QueryInterface(Ci.nsIHttpChannel);
+ if (!matchRequest(channel, this.filters)) {
+ return;
+ }
+
+ logPlatformEvent(topic, channel);
+
+ let id;
+ let reason;
+
+ try {
+ const request = subject.QueryInterface(Ci.nsIHttpChannel);
+ const properties = request.QueryInterface(Ci.nsIPropertyBag);
+ reason = request.loadInfo.requestBlockingReason;
+ id = properties.getProperty("cancelledByExtension");
+
+ // WebExtensionPolicy is not available for workers
+ if (typeof WebExtensionPolicy !== "undefined") {
+ id = WebExtensionPolicy.getByID(id).name;
+ }
+ } catch (err) {
+ // "cancelledByExtension" doesn't have to be available.
+ }
+
+ const httpActivity = this.createOrGetActivityObject(channel);
+ const serverTimings = this._extractServerTimings(channel);
+ if (httpActivity.owner) {
+ // Try extracting server timings. Note that they will be sent to the client
+ // in the `_onTransactionClose` method together with network event timings.
+ httpActivity.owner.addServerTimings(serverTimings);
+ } else {
+ // If the owner isn't set we need to create the network event and send
+ // it to the client. This happens in case where:
+ // - the request has been blocked (e.g. CORS) and "http-on-stop-request" is the first notification.
+ // - the NetworkObserver is start *after* the request started and we only receive the http-stop notification,
+ // but that doesn't mean the request is blocked, so check for its status.
+ const { status } = channel;
+ if (status == 0) {
+ // Do not pass any blocked reason, as this request is just fine.
+ // Bug 1489217 - Prevent watching for this request response content,
+ // as this request is already running, this is too late to watch for it.
+ this._createNetworkEvent(subject, { inProgressRequest: true });
+ } else {
+ if (reason == 0) {
+ // If we get there, we have a non-zero status, but no clear blocking reason
+ // This is most likely a request that failed for some reason, so try to pass this reason
+ reason = getErrorCodeString(status);
+ }
+ this._createNetworkEvent(subject, {
+ blockedReason: reason,
+ blockingExtension: id,
+ });
+ }
+ }
+ },
+
+ /**
+ * Observe notifications for the http-on-examine-response topic, coming from
+ * the nsIObserverService.
+ *
+ * @private
+ * @param nsIHttpChannel subject
+ * @param string topic
+ * @returns void
+ */
+ _httpResponseExaminer: function(subject, topic, blockedReason) {
+ // The httpResponseExaminer is used to retrieve the uncached response
+ // headers. The data retrieved is stored in openResponses. The
+ // NetworkResponseListener is responsible with updating the httpActivity
+ // object with the data from the new object in openResponses.
+ if (
+ !this.owner ||
+ (topic != "http-on-examine-response" &&
+ topic != "http-on-examine-cached-response" &&
+ topic != "http-on-failed-opening-request") ||
+ !(subject instanceof Ci.nsIHttpChannel) ||
+ !(subject instanceof Ci.nsIClassifiedChannel)
+ ) {
+ return;
+ }
+
+ const blockedOrFailed = topic === "http-on-failed-opening-request";
+
+ subject.QueryInterface(Ci.nsIClassifiedChannel);
+ const channel = subject.QueryInterface(Ci.nsIHttpChannel);
+
+ if (!matchRequest(channel, this.filters)) {
+ return;
+ }
+
+ logPlatformEvent(
+ topic,
+ subject,
+ blockedOrFailed
+ ? "blockedOrFailed:" + blockedReason
+ : channel.responseStatus
+ );
+
+ const response = {
+ id: gSequenceId(),
+ channel: channel,
+ headers: [],
+ cookies: [],
+ };
+
+ const setCookieHeaders = [];
+
+ if (!blockedOrFailed) {
+ channel.visitOriginalResponseHeaders({
+ visitHeader: function(name, value) {
+ const lowerName = name.toLowerCase();
+ if (lowerName == "set-cookie") {
+ setCookieHeaders.push(value);
+ }
+ response.headers.push({ name: name, value: value });
+ },
+ });
+
+ if (!response.headers.length) {
+ // No need to continue.
+ return;
+ }
+
+ if (setCookieHeaders.length) {
+ response.cookies = setCookieHeaders.reduce((result, header) => {
+ const cookies = NetworkHelper.parseSetCookieHeader(header);
+ return result.concat(cookies);
+ }, []);
+ }
+ }
+
+ // Determine the HTTP version.
+ const httpVersionMaj = {};
+ const httpVersionMin = {};
+
+ channel.QueryInterface(Ci.nsIHttpChannelInternal);
+ if (!blockedOrFailed) {
+ channel.getResponseVersion(httpVersionMaj, httpVersionMin);
+
+ response.status = channel.responseStatus;
+ response.statusText = channel.responseStatusText;
+ if (httpVersionMaj.value > 1) {
+ response.httpVersion = "HTTP/" + httpVersionMaj.value;
+ } else {
+ response.httpVersion =
+ "HTTP/" + httpVersionMaj.value + "." + httpVersionMin.value;
+ }
+
+ this.openResponses.set(channel, response);
+ }
+
+ if (topic === "http-on-examine-cached-response") {
+ // Service worker requests emits cached-response notification on non-e10s,
+ // and we fake one on e10s.
+ const fromServiceWorker = this.interceptedChannels.has(channel);
+ this.interceptedChannels.delete(channel);
+
+ // If this is a cached response (which are also emitted by service worker requests),
+ // there never was a request event so we need to construct one here
+ // so the frontend gets all the expected events.
+ let httpActivity = this.createOrGetActivityObject(channel);
+ if (!httpActivity.owner) {
+ httpActivity = this._createNetworkEvent(channel, {
+ fromCache: !fromServiceWorker,
+ fromServiceWorker: fromServiceWorker,
+ });
+ }
+
+ // We need to send the request body to the frontend for
+ // the faked (cached/service worker request) event.
+ this._onRequestBodySent(httpActivity);
+ this._sendRequestBody(httpActivity);
+
+ httpActivity.owner.addResponseStart(
+ {
+ httpVersion: response.httpVersion,
+ remoteAddress: "",
+ remotePort: "",
+ status: response.status,
+ statusText: response.statusText,
+ headersSize: 0,
+ waitingTime: 0,
+ },
+ "",
+ true
+ );
+
+ // There also is never any timing events, so we can fire this
+ // event with zeroed out values.
+ const timings = this._setupHarTimings(httpActivity, true);
+
+ const serverTimings = this._extractServerTimings(httpActivity.channel);
+ httpActivity.owner.addEventTimings(
+ timings.total,
+ timings.timings,
+ timings.offsets,
+ serverTimings
+ );
+ } else if (topic === "http-on-failed-opening-request") {
+ this._createNetworkEvent(channel, { blockedReason });
+ }
+ },
+
+ /**
+ * Observe notifications for the http-on-modify-request topic, coming from
+ * the nsIObserverService.
+ *
+ * @private
+ * @param nsIHttpChannel aSubject
+ * @returns void
+ */
+ _httpModifyExaminer: function(subject) {
+ const throttler = this._getThrottler();
+ if (throttler) {
+ const channel = subject.QueryInterface(Ci.nsIHttpChannel);
+ if (matchRequest(channel, this.filters)) {
+ logPlatformEvent("http-on-modify-request", channel);
+
+ // Read any request body here, before it is throttled.
+ const httpActivity = this.createOrGetActivityObject(channel);
+ this._onRequestBodySent(httpActivity);
+ throttler.manageUpload(channel);
+ }
+ }
+ },
+
+ /**
+ * A helper function for observeActivity. This does whatever work
+ * is required by a particular http activity event. Arguments are
+ * the same as for observeActivity.
+ */
+ _dispatchActivity: function(
+ httpActivity,
+ channel,
+ activityType,
+ activitySubtype,
+ timestamp,
+ extraSizeData,
+ extraStringData
+ ) {
+ const transCodes = this.httpTransactionCodes;
+
+ // Store the time information for this activity subtype.
+ if (activitySubtype in transCodes) {
+ const stage = transCodes[activitySubtype];
+ if (stage in httpActivity.timings) {
+ httpActivity.timings[stage].last = timestamp;
+ } else {
+ httpActivity.timings[stage] = {
+ first: timestamp,
+ last: timestamp,
+ };
+ }
+ }
+
+ switch (activitySubtype) {
+ case gActivityDistributor.ACTIVITY_SUBTYPE_REQUEST_BODY_SENT:
+ this._onRequestBodySent(httpActivity);
+ this._sendRequestBody(httpActivity);
+ break;
+ case gActivityDistributor.ACTIVITY_SUBTYPE_RESPONSE_HEADER:
+ this._onResponseHeader(httpActivity, extraStringData);
+ break;
+ case gActivityDistributor.ACTIVITY_SUBTYPE_TRANSACTION_CLOSE:
+ this._onTransactionClose(httpActivity);
+ break;
+ default:
+ break;
+ }
+ },
+
+ getActivityTypeString(activityType, activitySubtype) {
+ if (
+ activityType === Ci.nsIHttpActivityObserver.ACTIVITY_TYPE_SOCKET_TRANSPORT
+ ) {
+ for (const name in Ci.nsISocketTransport) {
+ if (Ci.nsISocketTransport[name] === activitySubtype) {
+ return "SOCKET_TRANSPORT:" + name;
+ }
+ }
+ } else if (
+ activityType === Ci.nsIHttpActivityObserver.ACTIVITY_TYPE_HTTP_TRANSACTION
+ ) {
+ for (const name in Ci.nsIHttpActivityObserver) {
+ if (Ci.nsIHttpActivityObserver[name] === activitySubtype) {
+ return "HTTP_TRANSACTION:" + name.replace("ACTIVITY_SUBTYPE_", "");
+ }
+ }
+ }
+ return "unexpected-activity-types:" + activityType + ":" + activitySubtype;
+ },
+
+ /**
+ * Begin observing HTTP traffic that originates inside the current tab.
+ *
+ * @see https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIHttpActivityObserver
+ *
+ * @param nsIHttpChannel channel
+ * @param number activityType
+ * @param number activitySubtype
+ * @param number timestamp
+ * @param number extraSizeData
+ * @param string extraStringData
+ */
+ observeActivity: DevToolsUtils.makeInfallible(function(
+ channel,
+ activityType,
+ activitySubtype,
+ timestamp,
+ extraSizeData,
+ extraStringData
+ ) {
+ if (
+ !this.owner ||
+ (activityType != gActivityDistributor.ACTIVITY_TYPE_HTTP_TRANSACTION &&
+ activityType != gActivityDistributor.ACTIVITY_TYPE_SOCKET_TRANSPORT)
+ ) {
+ return;
+ }
+
+ if (
+ !(channel instanceof Ci.nsIHttpChannel) ||
+ !(channel instanceof Ci.nsIClassifiedChannel)
+ ) {
+ return;
+ }
+
+ channel = channel.QueryInterface(Ci.nsIHttpChannel);
+ channel = channel.QueryInterface(Ci.nsIClassifiedChannel);
+
+ if (DEBUG_PLATFORM_EVENTS) {
+ logPlatformEvent(
+ this.getActivityTypeString(activityType, activitySubtype),
+ channel
+ );
+ }
+
+ if (
+ activitySubtype == gActivityDistributor.ACTIVITY_SUBTYPE_REQUEST_HEADER
+ ) {
+ this._onRequestHeader(channel, timestamp, extraStringData);
+ return;
+ }
+
+ // Iterate over all currently ongoing requests. If channel can't
+ // be found within them, then exit this function.
+ const httpActivity = this._findActivityObject(channel);
+ if (!httpActivity) {
+ return;
+ }
+
+ // If we're throttling, we must not report events as they arrive
+ // from platform, but instead let the throttler emit the events
+ // after some time has elapsed.
+ if (
+ httpActivity.downloadThrottle &&
+ this.httpDownloadActivities.includes(activitySubtype)
+ ) {
+ const callback = this._dispatchActivity.bind(this);
+ httpActivity.downloadThrottle.addActivityCallback(
+ callback,
+ httpActivity,
+ channel,
+ activityType,
+ activitySubtype,
+ timestamp,
+ extraSizeData,
+ extraStringData
+ );
+ } else {
+ this._dispatchActivity(
+ httpActivity,
+ channel,
+ activityType,
+ activitySubtype,
+ timestamp,
+ extraSizeData,
+ extraStringData
+ );
+ }
+ }),
+
+ /**
+ * Craft the "event" object passed to the Watcher class in order
+ * to instantiate the NetworkEventActor.
+ *
+ * /!\ This method does many other important things:
+ * - Cancel requests blocked by DevTools
+ * - Fetch request headers/cookies
+ * - Set a few attributes on http activity object
+ * - Register listener to record response content
+ */
+ _createNetworkEvent: function(
+ channel,
+ {
+ timestamp,
+ extraStringData,
+ fromCache,
+ fromServiceWorker,
+ blockedReason,
+ blockingExtension,
+ inProgressRequest,
+ }
+ ) {
+ const httpActivity = this.createOrGetActivityObject(channel);
+
+ channel.QueryInterface(Ci.nsIPrivateBrowsingChannel);
+ httpActivity.private = channel.isChannelPrivate;
+
+ if (timestamp) {
+ httpActivity.timings.REQUEST_HEADER = {
+ first: timestamp,
+ last: timestamp,
+ };
+ }
+
+ const trackingProtectionLevel2Enabled = Services.prefs
+ .getStringPref("urlclassifier.trackingTable")
+ .includes("content-track-digest256");
+ const tpFlagsMask = trackingProtectionLevel2Enabled
+ ? ~Ci.nsIClassifiedChannel.CLASSIFIED_ANY_BASIC_TRACKING &
+ ~Ci.nsIClassifiedChannel.CLASSIFIED_ANY_STRICT_TRACKING
+ : ~Ci.nsIClassifiedChannel.CLASSIFIED_ANY_BASIC_TRACKING &
+ Ci.nsIClassifiedChannel.CLASSIFIED_ANY_STRICT_TRACKING;
+ const event = {};
+ event.method = channel.requestMethod;
+ event.channelId = channel.channelId;
+ event.url = channel.URI.spec;
+ event.private = httpActivity.private;
+ event.headersSize = 0;
+ event.startedDateTime = (timestamp
+ ? new Date(Math.round(timestamp / 1000))
+ : new Date()
+ ).toISOString();
+ event.fromCache = fromCache;
+ event.fromServiceWorker = fromServiceWorker;
+ // Only consider channels classified as level-1 to be trackers if our preferences
+ // would not cause such channels to be blocked in strict content blocking mode.
+ // Make sure the value produced here is a boolean.
+ if (channel instanceof Ci.nsIClassifiedChannel) {
+ event.isThirdPartyTrackingResource = !!(
+ channel.isThirdPartyTrackingResource() &&
+ (channel.thirdPartyClassificationFlags & tpFlagsMask) == 0
+ );
+ }
+ const referrerInfo = channel.referrerInfo;
+ event.referrerPolicy = referrerInfo
+ ? referrerInfo.getReferrerPolicyString()
+ : "";
+ httpActivity.fromServiceWorker = fromServiceWorker;
+
+ if (extraStringData) {
+ event.headersSize = extraStringData.length;
+ }
+
+ // Determine the cause and if this is an XHR request.
+ let causeType = Ci.nsIContentPolicy.TYPE_OTHER;
+ let causeUri = null;
+ let stacktrace;
+
+ if (channel.loadInfo) {
+ causeType = channel.loadInfo.externalContentPolicyType;
+ const { loadingPrincipal } = channel.loadInfo;
+ if (loadingPrincipal) {
+ causeUri = loadingPrincipal.spec;
+ }
+ }
+
+ // Show the right WebSocket URL in case of WS channel.
+ if (channel.notificationCallbacks) {
+ let wsChannel = null;
+ try {
+ wsChannel = channel.notificationCallbacks.QueryInterface(
+ Ci.nsIWebSocketChannel
+ );
+ } catch (e) {
+ // Not all channels implement nsIWebSocketChannel.
+ }
+ if (wsChannel) {
+ event.url = wsChannel.URI.spec;
+ event.serial = wsChannel.serial;
+ }
+ }
+
+ event.cause = {
+ type: causeTypeToString(
+ causeType,
+ channel.loadFlags,
+ channel.loadInfo.internalContentPolicyType
+ ),
+ loadingDocumentUri: causeUri,
+ stacktrace,
+ };
+
+ httpActivity.isXHR = event.isXHR =
+ causeType === Ci.nsIContentPolicy.TYPE_XMLHTTPREQUEST ||
+ causeType === Ci.nsIContentPolicy.TYPE_FETCH;
+
+ // Determine the HTTP version.
+ const httpVersionMaj = {};
+ const httpVersionMin = {};
+ channel.QueryInterface(Ci.nsIHttpChannelInternal);
+ channel.getRequestVersion(httpVersionMaj, httpVersionMin);
+
+ event.httpVersion =
+ "HTTP/" + httpVersionMaj.value + "." + httpVersionMin.value;
+
+ event.discardRequestBody = !this.saveRequestAndResponseBodies;
+ event.discardResponseBody = !this.saveRequestAndResponseBodies;
+
+ // Check the request URL with ones manually blocked by the user in DevTools.
+ // If it's meant to be blocked, we cancel the request and annotate the event.
+ if (!blockedReason) {
+ if (blockedReason !== undefined) {
+ // We were definitely blocked, but the blocker didn't say why.
+ event.blockedReason = "unknown";
+ } else if (
+ this.blockedURLs.some(url =>
+ wildcardToRegExp(url).test(httpActivity.url)
+ )
+ ) {
+ channel.cancel(Cr.NS_BINDING_ABORTED);
+ event.blockedReason = "devtools";
+ }
+ } else {
+ event.blockedReason = blockedReason;
+ if (blockingExtension) {
+ event.blockingExtension = blockingExtension;
+ }
+ }
+
+ httpActivity.owner = this.owner.onNetworkEvent(event);
+
+ // Bug 1489217 - Avoid watching for response content for blocked or in-progress requests
+ // as it can't be observed and would throw if we try.
+ const recordRequestContent = !event.blockedReason && !inProgressRequest;
+ if (recordRequestContent) {
+ this._setupResponseListener(httpActivity, fromCache);
+ }
+
+ this.fetchRequestHeadersAndCookies(channel, httpActivity, extraStringData);
+
+ return httpActivity;
+ },
+
+ /**
+ * For a given channel, with its associated http activity object,
+ * fetch the request's headers and cookies.
+ * This data is passed to the owner, i.e. the NetworkEventActor,
+ * so that the frontend can later fetch it via getRequestHeaders/getRequestCookies.
+ */
+ fetchRequestHeadersAndCookies(channel, httpActivity, extraStringData) {
+ const headers = [];
+ let cookies = [];
+ let cookieHeader = null;
+
+ // Copy the request header data.
+ channel.visitRequestHeaders({
+ visitHeader: function(name, value) {
+ if (name == "Cookie") {
+ cookieHeader = value;
+ }
+ headers.push({ name: name, value: value });
+ },
+ });
+
+ if (cookieHeader) {
+ cookies = NetworkHelper.parseCookieHeader(cookieHeader);
+ }
+
+ httpActivity.owner.addRequestHeaders(headers, extraStringData);
+ httpActivity.owner.addRequestCookies(cookies);
+ },
+
+ /**
+ * Handler for ACTIVITY_SUBTYPE_REQUEST_HEADER. When a request starts the
+ * headers are sent to the server. This method creates the |httpActivity|
+ * object where we store the request and response information that is
+ * collected through its lifetime.
+ *
+ * @private
+ * @param nsIHttpChannel channel
+ * @param number timestamp
+ * @param string extraStringData
+ * @return void
+ */
+ _onRequestHeader: function(channel, timestamp, extraStringData) {
+ if (!matchRequest(channel, this.filters)) {
+ return;
+ }
+
+ this._createNetworkEvent(channel, { timestamp, extraStringData });
+ },
+
+ /**
+ * Find an HTTP activity object for the channel.
+ *
+ * @param nsIHttpChannel channel
+ * The HTTP channel whose activity object we want to find.
+ * @return object
+ * The HTTP activity object, or null if it is not found.
+ */
+ _findActivityObject: function(channel) {
+ return this.openRequests.getChannelById(channel.channelId);
+ },
+
+ /**
+ * Find an existing HTTP activity object, or create a new one. This
+ * object is used for storing all the request and response
+ * information.
+ *
+ * This is a HAR-like object. Conformance to the spec is not guaranteed at
+ * this point.
+ *
+ * @see http://www.softwareishard.com/blog/har-12-spec
+ * @param nsIHttpChannel channel
+ * The HTTP channel for which the HTTP activity object is created.
+ * @return object
+ * The new HTTP activity object.
+ */
+ createOrGetActivityObject: function(channel) {
+ let httpActivity = this._findActivityObject(channel);
+ if (!httpActivity) {
+ const win = NetworkHelper.getWindowForRequest(channel);
+ const charset = win ? win.document.characterSet : null;
+
+ httpActivity = {
+ id: gSequenceId(),
+ channel: channel,
+ // see _onRequestBodySent()
+ charset: charset,
+ sentBody: null,
+ url: channel.URI.spec,
+ headersSize: null,
+ // needed for host specific security info
+ hostname: channel.URI.host,
+ discardRequestBody: !this.saveRequestAndResponseBodies,
+ discardResponseBody: !this.saveRequestAndResponseBodies,
+ // internal timing information, see observeActivity()
+ timings: {},
+ // see _onResponseHeader()
+ responseStatus: null,
+ // the activity owner which is notified when changes happen
+ owner: null,
+ };
+
+ this.openRequests.set(channel, httpActivity);
+ }
+
+ return httpActivity;
+ },
+
+ /**
+ * Block a request based on certain filtering options.
+ *
+ * Currently, an exact URL match is the only supported filter type.
+ */
+ blockRequest(filter) {
+ if (!filter || !filter.url) {
+ // In the future, there may be other types of filters, such as domain.
+ // For now, ignore anything other than URL.
+ return;
+ }
+
+ this.blockedURLs.push(filter.url);
+ },
+
+ /**
+ * Unblock a request based on certain filtering options.
+ *
+ * Currently, an exact URL match is the only supported filter type.
+ */
+ unblockRequest(filter) {
+ if (!filter || !filter.url) {
+ // In the future, there may be other types of filters, such as domain.
+ // For now, ignore anything other than URL.
+ return;
+ }
+
+ this.blockedURLs = this.blockedURLs.filter(url => url != filter.url);
+ },
+
+ /**
+ * Updates the list of blocked request strings
+ *
+ * This match will be a (String).includes match, not an exact URL match
+ */
+ setBlockedUrls(urls) {
+ this.blockedURLs = urls || [];
+ },
+
+ /**
+ * Returns a list of blocked requests
+ * Useful as blockedURLs is mutated by both console & netmonitor
+ */
+ getBlockedUrls() {
+ return this.blockedURLs;
+ },
+
+ /**
+ * Setup the network response listener for the given HTTP activity. The
+ * NetworkResponseListener is responsible for storing the response body.
+ *
+ * @private
+ * @param object httpActivity
+ * The HTTP activity object we are tracking.
+ */
+ _setupResponseListener: function(httpActivity, fromCache) {
+ const channel = httpActivity.channel;
+ channel.QueryInterface(Ci.nsITraceableChannel);
+
+ if (!fromCache) {
+ const throttler = this._getThrottler();
+ if (throttler) {
+ httpActivity.downloadThrottle = throttler.manage(channel);
+ }
+ }
+
+ // The response will be written into the outputStream of this pipe.
+ // This allows us to buffer the data we are receiving and read it
+ // asynchronously.
+ // Both ends of the pipe must be blocking.
+ const sink = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
+
+ // The streams need to be blocking because this is required by the
+ // stream tee.
+ sink.init(false, false, this.responsePipeSegmentSize, PR_UINT32_MAX, null);
+
+ // Add listener for the response body.
+ const newListener = new NetworkResponseListener(this, httpActivity);
+
+ // Remember the input stream, so it isn't released by GC.
+ newListener.inputStream = sink.inputStream;
+ newListener.sink = sink;
+
+ const tee = Cc["@mozilla.org/network/stream-listener-tee;1"].createInstance(
+ Ci.nsIStreamListenerTee
+ );
+
+ const originalListener = channel.setNewListener(tee);
+
+ tee.init(originalListener, sink.outputStream, newListener);
+ },
+
+ /**
+ * Handler for ACTIVITY_SUBTYPE_REQUEST_BODY_SENT. The request body is logged
+ * here.
+ *
+ * @private
+ * @param object httpActivity
+ * The HTTP activity object we are working with.
+ */
+ _onRequestBodySent: function(httpActivity) {
+ // Return early if we don't need the request body, or if we've
+ // already found it.
+ if (httpActivity.discardRequestBody || httpActivity.sentBody !== null) {
+ return;
+ }
+
+ let sentBody = NetworkHelper.readPostTextFromRequest(
+ httpActivity.channel,
+ httpActivity.charset
+ );
+
+ if (
+ sentBody !== null &&
+ this.window &&
+ httpActivity.url == this.window.location.href
+ ) {
+ // If the request URL is the same as the current page URL, then
+ // we can try to get the posted text from the page directly.
+ // This check is necessary as otherwise the
+ // NetworkHelper.readPostTextFromPageViaWebNav()
+ // function is called for image requests as well but these
+ // are not web pages and as such don't store the posted text
+ // in the cache of the webpage.
+ const webNav = this.window.docShell.QueryInterface(Ci.nsIWebNavigation);
+ sentBody = NetworkHelper.readPostTextFromPageViaWebNav(
+ webNav,
+ httpActivity.charset
+ );
+ }
+
+ if (sentBody !== null) {
+ httpActivity.sentBody = sentBody;
+ }
+ },
+
+ /**
+ * Handler for ACTIVITY_SUBTYPE_RESPONSE_HEADER. This method stores
+ * information about the response headers.
+ *
+ * @private
+ * @param object httpActivity
+ * The HTTP activity object we are working with.
+ * @param string extraStringData
+ * The uncached response headers.
+ */
+ _onResponseHeader: function(httpActivity, extraStringData) {
+ // extraStringData contains the uncached response headers. The first line
+ // contains the response status (e.g. HTTP/1.1 200 OK).
+ //
+ // Note: The response header is not saved here. Calling the
+ // channel.visitResponseHeaders() method at this point sometimes causes an
+ // NS_ERROR_NOT_AVAILABLE exception.
+ //
+ // We could parse extraStringData to get the headers and their values, but
+ // that is not trivial to do in an accurate manner. Hence, we save the
+ // response headers in this._httpResponseExaminer().
+
+ const headers = extraStringData.split(/\r\n|\n|\r/);
+ const statusLine = headers.shift();
+ const statusLineArray = statusLine.split(" ");
+
+ const response = {};
+ response.httpVersion = statusLineArray.shift();
+ response.remoteAddress = httpActivity.channel.remoteAddress;
+ response.remotePort = httpActivity.channel.remotePort;
+ response.status = statusLineArray.shift();
+ response.statusText = statusLineArray.join(" ");
+ response.headersSize = extraStringData.length;
+ response.waitingTime = this._convertTimeToMs(
+ this._getWaitTiming(httpActivity.timings)
+ );
+ // Mime type needs to be sent on response start for identifying an sse channel.
+ const contentType = headers.find(header => {
+ const lowerName = header.toLowerCase();
+ return lowerName.startsWith("content-type");
+ });
+
+ if (contentType) {
+ response.mimeType = contentType.slice("Content-Type: ".length);
+ }
+
+ httpActivity.responseStatus = response.status;
+ httpActivity.headersSize = response.headersSize;
+
+ // Discard the response body for known response statuses.
+ switch (parseInt(response.status, 10)) {
+ case HTTP_MOVED_PERMANENTLY:
+ case HTTP_FOUND:
+ case HTTP_SEE_OTHER:
+ case HTTP_TEMPORARY_REDIRECT:
+ httpActivity.discardResponseBody = true;
+ break;
+ }
+
+ response.discardResponseBody = httpActivity.discardResponseBody;
+
+ httpActivity.owner.addResponseStart(response, extraStringData);
+ },
+
+ /**
+ * Handler for ACTIVITY_SUBTYPE_TRANSACTION_CLOSE. This method updates the HAR
+ * timing information on the HTTP activity object and clears the request
+ * from the list of known open requests.
+ *
+ * @private
+ * @param object httpActivity
+ * The HTTP activity object we work with.
+ */
+ _onTransactionClose: function(httpActivity) {
+ if (httpActivity.owner) {
+ const result = this._setupHarTimings(httpActivity);
+ const serverTimings = this._extractServerTimings(httpActivity.channel);
+
+ httpActivity.owner.addEventTimings(
+ result.total,
+ result.timings,
+ result.offsets,
+ serverTimings
+ );
+ }
+ },
+
+ _getBlockedTiming: function(timings) {
+ if (timings.STATUS_RESOLVING && timings.STATUS_CONNECTING_TO) {
+ return timings.STATUS_RESOLVING.first - timings.REQUEST_HEADER.first;
+ } else if (timings.STATUS_SENDING_TO) {
+ return timings.STATUS_SENDING_TO.first - timings.REQUEST_HEADER.first;
+ }
+
+ return -1;
+ },
+
+ _getDnsTiming: function(timings) {
+ if (timings.STATUS_RESOLVING && timings.STATUS_RESOLVED) {
+ return timings.STATUS_RESOLVED.last - timings.STATUS_RESOLVING.first;
+ }
+
+ return -1;
+ },
+
+ _getConnectTiming: function(timings) {
+ if (timings.STATUS_CONNECTING_TO && timings.STATUS_CONNECTED_TO) {
+ return (
+ timings.STATUS_CONNECTED_TO.last - timings.STATUS_CONNECTING_TO.first
+ );
+ }
+
+ return -1;
+ },
+
+ _getReceiveTiming: function(timings) {
+ if (timings.RESPONSE_START && timings.RESPONSE_COMPLETE) {
+ return timings.RESPONSE_COMPLETE.last - timings.RESPONSE_START.first;
+ }
+
+ return -1;
+ },
+
+ _getWaitTiming: function(timings) {
+ if (timings.RESPONSE_START) {
+ return (
+ timings.RESPONSE_START.first -
+ (timings.REQUEST_BODY_SENT || timings.STATUS_SENDING_TO).last
+ );
+ }
+
+ return -1;
+ },
+
+ _getSslTiming: function(timings) {
+ if (timings.STATUS_TLS_STARTING && timings.STATUS_TLS_ENDING) {
+ return timings.STATUS_TLS_ENDING.last - timings.STATUS_TLS_STARTING.first;
+ }
+
+ return -1;
+ },
+
+ _getSendTiming: function(timings) {
+ if (timings.STATUS_SENDING_TO) {
+ return timings.STATUS_SENDING_TO.last - timings.STATUS_SENDING_TO.first;
+ } else if (timings.REQUEST_HEADER && timings.REQUEST_BODY_SENT) {
+ return timings.REQUEST_BODY_SENT.last - timings.REQUEST_HEADER.first;
+ }
+
+ return -1;
+ },
+
+ _getDataFromTimedChannel: function(timedChannel) {
+ const lookUpArr = [
+ "tcpConnectEndTime",
+ "connectStartTime",
+ "connectEndTime",
+ "secureConnectionStartTime",
+ "domainLookupEndTime",
+ "domainLookupStartTime",
+ ];
+
+ return lookUpArr.reduce((prev, prop) => {
+ const propName = prop + "Tc";
+ return {
+ ...prev,
+ [propName]: (() => {
+ if (!timedChannel) {
+ return 0;
+ }
+
+ const value = timedChannel[prop];
+
+ if (
+ value != 0 &&
+ timedChannel.asyncOpenTime &&
+ value < timedChannel.asyncOpenTime
+ ) {
+ return 0;
+ }
+
+ return value;
+ })(),
+ };
+ }, {});
+ },
+
+ _getSecureConnectionStartTimeInfo: function(timings) {
+ let secureConnectionStartTime = 0;
+ let secureConnectionStartTimeRelative = false;
+
+ if (timings.STATUS_TLS_STARTING && timings.STATUS_TLS_ENDING) {
+ if (timings.STATUS_CONNECTING_TO) {
+ secureConnectionStartTime =
+ timings.STATUS_TLS_STARTING.first -
+ timings.STATUS_CONNECTING_TO.first;
+ }
+
+ if (secureConnectionStartTime < 0) {
+ secureConnectionStartTime = 0;
+ }
+ secureConnectionStartTimeRelative = true;
+ }
+
+ return {
+ secureConnectionStartTime,
+ secureConnectionStartTimeRelative,
+ };
+ },
+
+ _getStartSendingTimeInfo: function(timings, connectStartTimeTc) {
+ let startSendingTime = 0;
+ let startSendingTimeRelative = false;
+
+ if (timings.STATUS_SENDING_TO) {
+ if (timings.STATUS_CONNECTING_TO) {
+ startSendingTime =
+ timings.STATUS_SENDING_TO.first - timings.STATUS_CONNECTING_TO.first;
+ startSendingTimeRelative = true;
+ } else if (connectStartTimeTc != 0) {
+ startSendingTime = timings.STATUS_SENDING_TO.first - connectStartTimeTc;
+ startSendingTimeRelative = true;
+ }
+
+ if (startSendingTime < 0) {
+ startSendingTime = 0;
+ }
+ }
+ return { startSendingTime, startSendingTimeRelative };
+ },
+
+ /**
+ * Update the HTTP activity object to include timing information as in the HAR
+ * spec. The HTTP activity object holds the raw timing information in
+ * |timings| - these are timings stored for each activity notification. The
+ * HAR timing information is constructed based on these lower level
+ * data.
+ *
+ * @param object httpActivity
+ * The HTTP activity object we are working with.
+ * @param boolean fromCache
+ * Indicates that the result was returned from the browser cache
+ * @return object
+ * This object holds two properties:
+ * - total - the total time for all of the request and response.
+ * - timings - the HAR timings object.
+ */
+
+ _setupHarTimings: function(httpActivity, fromCache) {
+ if (fromCache) {
+ // If it came from the browser cache, we have no timing
+ // information and these should all be 0
+ return {
+ total: 0,
+ timings: {
+ blocked: 0,
+ dns: 0,
+ ssl: 0,
+ connect: 0,
+ send: 0,
+ wait: 0,
+ receive: 0,
+ },
+ offsets: {
+ blocked: 0,
+ dns: 0,
+ ssl: 0,
+ connect: 0,
+ send: 0,
+ wait: 0,
+ receive: 0,
+ },
+ };
+ }
+
+ const timings = httpActivity.timings;
+ const harTimings = {};
+ // If the TCP Fast Open option or tls1.3 0RTT is used tls and data can
+ // be dispatched in SYN packet and not after tcp socket is connected.
+ // To demostrate this properly we will calculated TLS and send start time
+ // relative to CONNECTING_TO.
+ // Similary if 0RTT is used, data can be sent as soon as a TLS handshake
+ // starts.
+
+ harTimings.blocked = this._getBlockedTiming(timings);
+ // DNS timing information is available only in when the DNS record is not
+ // cached.
+ harTimings.dns = this._getDnsTiming(timings);
+ harTimings.connect = this._getConnectTiming(timings);
+ harTimings.ssl = this._getSslTiming(timings);
+
+ let {
+ secureConnectionStartTime,
+ secureConnectionStartTimeRelative,
+ } = this._getSecureConnectionStartTimeInfo(timings);
+
+ // sometimes the connection information events are attached to a speculative
+ // channel instead of this one, but necko might glue them back together in the
+ // nsITimedChannel interface used by Resource and Navigation Timing
+ const timedChannel = httpActivity.channel.QueryInterface(
+ Ci.nsITimedChannel
+ );
+
+ const {
+ tcpConnectEndTimeTc,
+ connectStartTimeTc,
+ connectEndTimeTc,
+ secureConnectionStartTimeTc,
+ domainLookupEndTimeTc,
+ domainLookupStartTimeTc,
+ } = this._getDataFromTimedChannel(timedChannel);
+
+ if (
+ harTimings.connect <= 0 &&
+ timedChannel &&
+ tcpConnectEndTimeTc != 0 &&
+ connectStartTimeTc != 0
+ ) {
+ harTimings.connect = tcpConnectEndTimeTc - connectStartTimeTc;
+ if (secureConnectionStartTimeTc != 0) {
+ harTimings.ssl = connectEndTimeTc - secureConnectionStartTimeTc;
+ secureConnectionStartTime =
+ secureConnectionStartTimeTc - connectStartTimeTc;
+ secureConnectionStartTimeRelative = true;
+ } else {
+ harTimings.ssl = -1;
+ }
+ } else if (
+ timedChannel &&
+ timings.STATUS_TLS_STARTING &&
+ secureConnectionStartTimeTc != 0
+ ) {
+ // It can happen that TCP Fast Open actually have not sent any data and
+ // timings.STATUS_TLS_STARTING.first value will be corrected in
+ // timedChannel.secureConnectionStartTime
+ if (secureConnectionStartTimeTc > timings.STATUS_TLS_STARTING.first) {
+ // TCP Fast Open actually did not sent any data.
+ harTimings.ssl = connectEndTimeTc - secureConnectionStartTimeTc;
+ secureConnectionStartTimeRelative = false;
+ }
+ }
+
+ if (
+ harTimings.dns <= 0 &&
+ timedChannel &&
+ domainLookupEndTimeTc != 0 &&
+ domainLookupStartTimeTc != 0
+ ) {
+ harTimings.dns = domainLookupEndTimeTc - domainLookupStartTimeTc;
+ }
+
+ harTimings.send = this._getSendTiming(timings);
+ harTimings.wait = this._getWaitTiming(timings);
+ harTimings.receive = this._getReceiveTiming(timings);
+ let {
+ startSendingTime,
+ startSendingTimeRelative,
+ } = this._getStartSendingTimeInfo(timings, connectStartTimeTc);
+
+ if (secureConnectionStartTimeRelative) {
+ const time = Math.max(Math.round(secureConnectionStartTime / 1000), -1);
+ secureConnectionStartTime = time;
+ }
+ if (startSendingTimeRelative) {
+ const time = Math.max(Math.round(startSendingTime / 1000), -1);
+ startSendingTime = time;
+ }
+
+ const ot = this._calculateOffsetAndTotalTime(
+ harTimings,
+ secureConnectionStartTime,
+ startSendingTimeRelative,
+ secureConnectionStartTimeRelative,
+ startSendingTime
+ );
+ return {
+ total: ot.total,
+ timings: harTimings,
+ offsets: ot.offsets,
+ };
+ },
+
+ _extractServerTimings: function(channel) {
+ if (!channel || !channel.serverTiming) {
+ return null;
+ }
+
+ const serverTimings = new Array(channel.serverTiming.length);
+
+ for (let i = 0; i < channel.serverTiming.length; ++i) {
+ const {
+ name,
+ duration,
+ description,
+ } = channel.serverTiming.queryElementAt(i, Ci.nsIServerTiming);
+ serverTimings[i] = { name, duration, description };
+ }
+
+ return serverTimings;
+ },
+
+ _convertTimeToMs: function(timing) {
+ return Math.max(Math.round(timing / 1000), -1);
+ },
+
+ _calculateOffsetAndTotalTime: function(
+ harTimings,
+ secureConnectionStartTime,
+ startSendingTimeRelative,
+ secureConnectionStartTimeRelative,
+ startSendingTime
+ ) {
+ let totalTime = 0;
+ for (const timing in harTimings) {
+ const time = this._convertTimeToMs(harTimings[timing]);
+ harTimings[timing] = time;
+ if (time > -1 && timing != "connect" && timing != "ssl") {
+ totalTime += time;
+ }
+ }
+
+ // connect, ssl and send times can be overlapped.
+ if (startSendingTimeRelative) {
+ totalTime += startSendingTime;
+ } else if (secureConnectionStartTimeRelative) {
+ totalTime += secureConnectionStartTime;
+ totalTime += harTimings.ssl;
+ }
+
+ const offsets = {};
+ offsets.blocked = 0;
+ offsets.dns = harTimings.blocked;
+ offsets.connect = offsets.dns + harTimings.dns;
+ if (secureConnectionStartTimeRelative) {
+ offsets.ssl = offsets.connect + secureConnectionStartTime;
+ } else {
+ offsets.ssl = offsets.connect + harTimings.connect;
+ }
+ if (startSendingTimeRelative) {
+ offsets.send = offsets.connect + startSendingTime;
+ if (!secureConnectionStartTimeRelative) {
+ offsets.ssl = offsets.send - harTimings.ssl;
+ }
+ } else {
+ offsets.send = offsets.ssl + harTimings.ssl;
+ }
+ offsets.wait = offsets.send + harTimings.send;
+ offsets.receive = offsets.wait + harTimings.wait;
+
+ return {
+ total: totalTime,
+ offsets: offsets,
+ };
+ },
+
+ _sendRequestBody: function(httpActivity) {
+ if (httpActivity.sentBody !== null) {
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.requestBodyLimit"
+ );
+ const size = httpActivity.sentBody.length;
+ if (size > limit && limit > 0) {
+ httpActivity.sentBody = httpActivity.sentBody.substr(0, limit);
+ }
+ httpActivity.owner.addRequestPostData({
+ text: httpActivity.sentBody,
+ size: size,
+ });
+ httpActivity.sentBody = null;
+ }
+ },
+
+ /**
+ * Suspend observer activity. This is called when the Network monitor actor stops
+ * listening.
+ */
+ destroy: function() {
+ if (Services.appinfo.processType != Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
+ gActivityDistributor.removeObserver(this);
+ Services.obs.removeObserver(
+ this._httpResponseExaminer,
+ "http-on-examine-response"
+ );
+ Services.obs.removeObserver(
+ this._httpResponseExaminer,
+ "http-on-examine-cached-response"
+ );
+ Services.obs.removeObserver(
+ this._httpModifyExaminer,
+ "http-on-modify-request"
+ );
+ Services.obs.removeObserver(
+ this._httpStopRequest,
+ "http-on-stop-request"
+ );
+ } else {
+ Services.obs.removeObserver(
+ this._httpFailedOpening,
+ "http-on-failed-opening-request"
+ );
+ }
+
+ Services.obs.removeObserver(
+ this._serviceWorkerRequest,
+ "service-worker-synthesized-response"
+ );
+
+ this.owner = null;
+ this.filters = null;
+ this._throttler = null;
+ },
+};
+
+function gSequenceId() {
+ return gSequenceId.n++;
+}
+gSequenceId.n = 1;
+
+/**
+ * Convert a nsIContentPolicy constant to a display string
+ */
+const LOAD_CAUSE_STRINGS = {
+ [Ci.nsIContentPolicy.TYPE_INVALID]: "invalid",
+ [Ci.nsIContentPolicy.TYPE_OTHER]: "other",
+ [Ci.nsIContentPolicy.TYPE_SCRIPT]: "script",
+ [Ci.nsIContentPolicy.TYPE_IMAGE]: "img",
+ [Ci.nsIContentPolicy.TYPE_STYLESHEET]: "stylesheet",
+ [Ci.nsIContentPolicy.TYPE_OBJECT]: "object",
+ [Ci.nsIContentPolicy.TYPE_DOCUMENT]: "document",
+ [Ci.nsIContentPolicy.TYPE_SUBDOCUMENT]: "subdocument",
+ [Ci.nsIContentPolicy.TYPE_PING]: "ping",
+ [Ci.nsIContentPolicy.TYPE_XMLHTTPREQUEST]: "xhr",
+ [Ci.nsIContentPolicy.TYPE_OBJECT_SUBREQUEST]: "objectSubdoc",
+ [Ci.nsIContentPolicy.TYPE_DTD]: "dtd",
+ [Ci.nsIContentPolicy.TYPE_FONT]: "font",
+ [Ci.nsIContentPolicy.TYPE_MEDIA]: "media",
+ [Ci.nsIContentPolicy.TYPE_WEBSOCKET]: "websocket",
+ [Ci.nsIContentPolicy.TYPE_CSP_REPORT]: "csp",
+ [Ci.nsIContentPolicy.TYPE_XSLT]: "xslt",
+ [Ci.nsIContentPolicy.TYPE_BEACON]: "beacon",
+ [Ci.nsIContentPolicy.TYPE_FETCH]: "fetch",
+ [Ci.nsIContentPolicy.TYPE_IMAGESET]: "imageset",
+ [Ci.nsIContentPolicy.TYPE_WEB_MANIFEST]: "webManifest",
+};
+
+function causeTypeToString(causeType, loadFlags, internalContentPolicyType) {
+ let prefix = "";
+ if (
+ (causeType == Ci.nsIContentPolicy.TYPE_IMAGESET ||
+ internalContentPolicyType == Ci.nsIContentPolicy.TYPE_INTERNAL_IMAGE) &&
+ loadFlags & Ci.nsIRequest.LOAD_BACKGROUND
+ ) {
+ prefix = "lazy-";
+ }
+
+ return prefix + LOAD_CAUSE_STRINGS[causeType] || "unknown";
+}
+
+function stringToCauseType(value) {
+ return Object.keys(LOAD_CAUSE_STRINGS).find(
+ key => LOAD_CAUSE_STRINGS[key] === value
+ );
+}
+exports.stringToCauseType = stringToCauseType;
diff --git a/devtools/server/actors/network-monitor/network-parent.js b/devtools/server/actors/network-monitor/network-parent.js
new file mode 100644
index 0000000000..37b5fd8623
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-parent.js
@@ -0,0 +1,146 @@
+/* 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";
+
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { networkParentSpec } = require("devtools/shared/specs/network-parent");
+
+const {
+ TYPES: { NETWORK_EVENT },
+ getResourceWatcher,
+} = require("devtools/server/actors/resources/index");
+
+/**
+ * This actor manages all network functionality running
+ * in the parent process.
+ *
+ * @constructor
+ *
+ */
+const NetworkParentActor = ActorClassWithSpec(networkParentSpec, {
+ initialize(watcherActor) {
+ this.watcherActor = watcherActor;
+ Actor.prototype.initialize.call(this, this.watcherActor.conn);
+ },
+
+ // Caches the throttling data so that on clearing the
+ // current network throttling it can be reset to the previous.
+ defaultThrottleData: undefined,
+
+ isEqual(next, current) {
+ // If both objects, check all entries
+ if (current && next && next == current) {
+ return Object.entries(current).every(([k, v]) => {
+ return next[k] === v;
+ });
+ }
+ return false;
+ },
+
+ destroy(conn) {
+ Actor.prototype.destroy.call(this, conn);
+ },
+
+ get networkEventWatcher() {
+ return getResourceWatcher(this.watcherActor, NETWORK_EVENT);
+ },
+
+ setNetworkThrottling(throttleData) {
+ if (!this.networkEventWatcher) {
+ throw new Error("Not listening for network events");
+ }
+
+ if (throttleData !== null) {
+ throttleData = {
+ latencyMean: throttleData.latency,
+ latencyMax: throttleData.latency,
+ downloadBPSMean: throttleData.downloadThroughput,
+ downloadBPSMax: throttleData.downloadThroughput,
+ uploadBPSMean: throttleData.uploadThroughput,
+ uploadBPSMax: throttleData.uploadThroughput,
+ };
+ }
+
+ const currentThrottleData = this.networkEventWatcher.getThrottleData();
+ if (this.isEqual(throttleData, currentThrottleData)) {
+ return;
+ }
+
+ if (this.defaultThrottleData === undefined) {
+ this.defaultThrottleData = currentThrottleData;
+ }
+
+ this.networkEventWatcher.setThrottleData(throttleData);
+ },
+
+ getNetworkThrottling() {
+ if (!this.networkEventWatcher) {
+ throw new Error("Not listening for network events");
+ }
+ const throttleData = this.networkEventWatcher.getThrottleData();
+ if (!throttleData) {
+ return null;
+ }
+ return {
+ downloadThroughput: throttleData.downloadBPSMax,
+ uploadThroughput: throttleData.uploadBPSMax,
+ latency: throttleData.latencyMax,
+ };
+ },
+
+ clearNetworkThrottling() {
+ if (this.defaultThrottleData !== undefined) {
+ this.setNetworkThrottling(this.defaultThrottleData);
+ }
+ },
+
+ /**
+ * Sets the urls to block.
+ *
+ * @param Array urls
+ * The response packet - stack trace.
+ */
+ setBlockedUrls(urls) {
+ if (!this.networkEventWatcher) {
+ throw new Error("Not listening for network events");
+ }
+ this.networkEventWatcher.setBlockedUrls(urls);
+ return {};
+ },
+
+ /**
+ * Returns the urls that are block
+ */
+ getBlockedUrls() {
+ if (!this.networkEventWatcher) {
+ throw new Error("Not listening for network events");
+ }
+ return this.networkEventWatcher.getBlockedUrls();
+ },
+
+ /**
+ * Blocks the requests based on the filters
+ * @param {Object} filters
+ */
+ blockRequest(filters) {
+ if (!this.networkEventWatcher) {
+ throw new Error("Not listening for network events");
+ }
+ this.networkEventWatcher.blockRequest(filters);
+ },
+
+ /**
+ * Unblocks requests based on the filters
+ * @param {Object} filters
+ */
+ unblockRequest(filters) {
+ if (!this.networkEventWatcher) {
+ throw new Error("Not listening for network events");
+ }
+ this.networkEventWatcher.unblockRequest(filters);
+ },
+});
+
+exports.NetworkParentActor = NetworkParentActor;
diff --git a/devtools/server/actors/network-monitor/network-response-listener.js b/devtools/server/actors/network-monitor/network-response-listener.js
new file mode 100644
index 0000000000..583b60cafb
--- /dev/null
+++ b/devtools/server/actors/network-monitor/network-response-listener.js
@@ -0,0 +1,588 @@
+/* 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";
+
+const { Cc, Ci, Cr, Cu, components: Components } = require("chrome");
+const ChromeUtils = require("ChromeUtils");
+const Services = require("Services");
+
+loader.lazyRequireGetter(
+ this,
+ "NetworkHelper",
+ "devtools/shared/webconsole/network-helper"
+);
+loader.lazyRequireGetter(
+ this,
+ "DevToolsUtils",
+ "devtools/shared/DevToolsUtils"
+);
+loader.lazyRequireGetter(
+ this,
+ "CacheEntry",
+ "devtools/shared/platform/cache-entry",
+ true
+);
+loader.lazyImporter(this, "NetUtil", "resource://gre/modules/NetUtil.jsm");
+loader.lazyGetter(
+ this,
+ "WebExtensionPolicy",
+ () => Cu.getGlobalForObject(Cu).WebExtensionPolicy
+);
+
+// Network logging
+
+/**
+ * The network response listener implements the nsIStreamListener and
+ * nsIRequestObserver interfaces. This is used within the NetworkObserver feature
+ * to get the response body of the request.
+ *
+ * The code is mostly based on code listings from:
+ *
+ * http://www.softwareishard.com/blog/firebug/
+ * nsitraceablechannel-intercept-http-traffic/
+ *
+ * @constructor
+ * @param object owner
+ * The response listener owner. This object needs to hold the
+ * |openResponses| object.
+ * @param object httpActivity
+ * HttpActivity object associated with this request. See NetworkObserver
+ * for more information.
+ */
+function NetworkResponseListener(owner, httpActivity) {
+ this.owner = owner;
+ this.receivedData = "";
+ this.httpActivity = httpActivity;
+ this.bodySize = 0;
+ // Indicates if the response had a size greater than response body limit.
+ this.truncated = false;
+ // Note that this is really only needed for the non-e10s case.
+ // See bug 1309523.
+ const channel = this.httpActivity.channel;
+ this._wrappedNotificationCallbacks = channel.notificationCallbacks;
+ channel.notificationCallbacks = this;
+}
+
+exports.NetworkResponseListener = NetworkResponseListener;
+
+NetworkResponseListener.prototype = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIStreamListener",
+ "nsIInputStreamCallback",
+ "nsIRequestObserver",
+ "nsIInterfaceRequestor",
+ ]),
+
+ // nsIInterfaceRequestor implementation
+
+ /**
+ * This object implements nsIProgressEventSink, but also needs to forward
+ * interface requests to the notification callbacks of other objects.
+ */
+ getInterface(iid) {
+ if (iid.equals(Ci.nsIProgressEventSink)) {
+ return this;
+ }
+ if (this._wrappedNotificationCallbacks) {
+ return this._wrappedNotificationCallbacks.getInterface(iid);
+ }
+ throw Components.Exception("", Cr.NS_ERROR_NO_INTERFACE);
+ },
+
+ /**
+ * Forward notifications for interfaces this object implements, in case other
+ * objects also implemented them.
+ */
+ _forwardNotification(iid, method, args) {
+ if (!this._wrappedNotificationCallbacks) {
+ return;
+ }
+ try {
+ const impl = this._wrappedNotificationCallbacks.getInterface(iid);
+ impl[method].apply(impl, args);
+ } catch (e) {
+ if (e.result != Cr.NS_ERROR_NO_INTERFACE) {
+ throw e;
+ }
+ }
+ },
+
+ /**
+ * This NetworkResponseListener tracks the NetworkObserver.openResponses object
+ * to find the associated uncached headers.
+ * @private
+ */
+ _foundOpenResponse: false,
+
+ /**
+ * If the channel already had notificationCallbacks, hold them here internally
+ * so that we can forward getInterface requests to that object.
+ */
+ _wrappedNotificationCallbacks: null,
+
+ /**
+ * The response listener owner.
+ */
+ owner: null,
+
+ /**
+ * The response will be written into the outputStream of this nsIPipe.
+ * Both ends of the pipe must be blocking.
+ */
+ sink: null,
+
+ /**
+ * The HttpActivity object associated with this response.
+ */
+ httpActivity: null,
+
+ /**
+ * Stores the received data as a string.
+ */
+ receivedData: null,
+
+ /**
+ * The uncompressed, decoded response body size.
+ */
+ bodySize: null,
+
+ /**
+ * Response size on the wire, potentially compressed / encoded.
+ */
+ transferredSize: null,
+
+ /**
+ * The nsIRequest we are started for.
+ */
+ request: null,
+
+ /**
+ * Set the async listener for the given nsIAsyncInputStream. This allows us to
+ * wait asynchronously for any data coming from the stream.
+ *
+ * @param nsIAsyncInputStream stream
+ * The input stream from where we are waiting for data to come in.
+ * @param nsIInputStreamCallback listener
+ * The input stream callback you want. This is an object that must have
+ * the onInputStreamReady() method. If the argument is null, then the
+ * current callback is removed.
+ * @return void
+ */
+ setAsyncListener: function(stream, listener) {
+ // Asynchronously wait for the stream to be readable or closed.
+ stream.asyncWait(listener, 0, 0, Services.tm.mainThread);
+ },
+
+ /**
+ * Stores the received data, if request/response body logging is enabled. It
+ * also does limit the number of stored bytes, based on the
+ * `devtools.netmonitor.responseBodyLimit` pref.
+ *
+ * Learn more about nsIStreamListener at:
+ * https://developer.mozilla.org/en/XPCOM_Interface_Reference/nsIStreamListener
+ *
+ * @param nsIRequest request
+ * @param nsISupports context
+ * @param nsIInputStream inputStream
+ * @param unsigned long offset
+ * @param unsigned long count
+ */
+ onDataAvailable: function(request, inputStream, offset, count) {
+ this._findOpenResponse();
+ const data = NetUtil.readInputStreamToString(inputStream, count);
+
+ this.bodySize += count;
+
+ if (!this.httpActivity.discardResponseBody) {
+ const limit = Services.prefs.getIntPref(
+ "devtools.netmonitor.responseBodyLimit"
+ );
+ if (this.receivedData.length <= limit || limit == 0) {
+ this.receivedData += NetworkHelper.convertToUnicode(
+ data,
+ request.contentCharset
+ );
+ }
+ if (this.receivedData.length > limit && limit > 0) {
+ this.receivedData = this.receivedData.substr(0, limit);
+ this.truncated = true;
+ }
+ }
+ },
+
+ /**
+ * See documentation at
+ * https://developer.mozilla.org/En/NsIRequestObserver
+ *
+ * @param nsIRequest request
+ * @param nsISupports context
+ */
+ onStartRequest: function(request) {
+ request = request.QueryInterface(Ci.nsIChannel);
+ // Converter will call this again, we should just ignore that.
+ if (this.request) {
+ return;
+ }
+
+ this.request = request;
+ this._getSecurityInfo();
+ this._findOpenResponse();
+ // We need to track the offset for the onDataAvailable calls where
+ // we pass the data from our pipe to the converter.
+ this.offset = 0;
+
+ const channel = this.request;
+
+ // Bug 1372115 - We should load bytecode cached requests from cache as the actual
+ // channel content is going to be optimized data that reflects platform internals
+ // instead of the content user expects (i.e. content served by HTTP server)
+ // Note that bytecode cached is one example, there may be wasm or other usecase in
+ // future.
+ let isOptimizedContent = false;
+ try {
+ if (channel instanceof Ci.nsICacheInfoChannel) {
+ isOptimizedContent = channel.alternativeDataType;
+ }
+ } catch (e) {
+ // Accessing `alternativeDataType` for some SW requests throws.
+ }
+ if (isOptimizedContent) {
+ let charset;
+ try {
+ charset = this.request.contentCharset;
+ } catch (e) {
+ // Accessing the charset sometimes throws NS_ERROR_NOT_AVAILABLE when
+ // reloading the page
+ }
+ if (!charset) {
+ charset = this.httpActivity.charset;
+ }
+ NetworkHelper.loadFromCache(
+ this.httpActivity.url,
+ charset,
+ this._onComplete.bind(this)
+ );
+ return;
+ }
+
+ // In the multi-process mode, the conversion happens on the child
+ // side while we can only monitor the channel on the parent
+ // side. If the content is gzipped, we have to unzip it
+ // ourself. For that we use the stream converter services. Do not
+ // do that for Service workers as they are run in the child
+ // process.
+ if (
+ !this.httpActivity.fromServiceWorker &&
+ channel instanceof Ci.nsIEncodedChannel &&
+ channel.contentEncodings &&
+ !channel.applyConversion
+ ) {
+ const encodingHeader = channel.getResponseHeader("Content-Encoding");
+ const scs = Cc["@mozilla.org/streamConverters;1"].getService(
+ Ci.nsIStreamConverterService
+ );
+ const encodings = encodingHeader.split(/\s*\t*,\s*\t*/);
+ let nextListener = this;
+ const acceptedEncodings = [
+ "gzip",
+ "deflate",
+ "br",
+ "x-gzip",
+ "x-deflate",
+ ];
+ for (const i in encodings) {
+ // There can be multiple conversions applied
+ const enc = encodings[i].toLowerCase();
+ if (acceptedEncodings.indexOf(enc) > -1) {
+ this.converter = scs.asyncConvertData(
+ enc,
+ "uncompressed",
+ nextListener,
+ null
+ );
+ nextListener = this.converter;
+ }
+ }
+ if (this.converter) {
+ this.converter.onStartRequest(this.request, null);
+ }
+ }
+ // Asynchronously wait for the data coming from the request.
+ this.setAsyncListener(this.sink.inputStream, this);
+ },
+
+ /**
+ * Parse security state of this request and report it to the client.
+ */
+ _getSecurityInfo: DevToolsUtils.makeInfallible(function() {
+ // Many properties of the securityInfo (e.g., the server certificate or HPKP
+ // status) are not available in the content process and can't be even touched safely,
+ // because their C++ getters trigger assertions. This function is called in content
+ // process for synthesized responses from service workers, in the parent otherwise.
+ if (Services.appinfo.processType == Ci.nsIXULRuntime.PROCESS_TYPE_CONTENT) {
+ return;
+ }
+
+ // Take the security information from the original nsIHTTPChannel instead of
+ // the nsIRequest received in onStartRequest. If response to this request
+ // was a redirect from http to https, the request object seems to contain
+ // security info for the https request after redirect.
+ const secinfo = this.httpActivity.channel.securityInfo;
+ if (secinfo) {
+ secinfo.QueryInterface(Ci.nsITransportSecurityInfo);
+ }
+ const info = NetworkHelper.parseSecurityInfo(secinfo, this.httpActivity);
+
+ let isRacing = false;
+ try {
+ const channel = this.httpActivity.channel;
+ if (channel instanceof Ci.nsICacheInfoChannel) {
+ isRacing = channel.isRacing();
+ }
+ } catch (err) {
+ // See the following bug for more details:
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1582589
+ }
+
+ this.httpActivity.owner.addSecurityInfo(info, isRacing);
+ }),
+
+ /**
+ * Fetches cache information from CacheEntry
+ * @private
+ */
+ _fetchCacheInformation: function() {
+ const httpActivity = this.httpActivity;
+ CacheEntry.getCacheEntry(this.request, descriptor => {
+ httpActivity.owner.addResponseCache({
+ responseCache: descriptor,
+ });
+ });
+ },
+
+ /**
+ * Handle the onStopRequest by closing the sink output stream.
+ *
+ * For more documentation about nsIRequestObserver go to:
+ * https://developer.mozilla.org/En/NsIRequestObserver
+ */
+ onStopRequest: function() {
+ // Bug 1429365: onStopRequest may be called after onComplete for resources loaded
+ // from bytecode cache.
+ if (!this.httpActivity) {
+ return;
+ }
+ this._findOpenResponse();
+ this.sink.outputStream.close();
+ },
+
+ // nsIProgressEventSink implementation
+
+ /**
+ * Handle progress event as data is transferred. This is used to record the
+ * size on the wire, which may be compressed / encoded.
+ */
+ onProgress: function(request, progress, progressMax) {
+ this.transferredSize = progress;
+ // Need to forward as well to keep things like Download Manager's progress
+ // bar working properly.
+ this._forwardNotification(Ci.nsIProgressEventSink, "onProgress", arguments);
+ },
+
+ onStatus: function() {
+ this._forwardNotification(Ci.nsIProgressEventSink, "onStatus", arguments);
+ },
+
+ /**
+ * Find the open response object associated to the current request. The
+ * NetworkObserver._httpResponseExaminer() method saves the response headers in
+ * NetworkObserver.openResponses. This method takes the data from the open
+ * response object and puts it into the HTTP activity object, then sends it to
+ * the remote Web Console instance.
+ *
+ * @private
+ */
+ _findOpenResponse: function() {
+ if (!this.owner || this._foundOpenResponse) {
+ return;
+ }
+
+ const channel = this.httpActivity.channel;
+ const openResponse = this.owner.openResponses.getChannelById(
+ channel.channelId
+ );
+
+ if (!openResponse) {
+ return;
+ }
+
+ this._foundOpenResponse = true;
+ this.owner.openResponses.delete(channel);
+
+ this.httpActivity.owner.addResponseHeaders(openResponse.headers);
+ this.httpActivity.owner.addResponseCookies(openResponse.cookies);
+ },
+
+ /**
+ * Clean up the response listener once the response input stream is closed.
+ * This is called from onStopRequest() or from onInputStreamReady() when the
+ * stream is closed.
+ * @return void
+ */
+ onStreamClose: function() {
+ if (!this.httpActivity) {
+ return;
+ }
+ // Remove our listener from the request input stream.
+ this.setAsyncListener(this.sink.inputStream, null);
+
+ this._findOpenResponse();
+ if (this.request.fromCache || this.httpActivity.responseStatus == 304) {
+ this._fetchCacheInformation();
+ }
+
+ if (!this.httpActivity.discardResponseBody && this.receivedData.length) {
+ this._onComplete(this.receivedData);
+ } else if (
+ !this.httpActivity.discardResponseBody &&
+ this.httpActivity.responseStatus == 304
+ ) {
+ // Response is cached, so we load it from cache.
+ let charset;
+ try {
+ charset = this.request.contentCharset;
+ } catch (e) {
+ // Accessing the charset sometimes throws NS_ERROR_NOT_AVAILABLE when
+ // reloading the page
+ }
+ if (!charset) {
+ charset = this.httpActivity.charset;
+ }
+ NetworkHelper.loadFromCache(
+ this.httpActivity.url,
+ charset,
+ this._onComplete.bind(this)
+ );
+ } else {
+ this._onComplete();
+ }
+ },
+
+ /**
+ * Handler for when the response completes. This function cleans up the
+ * response listener.
+ *
+ * @param string [data]
+ * Optional, the received data coming from the response listener or
+ * from the cache.
+ */
+ _onComplete: function(data) {
+ const response = {
+ mimeType: "",
+ text: data || "",
+ };
+
+ response.size = this.bodySize;
+ response.transferredSize =
+ this.transferredSize + this.httpActivity.headersSize;
+
+ try {
+ response.mimeType = this.request.contentType;
+ } catch (ex) {
+ // Ignore.
+ }
+
+ if (
+ !response.mimeType ||
+ !NetworkHelper.isTextMimeType(response.mimeType)
+ ) {
+ response.encoding = "base64";
+ try {
+ response.text = btoa(response.text);
+ } catch (err) {
+ // Ignore.
+ }
+ }
+
+ if (response.mimeType && this.request.contentCharset) {
+ response.mimeType += "; charset=" + this.request.contentCharset;
+ }
+
+ this.receivedData = "";
+
+ let id;
+ let reason;
+
+ try {
+ const properties = this.request.QueryInterface(Ci.nsIPropertyBag);
+ reason = this.request.loadInfo.requestBlockingReason;
+ id = properties.getProperty("cancelledByExtension");
+
+ // WebExtensionPolicy is not available for workers
+ if (typeof WebExtensionPolicy !== "undefined") {
+ id = WebExtensionPolicy.getByID(id).name;
+ }
+ } catch (err) {
+ // "cancelledByExtension" doesn't have to be available.
+ }
+
+ this.httpActivity.owner.addResponseContent(response, {
+ discardResponseBody: this.httpActivity.discardResponseBody,
+ truncated: this.truncated,
+ blockedReason: reason,
+ blockingExtension: id,
+ });
+
+ this._wrappedNotificationCallbacks = null;
+ this.httpActivity = null;
+ this.sink = null;
+ this.inputStream = null;
+ this.converter = null;
+ this.request = null;
+ this.owner = null;
+ },
+
+ /**
+ * The nsIInputStreamCallback for when the request input stream is ready -
+ * either it has more data or it is closed.
+ *
+ * @param nsIAsyncInputStream stream
+ * The sink input stream from which data is coming.
+ * @returns void
+ */
+ onInputStreamReady: function(stream) {
+ if (!(stream instanceof Ci.nsIAsyncInputStream) || !this.httpActivity) {
+ return;
+ }
+
+ let available = -1;
+ try {
+ // This may throw if the stream is closed normally or due to an error.
+ available = stream.available();
+ } catch (ex) {
+ // Ignore.
+ }
+
+ if (available != -1) {
+ if (available != 0) {
+ if (this.converter) {
+ this.converter.onDataAvailable(
+ this.request,
+ stream,
+ this.offset,
+ available
+ );
+ } else {
+ this.onDataAvailable(this.request, stream, this.offset, available);
+ }
+ }
+ this.offset += available;
+ this.setAsyncListener(stream, this);
+ } else {
+ this.onStreamClose();
+ this.offset = 0;
+ }
+ },
+};
diff --git a/devtools/server/actors/network-monitor/stack-trace-collector.js b/devtools/server/actors/network-monitor/stack-trace-collector.js
new file mode 100644
index 0000000000..91174812de
--- /dev/null
+++ b/devtools/server/actors/network-monitor/stack-trace-collector.js
@@ -0,0 +1,207 @@
+/* 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";
+
+const { Ci, components } = require("chrome");
+const Services = require("Services");
+
+loader.lazyRequireGetter(
+ this,
+ "ChannelEventSinkFactory",
+ "devtools/server/actors/network-monitor/channel-event-sink",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "matchRequest",
+ "devtools/server/actors/network-monitor/network-observer",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WebConsoleUtils",
+ "devtools/server/actors/webconsole/utils",
+ true
+);
+
+function StackTraceCollector(filters, netmonitors) {
+ this.filters = filters;
+ this.stacktracesById = new Map();
+ this.netmonitors = netmonitors;
+}
+
+StackTraceCollector.prototype = {
+ init() {
+ Services.obs.addObserver(this, "http-on-opening-request");
+ Services.obs.addObserver(this, "document-on-opening-request");
+ Services.obs.addObserver(this, "network-monitor-alternate-stack");
+ ChannelEventSinkFactory.getService().registerCollector(this);
+ this.onGetStack = this.onGetStack.bind(this);
+ for (const { messageManager } of this.netmonitors) {
+ messageManager.addMessageListener(
+ "debug:request-stack:request",
+ this.onGetStack
+ );
+ }
+ },
+
+ destroy() {
+ Services.obs.removeObserver(this, "http-on-opening-request");
+ Services.obs.removeObserver(this, "document-on-opening-request");
+ Services.obs.removeObserver(this, "network-monitor-alternate-stack");
+ ChannelEventSinkFactory.getService().unregisterCollector(this);
+ for (const { messageManager } of this.netmonitors) {
+ messageManager.removeMessageListener(
+ "debug:request-stack:request",
+ this.onGetStack
+ );
+ }
+ },
+
+ _saveStackTrace(id, stacktrace) {
+ if (this.stacktracesById.has(id)) {
+ // We can get up to two stack traces for the same channel: one each from
+ // the two observer topics we are listening to. Use the first stack trace
+ // which is specified, and ignore any later one.
+ return;
+ }
+ for (const { messageManager } of this.netmonitors) {
+ messageManager.sendAsyncMessage("debug:request-stack-available", {
+ channelId: id,
+ stacktrace: stacktrace && stacktrace.length > 0,
+ lastFrame:
+ stacktrace && stacktrace.length > 0 ? stacktrace[0] : undefined,
+ });
+ }
+ this.stacktracesById.set(id, stacktrace);
+ },
+
+ observe(subject, topic, data) {
+ let channel, id;
+ try {
+ // We need to QI nsIHttpChannel in order to load the interface's
+ // methods / attributes for later code that could assume we are dealing
+ // with a nsIHttpChannel.
+ channel = subject.QueryInterface(Ci.nsIHttpChannel);
+ id = channel.channelId;
+ } catch (e1) {
+ try {
+ channel = subject.QueryInterface(Ci.nsIIdentChannel);
+ id = channel.channelId;
+ } catch (e2) {
+ // WebSocketChannels do not have IDs, so use the URL. When a WebSocket is
+ // opened in a content process, a channel is created locally but the HTTP
+ // channel for the connection lives entirely in the parent process. When
+ // the server code running in the parent sees that HTTP channel, it will
+ // look for the creation stack using the websocket's URL.
+ try {
+ channel = subject.QueryInterface(Ci.nsIWebSocketChannel);
+ } catch (e3) {
+ // Channels which don't implement the above interfaces can appear here,
+ // such as nsIFileChannel. Ignore these channels.
+ return;
+ }
+ id = channel.URI.spec;
+ }
+ }
+
+ if (!matchRequest(channel, this.filters)) {
+ return;
+ }
+
+ const stacktrace = [];
+ switch (topic) {
+ case "http-on-opening-request":
+ case "document-on-opening-request": {
+ // The channel is being opened on the main thread, associate the current
+ // stack with it.
+ //
+ // Convert the nsIStackFrame XPCOM objects to a nice JSON that can be
+ // passed around through message managers etc.
+ let frame = components.stack;
+ if (frame?.caller) {
+ frame = frame.caller;
+ while (frame) {
+ stacktrace.push({
+ filename: frame.filename,
+ lineNumber: frame.lineNumber,
+ columnNumber: frame.columnNumber,
+ functionName: frame.name,
+ asyncCause: frame.asyncCause,
+ });
+ frame = frame.caller || frame.asyncCaller;
+ }
+ }
+ break;
+ }
+ case "network-monitor-alternate-stack": {
+ // An alternate stack trace is being specified for this channel.
+ // The topic data is the JSON for the saved frame stack we should use,
+ // so convert this into the expected format.
+ //
+ // This topic is used in the following cases:
+ //
+ // - The HTTP channel is opened asynchronously or on a different thread
+ // from the code which triggered its creation, in which case the stack
+ // from components.stack will be empty. The alternate stack will be
+ // for the point we want to associate with the channel.
+ //
+ // - The channel is not a nsIHttpChannel, and we will receive no
+ // opening request notification for it.
+ let frame = JSON.parse(data);
+ while (frame) {
+ stacktrace.push({
+ filename: frame.source,
+ lineNumber: frame.line,
+ columnNumber: frame.column,
+ functionName: frame.functionDisplayName,
+ asyncCause: frame.asyncCause,
+ });
+ frame = frame.parent || frame.asyncParent;
+ }
+ break;
+ }
+ default:
+ throw new Error("Unexpected observe() topic");
+ }
+
+ this._saveStackTrace(id, stacktrace);
+ },
+
+ // eslint-disable-next-line no-shadow
+ onChannelRedirect(oldChannel, newChannel, flags) {
+ // We can be called with any nsIChannel, but are interested only in HTTP channels
+ try {
+ oldChannel.QueryInterface(Ci.nsIHttpChannel);
+ newChannel.QueryInterface(Ci.nsIHttpChannel);
+ } catch (ex) {
+ return;
+ }
+
+ const oldId = oldChannel.channelId;
+ const stacktrace = this.stacktracesById.get(oldId);
+ if (stacktrace) {
+ this._saveStackTrace(newChannel.channelId, stacktrace);
+ }
+ },
+
+ getStackTrace(channelId) {
+ const trace = this.stacktracesById.get(channelId);
+ this.stacktracesById.delete(channelId);
+ return WebConsoleUtils.removeFramesAboveDebuggerEval(trace);
+ },
+
+ onGetStack(msg) {
+ const messageManager = msg.target;
+ const channelId = msg.data;
+ const stack = this.getStackTrace(channelId);
+ messageManager.sendAsyncMessage("debug:request-stack:response", {
+ channelId,
+ stack,
+ });
+ },
+};
+
+exports.StackTraceCollector = StackTraceCollector;
diff --git a/devtools/server/actors/network-monitor/utils/channel-map.js b/devtools/server/actors/network-monitor/utils/channel-map.js
new file mode 100644
index 0000000000..ba58f94850
--- /dev/null
+++ b/devtools/server/actors/network-monitor/utils/channel-map.js
@@ -0,0 +1,74 @@
+/* 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";
+
+/* global FinalizationRegistry, WeakRef */
+
+/**
+ * This object implements iterable weak map for HTTP channels tracked by
+ * the network observer.
+ *
+ * We can't use Map() for storing HTTP channel references since we don't
+ * know when we should remove the entry in it (it's wrong to do it in
+ * 'onTransactionClose' since it doesn't have to be the last platform
+ * notification for a given channel). We want the map to auto update
+ * when the channel is garbage collected.
+ *
+ * We can't use WeakMap() since searching for a value by the channel object
+ * isn't reliable (there might be different objects representing the same
+ * channel). We need to search by channel ID, but ID can't be used as key
+ * in WeakMap().
+ *
+ * So, this custom map solves aforementioned issues.
+ */
+class ChannelMap {
+ constructor() {
+ this.weakMap = new WeakMap();
+ this.refMap = new Map();
+ this.finalizationGroup = new FinalizationRegistry(ChannelMap.cleanup);
+ }
+
+ static cleanup({ refMap, id }) {
+ refMap.delete(id);
+ }
+
+ set(channel, value) {
+ const ref = new WeakRef(channel);
+ this.weakMap.set(channel, { value, ref });
+ this.refMap.set(channel.channelId, ref);
+ this.finalizationGroup.register(
+ channel,
+ {
+ refMap: this.refMap,
+ id: channel.channelId,
+ },
+ ref
+ );
+ }
+
+ getChannelById(channelId) {
+ const ref = this.refMap.get(channelId);
+ const key = ref ? ref.deref() : null;
+ if (!key) {
+ return null;
+ }
+ const channelInfo = this.weakMap.get(key);
+ return channelInfo ? channelInfo.value : null;
+ }
+
+ delete(channel) {
+ const entry = this.weakMap.get(channel);
+ if (!entry) {
+ return false;
+ }
+
+ this.weakMap.delete(channel);
+ this.refMap.delete(channel.channelId);
+ this.finalizationGroup.unregister(entry.ref);
+ return true;
+ }
+}
+
+exports.ChannelMap = ChannelMap;
diff --git a/devtools/server/actors/network-monitor/utils/error-codes.js b/devtools/server/actors/network-monitor/utils/error-codes.js
new file mode 100644
index 0000000000..5912eb99a1
--- /dev/null
+++ b/devtools/server/actors/network-monitor/utils/error-codes.js
@@ -0,0 +1,564 @@
+/* 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";
+
+/**
+ * Given a platform error code numer, return the name of it as a string
+ *
+ * @param {Number} code The error code to translate.
+ * @return {String} The error's name.
+ */
+function getErrorCodeString(code) {
+ for (const name in ErrorCodes) {
+ if (ErrorCodes[name] == code) {
+ return name;
+ }
+ }
+ return "NS_UNKNOWN_ERROR_CODE-" + code;
+}
+exports.getErrorCodeString = getErrorCodeString;
+
+// Copied from https://searchfox.org/mozilla-central/source/__GENERATED__/xpcom/base/ErrorList.h#297
+// Allows to stringify an error number
+const ErrorCodes = {
+ NS_OK: 0x0,
+ NS_ERROR_BASE: 0xc1f30000,
+ NS_ERROR_NOT_INITIALIZED: 0xc1f30001,
+ NS_ERROR_ALREADY_INITIALIZED: 0xc1f30002,
+ NS_ERROR_NOT_IMPLEMENTED: 0x80004001,
+ NS_NOINTERFACE: 0x80004002,
+ NS_ERROR_NO_INTERFACE: 0x80004002,
+ NS_ERROR_ABORT: 0x80004004,
+ NS_ERROR_FAILURE: 0x80004005,
+ NS_ERROR_UNEXPECTED: 0x8000ffff,
+ NS_ERROR_OUT_OF_MEMORY: 0x8007000e,
+ NS_ERROR_ILLEGAL_VALUE: 0x80070057,
+ NS_ERROR_INVALID_ARG: 0x80070057,
+ NS_ERROR_INVALID_POINTER: 0x80070057,
+ NS_ERROR_NULL_POINTER: 0x80070057,
+ NS_ERROR_NO_AGGREGATION: 0x80040110,
+ NS_ERROR_NOT_AVAILABLE: 0x80040111,
+ NS_ERROR_FACTORY_NOT_REGISTERED: 0x80040154,
+ NS_ERROR_FACTORY_REGISTER_AGAIN: 0x80040155,
+ NS_ERROR_FACTORY_NOT_LOADED: 0x800401f8,
+ NS_ERROR_FACTORY_NO_SIGNATURE_SUPPORT: 0xc1f30101,
+ NS_ERROR_FACTORY_EXISTS: 0xc1f30100,
+ NS_ERROR_CANNOT_CONVERT_DATA: 0x80460001,
+ NS_ERROR_OBJECT_IS_IMMUTABLE: 0x80460002,
+ NS_ERROR_LOSS_OF_SIGNIFICANT_DATA: 0x80460003,
+ NS_ERROR_NOT_SAME_THREAD: 0x80460004,
+ NS_ERROR_ILLEGAL_DURING_SHUTDOWN: 0x8046001e,
+ NS_ERROR_SERVICE_NOT_AVAILABLE: 0x80460016,
+ NS_SUCCESS_LOSS_OF_INSIGNIFICANT_DATA: 0x460001,
+ NS_SUCCESS_INTERRUPTED_TRAVERSE: 0x460002,
+ NS_BASE_STREAM_CLOSED: 0x80470002,
+ NS_BASE_STREAM_OSERROR: 0x80470003,
+ NS_BASE_STREAM_ILLEGAL_ARGS: 0x80470004,
+ NS_BASE_STREAM_NO_CONVERTER: 0x80470005,
+ NS_BASE_STREAM_BAD_CONVERSION: 0x80470006,
+ NS_BASE_STREAM_WOULD_BLOCK: 0x80470007,
+ NS_ERROR_GFX_PRINTER_NO_PRINTER_AVAILABLE: 0x80480001,
+ NS_ERROR_GFX_PRINTER_NAME_NOT_FOUND: 0x80480002,
+ NS_ERROR_GFX_PRINTER_COULD_NOT_OPEN_FILE: 0x80480003,
+ NS_ERROR_GFX_PRINTER_STARTDOC: 0x80480004,
+ NS_ERROR_GFX_PRINTER_ENDDOC: 0x80480005,
+ NS_ERROR_GFX_PRINTER_STARTPAGE: 0x80480006,
+ NS_ERROR_GFX_PRINTER_DOC_IS_BUSY: 0x80480007,
+ NS_ERROR_GFX_CMAP_MALFORMED: 0x80480033,
+ NS_SUCCESS_EVENT_CONSUMED: 0x490001,
+ NS_SUCCESS_EVENT_HANDLED_ASYNCHRONOUSLY: 0x490002,
+ NS_BINDING_SUCCEEDED: 0x0,
+ NS_BINDING_FAILED: 0x804b0001,
+ NS_BINDING_ABORTED: 0x804b0002,
+ NS_BINDING_REDIRECTED: 0x804b0003,
+ NS_BINDING_RETARGETED: 0x804b0004,
+ NS_ERROR_MALFORMED_URI: 0x804b000a,
+ NS_ERROR_IN_PROGRESS: 0x804b000f,
+ NS_ERROR_NO_CONTENT: 0x804b0011,
+ NS_ERROR_UNKNOWN_PROTOCOL: 0x804b0012,
+ NS_ERROR_INVALID_CONTENT_ENCODING: 0x804b001b,
+ NS_ERROR_CORRUPTED_CONTENT: 0x804b001d,
+ NS_ERROR_INVALID_SIGNATURE: 0x804b003a,
+ NS_ERROR_FIRST_HEADER_FIELD_COMPONENT_EMPTY: 0x804b0022,
+ NS_ERROR_ALREADY_OPENED: 0x804b0049,
+ NS_ERROR_ALREADY_CONNECTED: 0x804b000b,
+ NS_ERROR_NOT_CONNECTED: 0x804b000c,
+ NS_ERROR_CONNECTION_REFUSED: 0x804b000d,
+ NS_ERROR_NET_TIMEOUT: 0x804b000e,
+ NS_ERROR_OFFLINE: 0x804b0010,
+ NS_ERROR_PORT_ACCESS_NOT_ALLOWED: 0x804b0013,
+ NS_ERROR_NET_RESET: 0x804b0014,
+ NS_ERROR_NET_INTERRUPT: 0x804b0047,
+ NS_ERROR_PROXY_CONNECTION_REFUSED: 0x804b0048,
+ NS_ERROR_NET_PARTIAL_TRANSFER: 0x804b004c,
+ NS_ERROR_NET_INADEQUATE_SECURITY: 0x804b0052,
+ NS_ERROR_NET_HTTP2_SENT_GOAWAY: 0x804b0053,
+ NS_ERROR_NET_HTTP3_PROTOCOL_ERROR: 0x804b0054,
+ NS_ERROR_NOT_RESUMABLE: 0x804b0019,
+ NS_ERROR_REDIRECT_LOOP: 0x804b001f,
+ NS_ERROR_ENTITY_CHANGED: 0x804b0020,
+ NS_ERROR_UNSAFE_CONTENT_TYPE: 0x804b004a,
+ NS_ERROR_REMOTE_XUL: 0x804b004b,
+ NS_ERROR_LOAD_SHOWED_ERRORPAGE: 0x804b004d,
+ NS_ERROR_DOCSHELL_DYING: 0x804b004e,
+ NS_ERROR_FTP_LOGIN: 0x804b0015,
+ NS_ERROR_FTP_CWD: 0x804b0016,
+ NS_ERROR_FTP_PASV: 0x804b0017,
+ NS_ERROR_FTP_PWD: 0x804b0018,
+ NS_ERROR_FTP_LIST: 0x804b001c,
+ NS_ERROR_UNKNOWN_HOST: 0x804b001e,
+ NS_ERROR_DNS_LOOKUP_QUEUE_FULL: 0x804b0021,
+ NS_ERROR_UNKNOWN_PROXY_HOST: 0x804b002a,
+ NS_ERROR_DEFINITIVE_UNKNOWN_HOST: 0x804b002b,
+ NS_ERROR_UNKNOWN_SOCKET_TYPE: 0x804b0033,
+ NS_ERROR_SOCKET_CREATE_FAILED: 0x804b0034,
+ NS_ERROR_SOCKET_ADDRESS_NOT_SUPPORTED: 0x804b0035,
+ NS_ERROR_SOCKET_ADDRESS_IN_USE: 0x804b0036,
+ NS_ERROR_CACHE_KEY_NOT_FOUND: 0x804b003d,
+ NS_ERROR_CACHE_DATA_IS_STREAM: 0x804b003e,
+ NS_ERROR_CACHE_DATA_IS_NOT_STREAM: 0x804b003f,
+ NS_ERROR_CACHE_WAIT_FOR_VALIDATION: 0x804b0040,
+ NS_ERROR_CACHE_ENTRY_DOOMED: 0x804b0041,
+ NS_ERROR_CACHE_READ_ACCESS_DENIED: 0x804b0042,
+ NS_ERROR_CACHE_WRITE_ACCESS_DENIED: 0x804b0043,
+ NS_ERROR_CACHE_IN_USE: 0x804b0044,
+ NS_ERROR_DOCUMENT_NOT_CACHED: 0x804b0046,
+ NS_ERROR_INSUFFICIENT_DOMAIN_LEVELS: 0x804b0050,
+ NS_ERROR_HOST_IS_IP_ADDRESS: 0x804b0051,
+ NS_SUCCESS_ADOPTED_DATA: 0x4b005a,
+ NS_NET_STATUS_BEGIN_FTP_TRANSACTION: 0x4b001b,
+ NS_NET_STATUS_END_FTP_TRANSACTION: 0x4b001c,
+ NS_SUCCESS_AUTH_FINISHED: 0x4b0028,
+ NS_NET_STATUS_READING: 0x804b0008,
+ NS_NET_STATUS_WRITING: 0x804b0009,
+ NS_NET_STATUS_RESOLVING_HOST: 0x804b0003,
+ NS_NET_STATUS_RESOLVED_HOST: 0x804b000b,
+ NS_NET_STATUS_CONNECTING_TO: 0x804b0007,
+ NS_NET_STATUS_CONNECTED_TO: 0x804b0004,
+ NS_NET_STATUS_TLS_HANDSHAKE_STARTING: 0x804b000c,
+ NS_NET_STATUS_TLS_HANDSHAKE_ENDED: 0x804b000d,
+ NS_NET_STATUS_SENDING_TO: 0x804b0005,
+ NS_NET_STATUS_WAITING_FOR: 0x804b000a,
+ NS_NET_STATUS_RECEIVING_FROM: 0x804b0006,
+ NS_ERROR_INTERCEPTION_FAILED: 0x804b0064,
+ NS_ERROR_PROXY_CODE_BASE: 0x804b03e8,
+ NS_ERROR_PROXY_MULTIPLE_CHOICES: 0x804b0514,
+ NS_ERROR_PROXY_MOVED_PERMANENTLY: 0x804b0515,
+ NS_ERROR_PROXY_FOUND: 0x804b0516,
+ NS_ERROR_PROXY_SEE_OTHER: 0x804b0517,
+ NS_ERROR_PROXY_NOT_MODIFIED: 0x804b0518,
+ NS_ERROR_PROXY_TEMPORARY_REDIRECT: 0x804b051b,
+ NS_ERROR_PROXY_PERMANENT_REDIRECT: 0x804b051c,
+ NS_ERROR_PROXY_BAD_REQUEST: 0x804b0578,
+ NS_ERROR_PROXY_UNAUTHORIZED: 0x804b0579,
+ NS_ERROR_PROXY_PAYMENT_REQUIRED: 0x804b057a,
+ NS_ERROR_PROXY_FORBIDDEN: 0x804b057b,
+ NS_ERROR_PROXY_NOT_FOUND: 0x804b057c,
+ NS_ERROR_PROXY_METHOD_NOT_ALLOWED: 0x804b057d,
+ NS_ERROR_PROXY_NOT_ACCEPTABLE: 0x804b057e,
+ NS_ERROR_PROXY_AUTHENTICATION_FAILED: 0x804b057f,
+ NS_ERROR_PROXY_REQUEST_TIMEOUT: 0x804b0580,
+ NS_ERROR_PROXY_CONFLICT: 0x804b0581,
+ NS_ERROR_PROXY_GONE: 0x804b0582,
+ NS_ERROR_PROXY_LENGTH_REQUIRED: 0x804b0583,
+ NS_ERROR_PROXY_PRECONDITION_FAILED: 0x804b0584,
+ NS_ERROR_PROXY_REQUEST_ENTITY_TOO_LARGE: 0x804b0585,
+ NS_ERROR_PROXY_REQUEST_URI_TOO_LONG: 0x804b0586,
+ NS_ERROR_PROXY_UNSUPPORTED_MEDIA_TYPE: 0x804b0587,
+ NS_ERROR_PROXY_REQUESTED_RANGE_NOT_SATISFIABLE: 0x804b0588,
+ NS_ERROR_PROXY_EXPECTATION_FAILED: 0x804b0589,
+ NS_ERROR_PROXY_MISDIRECTED_REQUEST: 0x804b058d,
+ NS_ERROR_PROXY_TOO_EARLY: 0x804b0591,
+ NS_ERROR_PROXY_UPGRADE_REQUIRED: 0x804b0592,
+ NS_ERROR_PROXY_PRECONDITION_REQUIRED: 0x804b0594,
+ NS_ERROR_PROXY_TOO_MANY_REQUESTS: 0x804b0595,
+ NS_ERROR_PROXY_REQUEST_HEADER_FIELDS_TOO_LARGE: 0x804b0597,
+ NS_ERROR_PROXY_UNAVAILABLE_FOR_LEGAL_REASONS: 0x804b05ab,
+ NS_ERROR_PROXY_INTERNAL_SERVER_ERROR: 0x804b05dc,
+ NS_ERROR_PROXY_NOT_IMPLEMENTED: 0x804b05dd,
+ NS_ERROR_PROXY_BAD_GATEWAY: 0x804b05de,
+ NS_ERROR_PROXY_SERVICE_UNAVAILABLE: 0x804b05df,
+ NS_ERROR_PROXY_GATEWAY_TIMEOUT: 0x804b05e0,
+ NS_ERROR_PROXY_VERSION_NOT_SUPPORTED: 0x804b05e1,
+ NS_ERROR_PROXY_VARIANT_ALSO_NEGOTIATES: 0x804b05e2,
+ NS_ERROR_PROXY_NOT_EXTENDED: 0x804b05e6,
+ NS_ERROR_PROXY_NETWORK_AUTHENTICATION_REQUIRED: 0x804b05e7,
+ NS_ERROR_PLUGINS_PLUGINSNOTCHANGED: 0x804c03e8,
+ NS_ERROR_PLUGIN_DISABLED: 0x804c03e9,
+ NS_ERROR_PLUGIN_BLOCKLISTED: 0x804c03ea,
+ NS_ERROR_PLUGIN_TIME_RANGE_NOT_SUPPORTED: 0x804c03eb,
+ NS_ERROR_PLUGIN_CLICKTOPLAY: 0x804c03ec,
+ NS_OK_PARSE_SHEET: 0x4d0001,
+ NS_POSITION_BEFORE_TABLE: 0x4d0003,
+ NS_ERROR_HTMLPARSER_CONTINUE: 0x0,
+ NS_ERROR_HTMLPARSER_EOF: 0x804e03e8,
+ NS_ERROR_HTMLPARSER_UNKNOWN: 0x804e03e9,
+ NS_ERROR_HTMLPARSER_CANTPROPAGATE: 0x804e03ea,
+ NS_ERROR_HTMLPARSER_CONTEXTMISMATCH: 0x804e03eb,
+ NS_ERROR_HTMLPARSER_BADFILENAME: 0x804e03ec,
+ NS_ERROR_HTMLPARSER_BADURL: 0x804e03ed,
+ NS_ERROR_HTMLPARSER_INVALIDPARSERCONTEXT: 0x804e03ee,
+ NS_ERROR_HTMLPARSER_INTERRUPTED: 0x804e03ef,
+ NS_ERROR_HTMLPARSER_BLOCK: 0x804e03f0,
+ NS_ERROR_HTMLPARSER_BADTOKENIZER: 0x804e03f1,
+ NS_ERROR_HTMLPARSER_BADATTRIBUTE: 0x804e03f2,
+ NS_ERROR_HTMLPARSER_UNRESOLVEDDTD: 0x804e03f3,
+ NS_ERROR_HTMLPARSER_MISPLACEDTABLECONTENT: 0x804e03f4,
+ NS_ERROR_HTMLPARSER_BADDTD: 0x804e03f5,
+ NS_ERROR_HTMLPARSER_BADCONTEXT: 0x804e03f6,
+ NS_ERROR_HTMLPARSER_STOPPARSING: 0x804e03f7,
+ NS_ERROR_HTMLPARSER_UNTERMINATEDSTRINGLITERAL: 0x804e03f8,
+ NS_ERROR_HTMLPARSER_HIERARCHYTOODEEP: 0x804e03f9,
+ NS_ERROR_HTMLPARSER_FAKE_ENDTAG: 0x804e03fa,
+ NS_ERROR_HTMLPARSER_INVALID_COMMENT: 0x804e03fb,
+ NS_RDF_ASSERTION_ACCEPTED: 0x0,
+ NS_RDF_NO_VALUE: 0x4f0002,
+ NS_RDF_ASSERTION_REJECTED: 0x4f0003,
+ NS_RDF_STOP_VISIT: 0x4f0004,
+ NS_ERROR_UCONV_NOCONV: 0x80500001,
+ NS_ERROR_UDEC_ILLEGALINPUT: 0x8050000e,
+ NS_OK_HAD_REPLACEMENTS: 0x500003,
+ NS_OK_UDEC_MOREINPUT: 0x50000c,
+ NS_OK_UDEC_MOREOUTPUT: 0x50000d,
+ NS_OK_UENC_MOREOUTPUT: 0x500022,
+ NS_ERROR_UENC_NOMAPPING: 0x500023,
+ NS_ERROR_ILLEGAL_INPUT: 0x8050000e,
+ NS_ERROR_FILE_UNRECOGNIZED_PATH: 0x80520001,
+ NS_ERROR_FILE_UNRESOLVABLE_SYMLINK: 0x80520002,
+ NS_ERROR_FILE_EXECUTION_FAILED: 0x80520003,
+ NS_ERROR_FILE_UNKNOWN_TYPE: 0x80520004,
+ NS_ERROR_FILE_DESTINATION_NOT_DIR: 0x80520005,
+ NS_ERROR_FILE_TARGET_DOES_NOT_EXIST: 0x80520006,
+ NS_ERROR_FILE_COPY_OR_MOVE_FAILED: 0x80520007,
+ NS_ERROR_FILE_ALREADY_EXISTS: 0x80520008,
+ NS_ERROR_FILE_INVALID_PATH: 0x80520009,
+ NS_ERROR_FILE_DISK_FULL: 0x8052000a,
+ NS_ERROR_FILE_CORRUPTED: 0x8052000b,
+ NS_ERROR_FILE_NOT_DIRECTORY: 0x8052000c,
+ NS_ERROR_FILE_IS_DIRECTORY: 0x8052000d,
+ NS_ERROR_FILE_IS_LOCKED: 0x8052000e,
+ NS_ERROR_FILE_TOO_BIG: 0x8052000f,
+ NS_ERROR_FILE_NO_DEVICE_SPACE: 0x80520010,
+ NS_ERROR_FILE_NAME_TOO_LONG: 0x80520011,
+ NS_ERROR_FILE_NOT_FOUND: 0x80520012,
+ NS_ERROR_FILE_READ_ONLY: 0x80520013,
+ NS_ERROR_FILE_DIR_NOT_EMPTY: 0x80520014,
+ NS_ERROR_FILE_ACCESS_DENIED: 0x80520015,
+ NS_SUCCESS_FILE_DIRECTORY_EMPTY: 0x520001,
+ NS_SUCCESS_AGGREGATE_RESULT: 0x520002,
+ NS_ERROR_DOM_INDEX_SIZE_ERR: 0x80530001,
+ NS_ERROR_DOM_HIERARCHY_REQUEST_ERR: 0x80530003,
+ NS_ERROR_DOM_WRONG_DOCUMENT_ERR: 0x80530004,
+ NS_ERROR_DOM_INVALID_CHARACTER_ERR: 0x80530005,
+ NS_ERROR_DOM_NO_MODIFICATION_ALLOWED_ERR: 0x80530007,
+ NS_ERROR_DOM_NOT_FOUND_ERR: 0x80530008,
+ NS_ERROR_DOM_NOT_SUPPORTED_ERR: 0x80530009,
+ NS_ERROR_DOM_INUSE_ATTRIBUTE_ERR: 0x8053000a,
+ NS_ERROR_DOM_INVALID_STATE_ERR: 0x8053000b,
+ NS_ERROR_DOM_SYNTAX_ERR: 0x8053000c,
+ NS_ERROR_DOM_INVALID_MODIFICATION_ERR: 0x8053000d,
+ NS_ERROR_DOM_NAMESPACE_ERR: 0x8053000e,
+ NS_ERROR_DOM_INVALID_ACCESS_ERR: 0x8053000f,
+ NS_ERROR_DOM_TYPE_MISMATCH_ERR: 0x80530011,
+ NS_ERROR_DOM_SECURITY_ERR: 0x80530012,
+ NS_ERROR_DOM_NETWORK_ERR: 0x80530013,
+ NS_ERROR_DOM_ABORT_ERR: 0x80530014,
+ NS_ERROR_DOM_URL_MISMATCH_ERR: 0x80530015,
+ NS_ERROR_DOM_QUOTA_EXCEEDED_ERR: 0x80530016,
+ NS_ERROR_DOM_TIMEOUT_ERR: 0x80530017,
+ NS_ERROR_DOM_INVALID_NODE_TYPE_ERR: 0x80530018,
+ NS_ERROR_DOM_DATA_CLONE_ERR: 0x80530019,
+ NS_ERROR_DOM_ENCODING_NOT_SUPPORTED_ERR: 0x8053001c,
+ NS_ERROR_DOM_UNKNOWN_ERR: 0x8053001e,
+ NS_ERROR_DOM_DATA_ERR: 0x8053001f,
+ NS_ERROR_DOM_OPERATION_ERR: 0x80530020,
+ NS_ERROR_DOM_NOT_ALLOWED_ERR: 0x80530021,
+ NS_ERROR_DOM_SECMAN_ERR: 0x805303e9,
+ NS_ERROR_DOM_WRONG_TYPE_ERR: 0x805303ea,
+ NS_ERROR_DOM_NOT_OBJECT_ERR: 0x805303eb,
+ NS_ERROR_DOM_NOT_XPC_OBJECT_ERR: 0x805303ec,
+ NS_ERROR_DOM_NOT_NUMBER_ERR: 0x805303ed,
+ NS_ERROR_DOM_NOT_BOOLEAN_ERR: 0x805303ee,
+ NS_ERROR_DOM_NOT_FUNCTION_ERR: 0x805303ef,
+ NS_ERROR_DOM_TOO_FEW_PARAMETERS_ERR: 0x805303f0,
+ NS_ERROR_DOM_PROP_ACCESS_DENIED: 0x805303f2,
+ NS_ERROR_DOM_XPCONNECT_ACCESS_DENIED: 0x805303f3,
+ NS_ERROR_DOM_BAD_URI: 0x805303f4,
+ NS_ERROR_DOM_RETVAL_UNDEFINED: 0x805303f5,
+ NS_ERROR_UNCATCHABLE_EXCEPTION: 0x805303f7,
+ NS_ERROR_DOM_MALFORMED_URI: 0x805303f8,
+ NS_ERROR_DOM_INVALID_HEADER_NAME: 0x805303f9,
+ NS_ERROR_DOM_INVALID_STATE_XHR_HAS_INVALID_CONTEXT: 0x805303fa,
+ NS_ERROR_DOM_INVALID_STATE_XHR_MUST_BE_OPENED: 0x805303fb,
+ NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_SENDING: 0x805303fc,
+ NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_LOADING_OR_DONE_RESPONSE_TYPE: 0x805303fd,
+ NS_ERROR_DOM_INVALID_STATE_XHR_MUST_NOT_BE_LOADING_OR_DONE_OVERRIDE_MIME_TYPE: 0x8053040d,
+ NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSEXML: 0x805303fe,
+ NS_ERROR_DOM_INVALID_STATE_XHR_HAS_WRONG_RESPONSETYPE_FOR_RESPONSETEXT: 0x805303ff,
+ NS_ERROR_DOM_INVALID_STATE_XHR_CHUNKED_RESPONSETYPES_UNSUPPORTED_FOR_SYNC: 0x80530400,
+ NS_ERROR_DOM_INVALID_ACCESS_XHR_TIMEOUT_AND_RESPONSETYPE_UNSUPPORTED_FOR_SYNC: 0x80530401,
+ NS_ERROR_DOM_JS_DECODING_ERROR: 0x80530402,
+ NS_ERROR_DOM_IMAGE_INACTIVE_DOCUMENT: 0x80530403,
+ NS_ERROR_DOM_IMAGE_INVALID_REQUEST: 0x80530404,
+ NS_ERROR_DOM_IMAGE_BROKEN: 0x80530405,
+ NS_ERROR_DOM_INVALID_STATE_DOCUMENT_EXEC_COMMAND: 0x80530406,
+ NS_ERROR_DOM_INVALID_STATE_DOCUMENT_QUERY_COMMAND_ENABLED: 0x80530407,
+ NS_ERROR_DOM_INVALID_STATE_DOCUMENT_QUERY_COMMAND_INDETERM: 0x80530408,
+ NS_ERROR_DOM_INVALID_STATE_DOCUMENT_QUERY_COMMAND_STATE: 0x80530409,
+ NS_ERROR_DOM_INVALID_STATE_DOCUMENT_QUERY_COMMAND_SUPPORTED: 0x8053040a,
+ NS_ERROR_DOM_INVALID_STATE_DOCUMENT_QUERY_COMMAND_VALUE: 0x8053040b,
+ NS_ERROR_DOM_CORP_FAILED: 0x8053040c,
+ NS_SUCCESS_DOM_NO_OPERATION: 0x530001,
+ NS_SUCCESS_DOM_SCRIPT_EVALUATION_THREW: 0x530002,
+ NS_SUCCESS_DOM_SCRIPT_EVALUATION_THREW_UNCATCHABLE: 0x530003,
+ NS_IMAGELIB_ERROR_FAILURE: 0x80540005,
+ NS_IMAGELIB_ERROR_NO_DECODER: 0x80540006,
+ NS_IMAGELIB_ERROR_NOT_FINISHED: 0x80540007,
+ NS_IMAGELIB_ERROR_NO_ENCODER: 0x80540009,
+ NS_ERROR_EDITOR_DESTROYED: 0x80560001,
+ NS_ERROR_EDITOR_UNEXPECTED_DOM_TREE: 0x80560002,
+ NS_ERROR_EDITOR_ACTION_CANCELED: 0x80560003,
+ NS_SUCCESS_EDITOR_ELEMENT_NOT_FOUND: 0x560001,
+ NS_SUCCESS_EDITOR_FOUND_TARGET: 0x560002,
+ NS_ERROR_XPC_NOT_ENOUGH_ARGS: 0x80570001,
+ NS_ERROR_XPC_NEED_OUT_OBJECT: 0x80570002,
+ NS_ERROR_XPC_CANT_SET_OUT_VAL: 0x80570003,
+ NS_ERROR_XPC_NATIVE_RETURNED_FAILURE: 0x80570004,
+ NS_ERROR_XPC_CANT_GET_INTERFACE_INFO: 0x80570005,
+ NS_ERROR_XPC_CANT_GET_PARAM_IFACE_INFO: 0x80570006,
+ NS_ERROR_XPC_CANT_GET_METHOD_INFO: 0x80570007,
+ NS_ERROR_XPC_UNEXPECTED: 0x80570008,
+ NS_ERROR_XPC_BAD_CONVERT_JS: 0x80570009,
+ NS_ERROR_XPC_BAD_CONVERT_NATIVE: 0x8057000a,
+ NS_ERROR_XPC_BAD_CONVERT_JS_NULL_REF: 0x8057000b,
+ NS_ERROR_XPC_BAD_OP_ON_WN_PROTO: 0x8057000c,
+ NS_ERROR_XPC_CANT_CONVERT_WN_TO_FUN: 0x8057000d,
+ NS_ERROR_XPC_CANT_DEFINE_PROP_ON_WN: 0x8057000e,
+ NS_ERROR_XPC_CANT_WATCH_WN_STATIC: 0x8057000f,
+ NS_ERROR_XPC_CANT_EXPORT_WN_STATIC: 0x80570010,
+ NS_ERROR_XPC_SCRIPTABLE_CALL_FAILED: 0x80570011,
+ NS_ERROR_XPC_SCRIPTABLE_CTOR_FAILED: 0x80570012,
+ NS_ERROR_XPC_CANT_CALL_WO_SCRIPTABLE: 0x80570013,
+ NS_ERROR_XPC_CANT_CTOR_WO_SCRIPTABLE: 0x80570014,
+ NS_ERROR_XPC_CI_RETURNED_FAILURE: 0x80570015,
+ NS_ERROR_XPC_GS_RETURNED_FAILURE: 0x80570016,
+ NS_ERROR_XPC_BAD_CID: 0x80570017,
+ NS_ERROR_XPC_BAD_IID: 0x80570018,
+ NS_ERROR_XPC_CANT_CREATE_WN: 0x80570019,
+ NS_ERROR_XPC_JS_THREW_EXCEPTION: 0x8057001a,
+ NS_ERROR_XPC_JS_THREW_NATIVE_OBJECT: 0x8057001b,
+ NS_ERROR_XPC_JS_THREW_JS_OBJECT: 0x8057001c,
+ NS_ERROR_XPC_JS_THREW_NULL: 0x8057001d,
+ NS_ERROR_XPC_JS_THREW_STRING: 0x8057001e,
+ NS_ERROR_XPC_JS_THREW_NUMBER: 0x8057001f,
+ NS_ERROR_XPC_JAVASCRIPT_ERROR: 0x80570020,
+ NS_ERROR_XPC_JAVASCRIPT_ERROR_WITH_DETAILS: 0x80570021,
+ NS_ERROR_XPC_CANT_CONVERT_PRIMITIVE_TO_ARRAY: 0x80570022,
+ NS_ERROR_XPC_CANT_CONVERT_OBJECT_TO_ARRAY: 0x80570023,
+ NS_ERROR_XPC_NOT_ENOUGH_ELEMENTS_IN_ARRAY: 0x80570024,
+ NS_ERROR_XPC_CANT_GET_ARRAY_INFO: 0x80570025,
+ NS_ERROR_XPC_NOT_ENOUGH_CHARS_IN_STRING: 0x80570026,
+ NS_ERROR_XPC_SECURITY_MANAGER_VETO: 0x80570027,
+ NS_ERROR_XPC_INTERFACE_NOT_SCRIPTABLE: 0x80570028,
+ NS_ERROR_XPC_INTERFACE_NOT_FROM_NSISUPPORTS: 0x80570029,
+ NS_ERROR_XPC_CANT_GET_JSOBJECT_OF_DOM_OBJECT: 0x8057002a,
+ NS_ERROR_XPC_CANT_SET_READ_ONLY_CONSTANT: 0x8057002b,
+ NS_ERROR_XPC_CANT_SET_READ_ONLY_ATTRIBUTE: 0x8057002c,
+ NS_ERROR_XPC_CANT_SET_READ_ONLY_METHOD: 0x8057002d,
+ NS_ERROR_XPC_CANT_ADD_PROP_TO_WRAPPED_NATIVE: 0x8057002e,
+ NS_ERROR_XPC_CALL_TO_SCRIPTABLE_FAILED: 0x8057002f,
+ NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 0x80570030,
+ NS_ERROR_XPC_BAD_ID_STRING: 0x80570031,
+ NS_ERROR_XPC_BAD_INITIALIZER_NAME: 0x80570032,
+ NS_ERROR_XPC_HAS_BEEN_SHUTDOWN: 0x80570033,
+ NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN: 0x80570034,
+ NS_ERROR_XPC_BAD_CONVERT_JS_ZERO_ISNOT_NULL: 0x80570035,
+ NS_ERROR_LAUNCHED_CHILD_PROCESS: 0x805800c8,
+ NS_ERROR_SHOW_PROFILE_MANAGER: 0x805800c9,
+ NS_ERROR_DATABASE_CHANGED: 0x805800ca,
+ NS_ERROR_XFO_VIOLATION: 0x805a0060,
+ NS_ERROR_CSP_NAVIGATE_TO_VIOLATION: 0x805a0061,
+ NS_ERROR_CSP_FORM_ACTION_VIOLATION: 0x805a0062,
+ NS_ERROR_CSP_FRAME_ANCESTOR_VIOLATION: 0x805a0063,
+ NS_ERROR_SRI_CORRUPT: 0x805a00c8,
+ NS_ERROR_SRI_NOT_ELIGIBLE: 0x805a00c9,
+ NS_ERROR_SRI_UNEXPECTED_HASH_TYPE: 0x805a00ca,
+ NS_ERROR_SRI_IMPORT: 0x805a00cb,
+ NS_ERROR_CMS_VERIFY_NOT_SIGNED: 0x805a0400,
+ NS_ERROR_CMS_VERIFY_NO_CONTENT_INFO: 0x805a0401,
+ NS_ERROR_CMS_VERIFY_BAD_DIGEST: 0x805a0402,
+ NS_ERROR_CMS_VERIFY_NOCERT: 0x805a0404,
+ NS_ERROR_CMS_VERIFY_UNTRUSTED: 0x805a0405,
+ NS_ERROR_CMS_VERIFY_ERROR_UNVERIFIED: 0x805a0407,
+ NS_ERROR_CMS_VERIFY_ERROR_PROCESSING: 0x805a0408,
+ NS_ERROR_CMS_VERIFY_BAD_SIGNATURE: 0x805a0409,
+ NS_ERROR_CMS_VERIFY_DIGEST_MISMATCH: 0x805a040a,
+ NS_ERROR_CMS_VERIFY_UNKNOWN_ALGO: 0x805a040b,
+ NS_ERROR_CMS_VERIFY_UNSUPPORTED_ALGO: 0x805a040c,
+ NS_ERROR_CMS_VERIFY_MALFORMED_SIGNATURE: 0x805a040d,
+ NS_ERROR_CMS_VERIFY_HEADER_MISMATCH: 0x805a040e,
+ NS_ERROR_CMS_VERIFY_NOT_YET_ATTEMPTED: 0x805a040f,
+ NS_ERROR_CMS_VERIFY_CERT_WITHOUT_ADDRESS: 0x805a0410,
+ NS_ERROR_CMS_ENCRYPT_NO_BULK_ALG: 0x805a0420,
+ NS_ERROR_CMS_ENCRYPT_INCOMPLETE: 0x805a0421,
+ NS_ERROR_DOM_INVALID_EXPRESSION_ERR: 0x805b0033,
+ NS_ERROR_WONT_HANDLE_CONTENT: 0x805d0001,
+ NS_ERROR_MALWARE_URI: 0x805d001e,
+ NS_ERROR_PHISHING_URI: 0x805d001f,
+ NS_ERROR_TRACKING_URI: 0x805d0022,
+ NS_ERROR_UNWANTED_URI: 0x805d0023,
+ NS_ERROR_BLOCKED_URI: 0x805d0025,
+ NS_ERROR_HARMFUL_URI: 0x805d0026,
+ NS_ERROR_FINGERPRINTING_URI: 0x805d0029,
+ NS_ERROR_CRYPTOMINING_URI: 0x805d002a,
+ NS_ERROR_SOCIALTRACKING_URI: 0x805d002b,
+ NS_ERROR_SAVE_LINK_AS_TIMEOUT: 0x805d0020,
+ NS_ERROR_PARSED_DATA_CACHED: 0x805d0021,
+ NS_REFRESHURI_HEADER_FOUND: 0x5d0002,
+ NS_ERROR_CONTENT_BLOCKED: 0x805e0006,
+ NS_ERROR_CONTENT_BLOCKED_SHOW_ALT: 0x805e0007,
+ NS_PROPTABLE_PROP_NOT_THERE: 0x805e000a,
+ NS_ERROR_CONTENT_CRASHED: 0x805e0010,
+ NS_ERROR_FRAME_CRASHED: 0x805e000e,
+ NS_ERROR_BUILDID_MISMATCH: 0x805e0011,
+ NS_PROPTABLE_PROP_OVERWRITTEN: 0x5e000b,
+ NS_FINDBROADCASTER_NOT_FOUND: 0x5e000c,
+ NS_FINDBROADCASTER_FOUND: 0x5e000d,
+ NS_ERROR_XPATH_INVALID_ARG: 0x80070057,
+ NS_ERROR_XSLT_PARSE_FAILURE: 0x80600001,
+ NS_ERROR_XPATH_PARSE_FAILURE: 0x80600002,
+ NS_ERROR_XSLT_ALREADY_SET: 0x80600003,
+ NS_ERROR_XSLT_EXECUTION_FAILURE: 0x80600004,
+ NS_ERROR_XPATH_UNKNOWN_FUNCTION: 0x80600005,
+ NS_ERROR_XSLT_BAD_RECURSION: 0x80600006,
+ NS_ERROR_XSLT_BAD_VALUE: 0x80600007,
+ NS_ERROR_XSLT_NODESET_EXPECTED: 0x80600008,
+ NS_ERROR_XSLT_ABORTED: 0x80600009,
+ NS_ERROR_XSLT_NETWORK_ERROR: 0x8060000a,
+ NS_ERROR_XSLT_WRONG_MIME_TYPE: 0x8060000b,
+ NS_ERROR_XSLT_LOAD_RECURSION: 0x8060000c,
+ NS_ERROR_XPATH_BAD_ARGUMENT_COUNT: 0x8060000d,
+ NS_ERROR_XPATH_BAD_EXTENSION_FUNCTION: 0x8060000e,
+ NS_ERROR_XPATH_PAREN_EXPECTED: 0x8060000f,
+ NS_ERROR_XPATH_INVALID_AXIS: 0x80600010,
+ NS_ERROR_XPATH_NO_NODE_TYPE_TEST: 0x80600011,
+ NS_ERROR_XPATH_BRACKET_EXPECTED: 0x80600012,
+ NS_ERROR_XPATH_INVALID_VAR_NAME: 0x80600013,
+ NS_ERROR_XPATH_UNEXPECTED_END: 0x80600014,
+ NS_ERROR_XPATH_OPERATOR_EXPECTED: 0x80600015,
+ NS_ERROR_XPATH_UNCLOSED_LITERAL: 0x80600016,
+ NS_ERROR_XPATH_BAD_COLON: 0x80600017,
+ NS_ERROR_XPATH_BAD_BANG: 0x80600018,
+ NS_ERROR_XPATH_ILLEGAL_CHAR: 0x80600019,
+ NS_ERROR_XPATH_BINARY_EXPECTED: 0x8060001a,
+ NS_ERROR_XSLT_LOAD_BLOCKED_ERROR: 0x8060001b,
+ NS_ERROR_XPATH_INVALID_EXPRESSION_EVALUATED: 0x8060001c,
+ NS_ERROR_XPATH_UNBALANCED_CURLY_BRACE: 0x8060001d,
+ NS_ERROR_XSLT_BAD_NODE_NAME: 0x8060001e,
+ NS_ERROR_XSLT_VAR_ALREADY_SET: 0x8060001f,
+ NS_ERROR_XSLT_CALL_TO_KEY_NOT_ALLOWED: 0x80600020,
+ NS_XSLT_GET_NEW_HANDLER: 0x600001,
+ NS_ERROR_TRANSPORT_INIT: 0x80610001,
+ NS_ERROR_DUPLICATE_HANDLE: 0x80610002,
+ NS_ERROR_BRIDGE_OPEN_PARENT: 0x80610003,
+ NS_ERROR_BRIDGE_OPEN_CHILD: 0x80610004,
+ NS_ERROR_DOM_SVG_WRONG_TYPE_ERR: 0x80620000,
+ NS_ERROR_DOM_SVG_MATRIX_NOT_INVERTABLE: 0x80620002,
+ NS_ERROR_STORAGE_BUSY: 0x80630001,
+ NS_ERROR_STORAGE_IOERR: 0x80630002,
+ NS_ERROR_STORAGE_CONSTRAINT: 0x80630003,
+ NS_ERROR_DOM_FILE_NOT_FOUND_ERR: 0x80650000,
+ NS_ERROR_DOM_FILE_NOT_READABLE_ERR: 0x80650001,
+ NS_ERROR_DOM_INDEXEDDB_UNKNOWN_ERR: 0x80660001,
+ NS_ERROR_DOM_INDEXEDDB_NOT_FOUND_ERR: 0x80660003,
+ NS_ERROR_DOM_INDEXEDDB_CONSTRAINT_ERR: 0x80660004,
+ NS_ERROR_DOM_INDEXEDDB_DATA_ERR: 0x80660005,
+ NS_ERROR_DOM_INDEXEDDB_NOT_ALLOWED_ERR: 0x80660006,
+ NS_ERROR_DOM_INDEXEDDB_TRANSACTION_INACTIVE_ERR: 0x80660007,
+ NS_ERROR_DOM_INDEXEDDB_ABORT_ERR: 0x80660008,
+ NS_ERROR_DOM_INDEXEDDB_READ_ONLY_ERR: 0x80660009,
+ NS_ERROR_DOM_INDEXEDDB_TIMEOUT_ERR: 0x8066000a,
+ NS_ERROR_DOM_INDEXEDDB_QUOTA_ERR: 0x8066000b,
+ NS_ERROR_DOM_INDEXEDDB_VERSION_ERR: 0x8066000c,
+ NS_ERROR_DOM_INDEXEDDB_RECOVERABLE_ERR: 0x806603e9,
+ NS_ERROR_DOM_INDEXEDDB_KEY_ERR: 0x806603ea,
+ NS_ERROR_DOM_INDEXEDDB_RENAME_OBJECT_STORE_ERR: 0x806603eb,
+ NS_ERROR_DOM_INDEXEDDB_RENAME_INDEX_ERR: 0x806603ec,
+ NS_ERROR_DOM_FILEHANDLE_UNKNOWN_ERR: 0x80670001,
+ NS_ERROR_DOM_FILEHANDLE_NOT_ALLOWED_ERR: 0x80670002,
+ NS_ERROR_DOM_FILEHANDLE_INACTIVE_ERR: 0x80670003,
+ NS_ERROR_DOM_FILEHANDLE_ABORT_ERR: 0x80670004,
+ NS_ERROR_DOM_FILEHANDLE_READ_ONLY_ERR: 0x80670005,
+ NS_ERROR_DOM_FILEHANDLE_QUOTA_ERR: 0x80670006,
+ NS_ERROR_SIGNED_JAR_NOT_SIGNED: 0x80680001,
+ NS_ERROR_SIGNED_JAR_MODIFIED_ENTRY: 0x80680002,
+ NS_ERROR_SIGNED_JAR_UNSIGNED_ENTRY: 0x80680003,
+ NS_ERROR_SIGNED_JAR_ENTRY_MISSING: 0x80680004,
+ NS_ERROR_SIGNED_JAR_WRONG_SIGNATURE: 0x80680005,
+ NS_ERROR_SIGNED_JAR_ENTRY_TOO_LARGE: 0x80680006,
+ NS_ERROR_SIGNED_JAR_ENTRY_INVALID: 0x80680007,
+ NS_ERROR_SIGNED_JAR_MANIFEST_INVALID: 0x80680008,
+ NS_ERROR_DOM_FILESYSTEM_INVALID_PATH_ERR: 0x80690001,
+ NS_ERROR_DOM_FILESYSTEM_INVALID_MODIFICATION_ERR: 0x80690002,
+ NS_ERROR_DOM_FILESYSTEM_NO_MODIFICATION_ALLOWED_ERR: 0x80690003,
+ NS_ERROR_DOM_FILESYSTEM_PATH_EXISTS_ERR: 0x80690004,
+ NS_ERROR_DOM_FILESYSTEM_TYPE_MISMATCH_ERR: 0x80690005,
+ NS_ERROR_DOM_FILESYSTEM_UNKNOWN_ERR: 0x80690006,
+ NS_ERROR_SIGNED_APP_MANIFEST_INVALID: 0x806b0001,
+ NS_ERROR_DOM_ANIM_MISSING_PROPS_ERR: 0x806c0001,
+ NS_ERROR_DOM_PUSH_INVALID_REGISTRATION_ERR: 0x806d0001,
+ NS_ERROR_DOM_PUSH_DENIED_ERR: 0x806d0002,
+ NS_ERROR_DOM_PUSH_ABORT_ERR: 0x806d0003,
+ NS_ERROR_DOM_PUSH_SERVICE_UNREACHABLE: 0x806d0004,
+ NS_ERROR_DOM_PUSH_INVALID_KEY_ERR: 0x806d0005,
+ NS_ERROR_DOM_PUSH_MISMATCHED_KEY_ERR: 0x806d0006,
+ NS_ERROR_DOM_PUSH_GCM_DISABLED: 0x806d0007,
+ NS_ERROR_DOM_MEDIA_ABORT_ERR: 0x806e0001,
+ NS_ERROR_DOM_MEDIA_NOT_ALLOWED_ERR: 0x806e0002,
+ NS_ERROR_DOM_MEDIA_NOT_SUPPORTED_ERR: 0x806e0003,
+ NS_ERROR_DOM_MEDIA_DECODE_ERR: 0x806e0004,
+ NS_ERROR_DOM_MEDIA_FATAL_ERR: 0x806e0005,
+ NS_ERROR_DOM_MEDIA_METADATA_ERR: 0x806e0006,
+ NS_ERROR_DOM_MEDIA_OVERFLOW_ERR: 0x806e0007,
+ NS_ERROR_DOM_MEDIA_END_OF_STREAM: 0x806e0008,
+ NS_ERROR_DOM_MEDIA_WAITING_FOR_DATA: 0x806e0009,
+ NS_ERROR_DOM_MEDIA_CANCELED: 0x806e000a,
+ NS_ERROR_DOM_MEDIA_MEDIASINK_ERR: 0x806e000b,
+ NS_ERROR_DOM_MEDIA_DEMUXER_ERR: 0x806e000c,
+ NS_ERROR_DOM_MEDIA_CDM_ERR: 0x806e000d,
+ NS_ERROR_DOM_MEDIA_NEED_NEW_DECODER: 0x806e000e,
+ NS_ERROR_DOM_MEDIA_INITIALIZING_DECODER: 0x806e000f,
+ NS_ERROR_DOM_MEDIA_CUBEB_INITIALIZATION_ERR: 0x806e0065,
+ NS_ERROR_UC_UPDATE_UNKNOWN: 0x806f0001,
+ NS_ERROR_UC_UPDATE_DUPLICATE_PREFIX: 0x806f0002,
+ NS_ERROR_UC_UPDATE_INFINITE_LOOP: 0x806f0003,
+ NS_ERROR_UC_UPDATE_WRONG_REMOVAL_INDICES: 0x806f0004,
+ NS_ERROR_UC_UPDATE_CHECKSUM_MISMATCH: 0x806f0005,
+ NS_ERROR_UC_UPDATE_MISSING_CHECKSUM: 0x806f0006,
+ NS_ERROR_UC_UPDATE_SHUTDOWNING: 0x806f0007,
+ NS_ERROR_UC_UPDATE_TABLE_NOT_FOUND: 0x806f0008,
+ NS_ERROR_UC_UPDATE_BUILD_PREFIX_FAILURE: 0x806f0009,
+ NS_ERROR_UC_UPDATE_FAIL_TO_WRITE_DISK: 0x806f000a,
+ NS_ERROR_UC_UPDATE_UNEXPECTED_VERSION: 0x806f000b,
+ NS_ERROR_UC_PARSER_MISSING_PARAM: 0x806f000c,
+ NS_ERROR_UC_PARSER_DECODE_FAILURE: 0x806f000d,
+ NS_ERROR_UC_PARSER_UNKNOWN_THREAT: 0x806f000e,
+ NS_ERROR_UC_PARSER_MISSING_VALUE: 0x806f000f,
+ NS_ERROR_INTERNAL_ERRORRESULT_JS_EXCEPTION: 0x80700001,
+ NS_ERROR_INTERNAL_ERRORRESULT_DOMEXCEPTION: 0x80700002,
+ NS_ERROR_INTERNAL_ERRORRESULT_EXCEPTION_ON_JSCONTEXT: 0x80700003,
+ NS_ERROR_INTERNAL_ERRORRESULT_TYPEERROR: 0x80700004,
+ NS_ERROR_INTERNAL_ERRORRESULT_RANGEERROR: 0x80700005,
+ NS_ERROR_DOWNLOAD_COMPLETE: 0x80780001,
+ NS_ERROR_DOWNLOAD_NOT_PARTIAL: 0x80780002,
+ NS_ERROR_UNORM_MOREOUTPUT: 0x80780021,
+ NS_ERROR_DOCSHELL_REQUEST_REJECTED: 0x807803e9,
+ NS_ERROR_DOCUMENT_IS_PRINTMODE: 0x807807d1,
+ NS_SUCCESS_DONT_FIXUP: 0x780001,
+ NS_SUCCESS_RESTART_APP: 0x780001,
+ NS_ERROR_NOT_IN_TREE: 0x80780026,
+ NS_OK_NO_NAME_CLAUSE_HANDLED: 0x780022,
+ NS_ERROR_BLOCKED_BY_POLICY: 0x80780003,
+};
diff --git a/devtools/server/actors/network-monitor/utils/moz.build b/devtools/server/actors/network-monitor/utils/moz.build
new file mode 100644
index 0000000000..4293b5cbf8
--- /dev/null
+++ b/devtools/server/actors/network-monitor/utils/moz.build
@@ -0,0 +1,7 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules("channel-map.js", "error-codes.js", "wildcard-to-regexp.js")
diff --git a/devtools/server/actors/network-monitor/utils/wildcard-to-regexp.js b/devtools/server/actors/network-monitor/utils/wildcard-to-regexp.js
new file mode 100644
index 0000000000..95137564ad
--- /dev/null
+++ b/devtools/server/actors/network-monitor/utils/wildcard-to-regexp.js
@@ -0,0 +1,26 @@
+/* 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";
+
+/**
+ * Create a RegExp from a given wildcard string.
+ */
+function wildcardToRegExp(s) {
+ return new RegExp(
+ s
+ .split("*")
+ .map(regExpEscape)
+ .join(".*"),
+ "i"
+ );
+}
+exports.wildcardToRegExp = wildcardToRegExp;
+
+/**
+ * Escapes all special RegExp characters in the given string.
+ */
+const regExpEscape = s => {
+ return s.replace(/[|\\{}()[\]^$+*?.]/g, "\\$&");
+};
diff --git a/devtools/server/actors/network-monitor/websocket-actor.js b/devtools/server/actors/network-monitor/websocket-actor.js
new file mode 100644
index 0000000000..c4a0af0685
--- /dev/null
+++ b/devtools/server/actors/network-monitor/websocket-actor.js
@@ -0,0 +1,151 @@
+/* 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";
+
+const { Cc, Ci } = require("chrome");
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { webSocketSpec } = require("devtools/shared/specs/websocket");
+const { LongStringActor } = require("devtools/server/actors/string");
+
+const webSocketEventService = Cc[
+ "@mozilla.org/websocketevent/service;1"
+].getService(Ci.nsIWebSocketEventService);
+
+/**
+ * This actor intercepts WebSocket traffic for a specific window.
+ *
+ * @see devtools/shared/spec/websocket.js for documentation.
+ */
+const WebSocketActor = ActorClassWithSpec(webSocketSpec, {
+ initialize(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+
+ this.targetActor = targetActor;
+ this.innerWindowID = null;
+
+ // Each connection's webSocketSerialID is mapped to a httpChannelId
+ this.connections = new Map();
+
+ // Register for backend events.
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.targetActor.on("window-ready", this.onWindowReady);
+ },
+
+ onWindowReady({ isTopLevel }) {
+ if (isTopLevel) {
+ this.startListening();
+ }
+ },
+
+ destroy: function() {
+ this.targetActor.off("window-ready", this.onWindowReady);
+
+ this.stopListening();
+ Actor.prototype.destroy.call(this);
+ },
+
+ // Actor API
+
+ startListening: function() {
+ this.stopListening();
+ this.innerWindowID = this.targetActor.window.windowGlobalChild.innerWindowId;
+ webSocketEventService.addListener(this.innerWindowID, this);
+ },
+
+ stopListening() {
+ if (!this.innerWindowID) {
+ return;
+ }
+ if (webSocketEventService.hasListenerFor(this.innerWindowID)) {
+ webSocketEventService.removeListener(this.innerWindowID, this);
+ }
+
+ this.innerWindowID = null;
+ },
+
+ // nsIWebSocketEventService
+
+ webSocketCreated(webSocketSerialID, uri, protocols) {},
+
+ webSocketOpened(
+ webSocketSerialID,
+ effectiveURI,
+ protocols,
+ extensions,
+ httpChannelId
+ ) {
+ this.connections.set(webSocketSerialID, httpChannelId);
+
+ this.emit(
+ "serverWebSocketOpened",
+ httpChannelId,
+ effectiveURI,
+ protocols,
+ extensions
+ );
+ },
+
+ webSocketMessageAvailable(webSocketSerialID, data, messageType) {},
+
+ webSocketClosed(webSocketSerialID, wasClean, code, reason) {
+ const httpChannelId = this.connections.get(webSocketSerialID);
+
+ this.connections.delete(webSocketSerialID);
+ this.emit("serverWebSocketClosed", httpChannelId, wasClean, code, reason);
+ },
+
+ frameReceived(webSocketSerialID, frame) {
+ const httpChannelId = this.connections.get(webSocketSerialID);
+
+ if (!httpChannelId) {
+ return;
+ }
+
+ let payload = frame.payload;
+ payload = new LongStringActor(this.conn, payload);
+ this.manage(payload);
+ payload = payload.form();
+
+ this.emit("serverFrameReceived", httpChannelId, {
+ type: "received",
+ payload,
+ timeStamp: frame.timeStamp,
+ finBit: frame.finBit,
+ rsvBit1: frame.rsvBit1,
+ rsvBit2: frame.rsvBit2,
+ rsvBit3: frame.rsvBit3,
+ opCode: frame.opCode,
+ mask: frame.mask,
+ maskBit: frame.maskBit,
+ });
+ },
+
+ frameSent(webSocketSerialID, frame) {
+ const httpChannelId = this.connections.get(webSocketSerialID);
+
+ if (!httpChannelId) {
+ return;
+ }
+
+ let payload = new LongStringActor(this.conn, frame.payload);
+ this.manage(payload);
+ payload = payload.form();
+
+ this.emit("serverFrameSent", httpChannelId, {
+ type: "sent",
+ payload,
+ timeStamp: frame.timeStamp,
+ finBit: frame.finBit,
+ rsvBit1: frame.rsvBit1,
+ rsvBit2: frame.rsvBit2,
+ rsvBit3: frame.rsvBit3,
+ opCode: frame.opCode,
+ mask: frame.mask,
+ maskBit: frame.maskBit,
+ });
+ },
+});
+
+exports.WebSocketActor = WebSocketActor;
diff --git a/devtools/server/actors/object.js b/devtools/server/actors/object.js
new file mode 100644
index 0000000000..55dac64275
--- /dev/null
+++ b/devtools/server/actors/object.js
@@ -0,0 +1,810 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const { assert } = DevToolsUtils;
+
+const protocol = require("devtools/shared/protocol");
+const { objectSpec } = require("devtools/shared/specs/object");
+
+loader.lazyRequireGetter(
+ this,
+ "PropertyIteratorActor",
+ "devtools/server/actors/object/property-iterator",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "SymbolIteratorActor",
+ "devtools/server/actors/object/symbol-iterator",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "previewers",
+ "devtools/server/actors/object/previewers"
+);
+loader.lazyRequireGetter(
+ this,
+ "stringify",
+ "devtools/server/actors/object/stringifiers"
+);
+
+// ContentDOMReference requires ChromeUtils, which isn't available in worker context.
+if (!isWorker) {
+ loader.lazyRequireGetter(
+ this,
+ "ContentDOMReference",
+ "resource://gre/modules/ContentDOMReference.jsm",
+ true
+ );
+}
+
+const {
+ getArrayLength,
+ getPromiseState,
+ getStorageLength,
+ isArray,
+ isStorage,
+ isTypedArray,
+} = require("devtools/server/actors/object/utils");
+
+const proto = {
+ /**
+ * Creates an actor for the specified object.
+ *
+ * @param obj Debugger.Object
+ * The debuggee object.
+ * @param Object
+ * A collection of abstract methods that are implemented by the caller.
+ * ObjectActor requires the following functions to be implemented by
+ * the caller:
+ * - createValueGrip
+ * Creates a value grip for the given object
+ * - createEnvironmentActor
+ * Creates and return an environment actor
+ * - getGripDepth
+ * An actor's grip depth getter
+ * - incrementGripDepth
+ * Increment the actor's grip depth
+ * - decrementGripDepth
+ * Decrement the actor's grip depth
+ */
+ initialize(
+ obj,
+ {
+ thread,
+ createValueGrip: createValueGripHook,
+ createEnvironmentActor,
+ getGripDepth,
+ incrementGripDepth,
+ decrementGripDepth,
+ },
+ conn
+ ) {
+ assert(
+ !obj.optimizedOut,
+ "Should not create object actors for optimized out values!"
+ );
+ protocol.Actor.prototype.initialize.call(this, conn);
+
+ this.conn = conn;
+ this.obj = obj;
+ this.thread = thread;
+ this.hooks = {
+ createValueGrip: createValueGripHook,
+ createEnvironmentActor,
+ getGripDepth,
+ incrementGripDepth,
+ decrementGripDepth,
+ };
+ },
+
+ rawValue: function() {
+ return this.obj.unsafeDereference();
+ },
+
+ addWatchpoint(property, label, watchpointType) {
+ this.thread.addWatchpoint(this, { property, label, watchpointType });
+ },
+
+ removeWatchpoint(property) {
+ this.thread.removeWatchpoint(this, property);
+ },
+
+ removeWatchpoints() {
+ this.thread.removeWatchpoint(this);
+ },
+
+ /**
+ * Returns a grip for this actor for returning in a protocol message.
+ */
+ form: function() {
+ const g = {
+ type: "object",
+ actor: this.actorID,
+ };
+
+ const unwrapped = DevToolsUtils.unwrap(this.obj);
+ if (unwrapped === undefined) {
+ // Objects belonging to an invisible-to-debugger compartment might be proxies,
+ // so just in case they shouldn't be accessed.
+ g.class = "InvisibleToDebugger: " + this.obj.class;
+ return g;
+ }
+
+ if (unwrapped?.isProxy) {
+ // Proxy objects can run traps when accessed, so just create a preview with
+ // the target and the handler.
+ g.class = "Proxy";
+ this.hooks.incrementGripDepth();
+ previewers.Proxy[0](this, g, null);
+ this.hooks.decrementGripDepth();
+ return g;
+ }
+
+ const ownPropertyLength = this._getOwnPropertyLength();
+
+ Object.assign(g, {
+ // If the debuggee does not subsume the object's compartment, most properties won't
+ // be accessible. Cross-orgin Window and Location objects might expose some, though.
+ // Change the displayed class, but when creating the preview use the original one.
+ class: unwrapped === null ? "Restricted" : this.obj.class,
+ ownPropertyLength: Number.isFinite(ownPropertyLength)
+ ? ownPropertyLength
+ : undefined,
+ extensible: this.obj.isExtensible(),
+ frozen: this.obj.isFrozen(),
+ sealed: this.obj.isSealed(),
+ isError: this.obj.isError,
+ });
+
+ this.hooks.incrementGripDepth();
+
+ if (g.class == "Function") {
+ g.isClassConstructor = this.obj.isClassConstructor;
+ }
+
+ const raw = this.getRawObject();
+ this._populateGripPreview(g, raw);
+ this.hooks.decrementGripDepth();
+
+ if (raw && Node.isInstance(raw) && ContentDOMReference) {
+ // ContentDOMReference.get takes a DOM element and returns an object with
+ // its browsing context id, as well as a unique identifier. We are putting it in
+ // the grip here in order to be able to retrieve the node later, potentially from a
+ // different DevToolsServer running in the same process.
+ // If ContentDOMReference.get throws, we simply don't add the property to the grip.
+ try {
+ g.contentDomReference = ContentDOMReference.get(raw);
+ } catch (e) {}
+ }
+
+ return g;
+ },
+
+ _getOwnPropertyLength: function() {
+ if (isTypedArray(this.obj)) {
+ // Bug 1348761: getOwnPropertyNames is unnecessary slow on TypedArrays
+ return getArrayLength(this.obj);
+ }
+
+ if (isStorage(this.obj)) {
+ return getStorageLength(this.obj);
+ }
+
+ try {
+ return this.obj.getOwnPropertyNames().length;
+ } catch (err) {
+ // The above can throw when the debuggee does not subsume the object's
+ // compartment, or for some WrappedNatives like Cu.Sandbox.
+ }
+
+ return null;
+ },
+
+ getRawObject: function() {
+ let raw = this.obj.unsafeDereference();
+
+ // If Cu is not defined, we are running on a worker thread, where xrays
+ // don't exist.
+ if (raw && Cu) {
+ raw = Cu.unwaiveXrays(raw);
+ }
+
+ if (raw && !DevToolsUtils.isSafeJSObject(raw)) {
+ raw = null;
+ }
+
+ return raw;
+ },
+
+ /**
+ * Populate the `preview` property on `grip` given its type.
+ */
+ _populateGripPreview: function(grip, raw) {
+ for (const previewer of previewers[this.obj.class] || previewers.Object) {
+ try {
+ const previewerResult = previewer(this, grip, raw);
+ if (previewerResult) {
+ return;
+ }
+ } catch (e) {
+ const msg =
+ "ObjectActor.prototype._populateGripPreview previewer function";
+ DevToolsUtils.reportException(msg, e);
+ }
+ }
+ },
+
+ /**
+ * Returns an object exposing the internal Promise state.
+ */
+ promiseState: function() {
+ const { state, value, reason } = getPromiseState(this.obj);
+ const promiseState = { state };
+
+ if (state == "fulfilled") {
+ promiseState.value = this.hooks.createValueGrip(value);
+ } else if (state == "rejected") {
+ promiseState.reason = this.hooks.createValueGrip(reason);
+ }
+
+ promiseState.creationTimestamp = Date.now() - this.obj.promiseLifetime;
+
+ // Only add the timeToSettle property if the Promise isn't pending.
+ if (state !== "pending") {
+ promiseState.timeToSettle = this.obj.promiseTimeToResolution;
+ }
+
+ return { promiseState };
+ },
+
+ /**
+ * Handle a protocol request to provide the names of the properties defined on
+ * the object and not its prototype.
+ */
+ ownPropertyNames: function() {
+ let props = [];
+ if (DevToolsUtils.isSafeDebuggerObject(this.obj)) {
+ try {
+ props = this.obj.getOwnPropertyNames();
+ } catch (err) {
+ // The above can throw when the debuggee does not subsume the object's
+ // compartment, or for some WrappedNatives like Cu.Sandbox.
+ }
+ }
+ return { ownPropertyNames: props };
+ },
+
+ /**
+ * Creates an actor to iterate over an object property names and values.
+ * See PropertyIteratorActor constructor for more info about options param.
+ *
+ * @param options object
+ */
+ enumProperties: function(options) {
+ return PropertyIteratorActor(this, options, this.conn);
+ },
+
+ /**
+ * Creates an actor to iterate over entries of a Map/Set-like object.
+ */
+ enumEntries: function() {
+ return PropertyIteratorActor(this, { enumEntries: true }, this.conn);
+ },
+
+ /**
+ * Creates an actor to iterate over an object symbols properties.
+ */
+ enumSymbols: function() {
+ return SymbolIteratorActor(this, this.conn);
+ },
+
+ /**
+ * Handle a protocol request to provide the prototype and own properties of
+ * the object.
+ *
+ * @returns {Object} An object containing the data of this.obj, of the following form:
+ * - {Object} prototype: The descriptor of this.obj's prototype.
+ * - {Object} ownProperties: an object where the keys are the names of the
+ * this.obj's ownProperties, and the values the descriptors of
+ * the properties.
+ * - {Array} ownSymbols: An array containing all descriptors of this.obj's
+ * ownSymbols. Here we have an array, and not an object like for
+ * ownProperties, because we can have multiple symbols with the same
+ * name in this.obj, e.g. `{[Symbol()]: "a", [Symbol()]: "b"}`.
+ * - {Object} safeGetterValues: an object that maps this.obj's property names
+ * with safe getters descriptors.
+ */
+ prototypeAndProperties: function() {
+ let objProto = null;
+ let names = [];
+ let symbols = [];
+ if (DevToolsUtils.isSafeDebuggerObject(this.obj)) {
+ try {
+ objProto = this.obj.proto;
+ names = this.obj.getOwnPropertyNames();
+ symbols = this.obj.getOwnPropertySymbols();
+ } catch (err) {
+ // The above can throw when the debuggee does not subsume the object's
+ // compartment, or for some WrappedNatives like Cu.Sandbox.
+ }
+ }
+
+ const ownProperties = Object.create(null);
+ const ownSymbols = [];
+
+ for (const name of names) {
+ ownProperties[name] = this._propertyDescriptor(name);
+ }
+
+ for (const sym of symbols) {
+ ownSymbols.push({
+ name: sym.toString(),
+ descriptor: this._propertyDescriptor(sym),
+ });
+ }
+
+ return {
+ prototype: this.hooks.createValueGrip(objProto),
+ ownProperties,
+ ownSymbols,
+ safeGetterValues: this._findSafeGetterValues(names),
+ };
+ },
+
+ /**
+ * Find the safe getter values for the current Debugger.Object, |this.obj|.
+ *
+ * @private
+ * @param array ownProperties
+ * The array that holds the list of known ownProperties names for
+ * |this.obj|.
+ * @param number [limit=0]
+ * Optional limit of getter values to find.
+ * @return object
+ * An object that maps property names to safe getter descriptors as
+ * defined by the remote debugging protocol.
+ */
+ // eslint-disable-next-line complexity
+ _findSafeGetterValues: function(ownProperties, limit = 0) {
+ const safeGetterValues = Object.create(null);
+ let obj = this.obj;
+ let level = 0,
+ i = 0;
+
+ // Do not search safe getters in unsafe objects.
+ if (!DevToolsUtils.isSafeDebuggerObject(obj)) {
+ return safeGetterValues;
+ }
+
+ // Most objects don't have any safe getters but inherit some from their
+ // prototype. Avoid calling getOwnPropertyNames on objects that may have
+ // many properties like Array, strings or js objects. That to avoid
+ // freezing firefox when doing so.
+ if (isArray(this.obj) || ["Object", "String"].includes(this.obj.class)) {
+ obj = obj.proto;
+ level++;
+ }
+
+ while (obj && DevToolsUtils.isSafeDebuggerObject(obj)) {
+ const getters = this._findSafeGetters(obj);
+ for (const name of getters) {
+ // Avoid overwriting properties from prototypes closer to this.obj. Also
+ // avoid providing safeGetterValues from prototypes if property |name|
+ // is already defined as an own property.
+ if (
+ name in safeGetterValues ||
+ (obj != this.obj && ownProperties.includes(name))
+ ) {
+ continue;
+ }
+
+ // Ignore __proto__ on Object.prototye.
+ if (!obj.proto && name == "__proto__") {
+ continue;
+ }
+
+ let desc = null,
+ getter = null;
+ try {
+ desc = obj.getOwnPropertyDescriptor(name);
+ getter = desc.get;
+ } catch (ex) {
+ // The above can throw if the cache becomes stale.
+ }
+ if (!getter) {
+ obj._safeGetters = null;
+ continue;
+ }
+
+ const result = getter.call(this.obj);
+ if (!result || "throw" in result) {
+ continue;
+ }
+
+ let getterValue = undefined;
+ if ("return" in result) {
+ getterValue = result.return;
+ } else if ("yield" in result) {
+ getterValue = result.yield;
+ }
+
+ // Treat an already-rejected Promise as we would a thrown exception
+ // by not including it as a safe getter value (see Bug 1477765).
+ if (
+ getterValue &&
+ getterValue.class == "Promise" &&
+ getterValue.promiseState == "rejected"
+ ) {
+ // Until we have a good way to handle Promise rejections through the
+ // debugger API (Bug 1478076), call `catch` when it's safe to do so.
+ const raw = getterValue.unsafeDereference();
+ if (DevToolsUtils.isSafeJSObject(raw)) {
+ raw.catch(e => e);
+ }
+ continue;
+ }
+
+ // WebIDL attributes specified with the LenientThis extended attribute
+ // return undefined and should be ignored.
+ if (getterValue !== undefined) {
+ safeGetterValues[name] = {
+ getterValue: this.hooks.createValueGrip(getterValue),
+ getterPrototypeLevel: level,
+ enumerable: desc.enumerable,
+ writable: level == 0 ? desc.writable : true,
+ };
+ if (limit && ++i == limit) {
+ break;
+ }
+ }
+ }
+ if (limit && i == limit) {
+ break;
+ }
+
+ obj = obj.proto;
+ level++;
+ }
+
+ return safeGetterValues;
+ },
+
+ /**
+ * Find the safe getters for a given Debugger.Object. Safe getters are native
+ * getters which are safe to execute.
+ *
+ * @private
+ * @param Debugger.Object object
+ * The Debugger.Object where you want to find safe getters.
+ * @return Set
+ * A Set of names of safe getters. This result is cached for each
+ * Debugger.Object.
+ */
+ _findSafeGetters: function(object) {
+ if (object._safeGetters) {
+ return object._safeGetters;
+ }
+
+ const getters = new Set();
+
+ if (!DevToolsUtils.isSafeDebuggerObject(object)) {
+ object._safeGetters = getters;
+ return getters;
+ }
+
+ let names = [];
+ try {
+ names = object.getOwnPropertyNames();
+ } catch (ex) {
+ // Calling getOwnPropertyNames() on some wrapped native prototypes is not
+ // allowed: "cannot modify properties of a WrappedNative". See bug 952093.
+ }
+
+ for (const name of names) {
+ let desc = null;
+ try {
+ desc = object.getOwnPropertyDescriptor(name);
+ } catch (e) {
+ // Calling getOwnPropertyDescriptor on wrapped native prototypes is not
+ // allowed (bug 560072).
+ }
+ if (!desc || desc.value !== undefined || !("get" in desc)) {
+ continue;
+ }
+
+ if (DevToolsUtils.hasSafeGetter(desc)) {
+ getters.add(name);
+ }
+ }
+
+ object._safeGetters = getters;
+ return getters;
+ },
+
+ /**
+ * Handle a protocol request to provide the prototype of the object.
+ */
+ prototype: function() {
+ let objProto = null;
+ if (DevToolsUtils.isSafeDebuggerObject(this.obj)) {
+ objProto = this.obj.proto;
+ }
+ return { prototype: this.hooks.createValueGrip(objProto) };
+ },
+
+ /**
+ * Handle a protocol request to provide the property descriptor of the
+ * object's specified property.
+ *
+ * @param name string
+ * The property we want the description of.
+ */
+ property: function(name) {
+ if (!name) {
+ return this.throwError(
+ "missingParameter",
+ "no property name was specified"
+ );
+ }
+
+ return { descriptor: this._propertyDescriptor(name) };
+ },
+
+ /**
+ * Handle a protocol request to provide the value of the object's
+ * specified property.
+ *
+ * Note: Since this will evaluate getters, it can trigger execution of
+ * content code and may cause side effects. This endpoint should only be used
+ * when you are confident that the side-effects will be safe, or the user
+ * is expecting the effects.
+ *
+ * @param {string} name
+ * The property we want the value of.
+ * @param {string|null} receiverId
+ * The actorId of the receiver to be used if the property is a getter.
+ * If null or invalid, the receiver will be the referent.
+ */
+ propertyValue: function(name, receiverId) {
+ if (!name) {
+ return this.throwError(
+ "missingParameter",
+ "no property name was specified"
+ );
+ }
+
+ let receiver;
+ if (receiverId) {
+ const receiverActor = this.conn.getActor(receiverId);
+ if (receiverActor) {
+ receiver = receiverActor.obj;
+ }
+ }
+
+ const value = receiver
+ ? this.obj.getProperty(name, receiver)
+ : this.obj.getProperty(name);
+
+ return { value: this._buildCompletion(value) };
+ },
+
+ /**
+ * Handle a protocol request to evaluate a function and provide the value of
+ * the result.
+ *
+ * Note: Since this will evaluate the function, it can trigger execution of
+ * content code and may cause side effects. This endpoint should only be used
+ * when you are confident that the side-effects will be safe, or the user
+ * is expecting the effects.
+ *
+ * @param {any} context
+ * The 'this' value to call the function with.
+ * @param {Array<any>} args
+ * The array of un-decoded actor objects, or primitives.
+ */
+ apply: function(context, args) {
+ if (!this.obj.callable) {
+ return this.throwError("notCallable", "debugee object is not callable");
+ }
+
+ const debugeeContext = this._getValueFromGrip(context);
+ const debugeeArgs = args && args.map(this._getValueFromGrip, this);
+
+ const value = this.obj.apply(debugeeContext, debugeeArgs);
+
+ return { value: this._buildCompletion(value) };
+ },
+
+ _getValueFromGrip(grip) {
+ if (typeof grip !== "object" || !grip) {
+ return grip;
+ }
+
+ if (typeof grip.actor !== "string") {
+ return this.throwError(
+ "invalidGrip",
+ "grip argument did not include actor ID"
+ );
+ }
+
+ const actor = this.conn.getActor(grip.actor);
+
+ if (!actor) {
+ return this.throwError(
+ "unknownActor",
+ "grip actor did not match a known object"
+ );
+ }
+
+ return actor.obj;
+ },
+
+ /**
+ * Converts a Debugger API completion value record into an eqivalent
+ * object grip for use by the API.
+ *
+ * See https://developer.mozilla.org/en-US/docs/Tools/Debugger-API/Conventions#completion-values
+ * for more specifics on the expected behavior.
+ */
+ _buildCompletion(value) {
+ let completionGrip = null;
+
+ // .apply result will be falsy if the script being executed is terminated
+ // via the "slow script" dialog.
+ if (value) {
+ completionGrip = {};
+ if ("return" in value) {
+ completionGrip.return = this.hooks.createValueGrip(value.return);
+ }
+ if ("throw" in value) {
+ completionGrip.throw = this.hooks.createValueGrip(value.throw);
+ }
+ }
+
+ return completionGrip;
+ },
+
+ /**
+ * Handle a protocol request to provide the display string for the object.
+ */
+ displayString: function() {
+ const string = stringify(this.obj);
+ return { displayString: this.hooks.createValueGrip(string) };
+ },
+
+ /**
+ * A helper method that creates a property descriptor for the provided object,
+ * properly formatted for sending in a protocol response.
+ *
+ * @private
+ * @param string name
+ * The property that the descriptor is generated for.
+ * @param boolean [onlyEnumerable]
+ * Optional: true if you want a descriptor only for an enumerable
+ * property, false otherwise.
+ * @return object|undefined
+ * The property descriptor, or undefined if this is not an enumerable
+ * property and onlyEnumerable=true.
+ */
+ _propertyDescriptor: function(name, onlyEnumerable) {
+ if (!DevToolsUtils.isSafeDebuggerObject(this.obj)) {
+ return undefined;
+ }
+
+ let desc;
+ try {
+ desc = this.obj.getOwnPropertyDescriptor(name);
+ } catch (e) {
+ // Calling getOwnPropertyDescriptor on wrapped native prototypes is not
+ // allowed (bug 560072). Inform the user with a bogus, but hopefully
+ // explanatory, descriptor.
+ return {
+ configurable: false,
+ writable: false,
+ enumerable: false,
+ value: e.name,
+ };
+ }
+
+ if (isStorage(this.obj)) {
+ if (name === "length") {
+ return undefined;
+ }
+ return desc;
+ }
+
+ if (!desc || (onlyEnumerable && !desc.enumerable)) {
+ return undefined;
+ }
+
+ const retval = {
+ configurable: desc.configurable,
+ enumerable: desc.enumerable,
+ };
+ const obj = this.rawValue();
+
+ if ("value" in desc) {
+ retval.writable = desc.writable;
+ retval.value = this.hooks.createValueGrip(desc.value);
+ } else if (this.thread.getWatchpoint(obj, name.toString())) {
+ const watchpoint = this.thread.getWatchpoint(obj, name.toString());
+ retval.value = this.hooks.createValueGrip(watchpoint.desc.value);
+ retval.watchpoint = watchpoint.watchpointType;
+ } else {
+ if ("get" in desc) {
+ retval.get = this.hooks.createValueGrip(desc.get);
+ }
+
+ if ("set" in desc) {
+ retval.set = this.hooks.createValueGrip(desc.set);
+ }
+ }
+ return retval;
+ },
+
+ /**
+ * Handle a protocol request to provide the source code of a function.
+ *
+ * @param pretty boolean
+ */
+ decompile: function(pretty) {
+ if (this.obj.class !== "Function") {
+ return this.throwError(
+ "objectNotFunction",
+ "decompile request is only valid for grips with a 'Function' class."
+ );
+ }
+
+ return { decompiledCode: this.obj.decompile(!!pretty) };
+ },
+
+ /**
+ * Handle a protocol request to provide the parameters of a function.
+ */
+ parameterNames: function() {
+ if (this.obj.class !== "Function") {
+ return this.throwError(
+ "objectNotFunction",
+ "'parameterNames' request is only valid for grips with a 'Function' class."
+ );
+ }
+
+ return { parameterNames: this.obj.parameterNames };
+ },
+
+ /**
+ * Handle a protocol request to get the target and handler internal slots of a proxy.
+ */
+ proxySlots: function() {
+ // There could be transparent security wrappers, unwrap to check if it's a proxy.
+ // However, retrieve proxyTarget and proxyHandler from `this.obj` to avoid exposing
+ // the unwrapped target and handler.
+ const unwrapped = DevToolsUtils.unwrap(this.obj);
+ if (!unwrapped || !unwrapped.isProxy) {
+ return this.throwError(
+ "objectNotProxy",
+ "'proxySlots' request is only valid for grips with a 'Proxy' class."
+ );
+ }
+ return {
+ proxyTarget: this.hooks.createValueGrip(this.obj.proxyTarget),
+ proxyHandler: this.hooks.createValueGrip(this.obj.proxyHandler),
+ };
+ },
+
+ /**
+ * Release the actor, when it isn't needed anymore.
+ * Protocol.js uses this release method to call the destroy method.
+ */
+ release: function() {},
+};
+
+exports.ObjectActor = protocol.ActorClassWithSpec(objectSpec, proto);
+exports.ObjectActorProto = proto;
diff --git a/devtools/server/actors/object/moz.build b/devtools/server/actors/object/moz.build
new file mode 100644
index 0000000000..6f51d9abd7
--- /dev/null
+++ b/devtools/server/actors/object/moz.build
@@ -0,0 +1,12 @@
+# 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/.
+
+DevToolsModules(
+ "previewers.js",
+ "property-iterator.js",
+ "stringifiers.js",
+ "symbol-iterator.js",
+ "symbol.js",
+ "utils.js",
+)
diff --git a/devtools/server/actors/object/previewers.js b/devtools/server/actors/object/previewers.js
new file mode 100644
index 0000000000..2768b7c610
--- /dev/null
+++ b/devtools/server/actors/object/previewers.js
@@ -0,0 +1,898 @@
+/* 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";
+
+const { Cu, Ci } = require("chrome");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+loader.lazyRequireGetter(
+ this,
+ "ObjectUtils",
+ "devtools/server/actors/object/utils"
+);
+loader.lazyRequireGetter(
+ this,
+ "PropertyIterators",
+ "devtools/server/actors/object/property-iterator"
+);
+
+// Number of items to preview in objects, arrays, maps, sets, lists,
+// collections, etc.
+const OBJECT_PREVIEW_MAX_ITEMS = 10;
+
+/**
+ * Functions for adding information to ObjectActor grips for the purpose of
+ * having customized output. This object holds arrays mapped by
+ * Debugger.Object.prototype.class.
+ *
+ * In each array you can add functions that take three
+ * arguments:
+ * - the ObjectActor instance and its hooks to make a preview for,
+ * - the grip object being prepared for the client,
+ * - the raw JS object after calling Debugger.Object.unsafeDereference(). This
+ * argument is only provided if the object is safe for reading properties and
+ * executing methods. See DevToolsUtils.isSafeJSObject().
+ *
+ * Functions must return false if they cannot provide preview
+ * information for the debugger object, or true otherwise.
+ */
+const previewers = {
+ String: [
+ function(objectActor, grip, rawObj) {
+ return wrappedPrimitivePreviewer(
+ "String",
+ String,
+ objectActor,
+ grip,
+ rawObj
+ );
+ },
+ ],
+
+ Boolean: [
+ function(objectActor, grip, rawObj) {
+ return wrappedPrimitivePreviewer(
+ "Boolean",
+ Boolean,
+ objectActor,
+ grip,
+ rawObj
+ );
+ },
+ ],
+
+ Number: [
+ function(objectActor, grip, rawObj) {
+ return wrappedPrimitivePreviewer(
+ "Number",
+ Number,
+ objectActor,
+ grip,
+ rawObj
+ );
+ },
+ ],
+
+ Symbol: [
+ function(objectActor, grip, rawObj) {
+ return wrappedPrimitivePreviewer(
+ "Symbol",
+ Symbol,
+ objectActor,
+ grip,
+ rawObj
+ );
+ },
+ ],
+
+ Function: [
+ function({ obj, hooks }, grip) {
+ if (obj.name) {
+ grip.name = obj.name;
+ }
+
+ if (obj.displayName) {
+ grip.displayName = obj.displayName.substr(0, 500);
+ }
+
+ if (obj.parameterNames) {
+ grip.parameterNames = obj.parameterNames;
+ }
+
+ // Check if the developer has added a de-facto standard displayName
+ // property for us to use.
+ let userDisplayName;
+ try {
+ userDisplayName = obj.getOwnPropertyDescriptor("displayName");
+ } catch (e) {
+ // The above can throw "permission denied" errors when the debuggee
+ // does not subsume the function's compartment.
+ }
+
+ if (
+ userDisplayName &&
+ typeof userDisplayName.value == "string" &&
+ userDisplayName.value
+ ) {
+ grip.userDisplayName = hooks.createValueGrip(userDisplayName.value);
+ }
+
+ grip.isAsync = obj.isAsyncFunction;
+ grip.isGenerator = obj.isGeneratorFunction;
+
+ if (obj.script) {
+ grip.location = {
+ url: obj.script.url,
+ line: obj.script.startLine,
+ column: obj.script.startColumn,
+ };
+ }
+
+ return true;
+ },
+ ],
+
+ RegExp: [
+ function({ obj, hooks }, grip) {
+ const str = DevToolsUtils.callPropertyOnObject(obj, "toString");
+ if (typeof str != "string") {
+ return false;
+ }
+
+ grip.displayString = hooks.createValueGrip(str);
+ return true;
+ },
+ ],
+
+ Date: [
+ function({ obj, hooks }, grip) {
+ const time = DevToolsUtils.callPropertyOnObject(obj, "getTime");
+ if (typeof time != "number") {
+ return false;
+ }
+
+ grip.preview = {
+ timestamp: hooks.createValueGrip(time),
+ };
+ return true;
+ },
+ ],
+
+ Array: [
+ function({ obj, hooks }, grip) {
+ const length = ObjectUtils.getArrayLength(obj);
+
+ grip.preview = {
+ kind: "ArrayLike",
+ length: length,
+ };
+
+ if (hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const raw = obj.unsafeDereference();
+ const items = (grip.preview.items = []);
+
+ for (let i = 0; i < length; ++i) {
+ if (raw && !isWorker) {
+ // Array Xrays filter out various possibly-unsafe properties (like
+ // functions, and claim that the value is undefined instead. This
+ // is generally the right thing for privileged code accessing untrusted
+ // objects, but quite confusing for Object previews. So we manually
+ // override this protection by waiving Xrays on the array, and re-applying
+ // Xrays on any indexed value props that we pull off of it.
+ const desc = Object.getOwnPropertyDescriptor(Cu.waiveXrays(raw), i);
+ if (desc && !desc.get && !desc.set) {
+ let value = Cu.unwaiveXrays(desc.value);
+ value = ObjectUtils.makeDebuggeeValueIfNeeded(obj, value);
+ items.push(hooks.createValueGrip(value));
+ } else if (!desc) {
+ items.push(null);
+ } else {
+ items.push(hooks.createValueGrip(undefined));
+ }
+ } else if (raw && !Object.getOwnPropertyDescriptor(raw, i)) {
+ items.push(null);
+ } else {
+ // Workers do not have access to Cu.
+ const value = DevToolsUtils.getProperty(obj, i);
+ items.push(hooks.createValueGrip(value));
+ }
+
+ if (items.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ return true;
+ },
+ ],
+
+ Set: [
+ function(objectActor, grip) {
+ const size = DevToolsUtils.getProperty(objectActor.obj, "size");
+ if (typeof size != "number") {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "ArrayLike",
+ length: size,
+ };
+
+ // Avoid recursive object grips.
+ if (objectActor.hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const items = (grip.preview.items = []);
+ for (const item of PropertyIterators.enumSetEntries(
+ objectActor,
+ /* forPreview */ true
+ )) {
+ items.push(item);
+ if (items.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ return true;
+ },
+ ],
+
+ WeakSet: [
+ function(objectActor, grip) {
+ const enumEntries = PropertyIterators.enumWeakSetEntries(
+ objectActor,
+ /* forPreview */ true
+ );
+
+ grip.preview = {
+ kind: "ArrayLike",
+ length: enumEntries.size,
+ };
+
+ // Avoid recursive object grips.
+ if (objectActor.hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const items = (grip.preview.items = []);
+ for (const item of enumEntries) {
+ items.push(item);
+ if (items.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ return true;
+ },
+ ],
+
+ Map: [
+ function(objectActor, grip) {
+ const size = DevToolsUtils.getProperty(objectActor.obj, "size");
+ if (typeof size != "number") {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "MapLike",
+ size: size,
+ };
+
+ if (objectActor.hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const entries = (grip.preview.entries = []);
+ for (const entry of PropertyIterators.enumMapEntries(
+ objectActor,
+ /* forPreview */ true
+ )) {
+ entries.push(entry);
+ if (entries.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ return true;
+ },
+ ],
+
+ WeakMap: [
+ function(objectActor, grip) {
+ const enumEntries = PropertyIterators.enumWeakMapEntries(
+ objectActor,
+ /* forPreview */ true
+ );
+
+ grip.preview = {
+ kind: "MapLike",
+ size: enumEntries.size,
+ };
+
+ if (objectActor.hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const entries = (grip.preview.entries = []);
+ for (const entry of enumEntries) {
+ entries.push(entry);
+ if (entries.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ return true;
+ },
+ ],
+
+ DOMStringMap: [
+ function({ obj, hooks }, grip, rawObj) {
+ if (!rawObj) {
+ return false;
+ }
+
+ const keys = obj.getOwnPropertyNames();
+ grip.preview = {
+ kind: "MapLike",
+ size: keys.length,
+ };
+
+ if (hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const entries = (grip.preview.entries = []);
+ for (const key of keys) {
+ const value = ObjectUtils.makeDebuggeeValueIfNeeded(obj, rawObj[key]);
+ entries.push([key, hooks.createValueGrip(value)]);
+ if (entries.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ return true;
+ },
+ ],
+
+ Promise: [
+ function({ obj, hooks }, grip, rawObj) {
+ const { state, value, reason } = ObjectUtils.getPromiseState(obj);
+ const ownProperties = Object.create(null);
+ ownProperties["<state>"] = { value: state };
+ let ownPropertiesLength = 1;
+
+ // Only expose <value> or <reason> in top-level promises, to avoid recursion.
+ // <state> is not problematic because it's a string.
+ if (hooks.getGripDepth() === 1) {
+ if (state == "fulfilled") {
+ ownProperties["<value>"] = { value: hooks.createValueGrip(value) };
+ ++ownPropertiesLength;
+ } else if (state == "rejected") {
+ ownProperties["<reason>"] = { value: hooks.createValueGrip(reason) };
+ ++ownPropertiesLength;
+ }
+ }
+
+ grip.preview = {
+ kind: "Object",
+ ownProperties,
+ ownPropertiesLength,
+ };
+
+ return true;
+ },
+ ],
+
+ Proxy: [
+ function({ obj, hooks }, grip, rawObj) {
+ // Only preview top-level proxies, avoiding recursion. Otherwise, since both the
+ // target and handler can also be proxies, we could get an exponential behavior.
+ if (hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ // The `isProxy` getter of the debuggee object only detects proxies without
+ // security wrappers. If false, the target and handler are not available.
+ const hasTargetAndHandler = obj.isProxy;
+
+ grip.preview = {
+ kind: "Object",
+ ownProperties: Object.create(null),
+ ownPropertiesLength: 2 * hasTargetAndHandler,
+ };
+
+ if (hasTargetAndHandler) {
+ Object.assign(grip.preview.ownProperties, {
+ "<target>": { value: hooks.createValueGrip(obj.proxyTarget) },
+ "<handler>": { value: hooks.createValueGrip(obj.proxyHandler) },
+ });
+ }
+
+ return true;
+ },
+ ],
+};
+
+/**
+ * Generic previewer for classes wrapping primitives, like String,
+ * Number and Boolean.
+ *
+ * @param string className
+ * Class name to expect.
+ * @param object classObj
+ * The class to expect, eg. String. The valueOf() method of the class is
+ * invoked on the given object.
+ * @param ObjectActor objectActor
+ * The object actor
+ * @param Object grip
+ * The result grip to fill in
+ * @return Booolean true if the object was handled, false otherwise
+ */
+function wrappedPrimitivePreviewer(
+ className,
+ classObj,
+ objectActor,
+ grip,
+ rawObj
+) {
+ const { obj, hooks } = objectActor;
+
+ let v = null;
+ try {
+ v = classObj.prototype.valueOf.call(rawObj);
+ } catch (ex) {
+ // valueOf() can throw if the raw JS object is "misbehaved".
+ return false;
+ }
+
+ if (v === null) {
+ return false;
+ }
+
+ const canHandle = GenericObject(
+ objectActor,
+ grip,
+ rawObj,
+ className === "String"
+ );
+ if (!canHandle) {
+ return false;
+ }
+
+ grip.preview.wrappedValue = hooks.createValueGrip(
+ ObjectUtils.makeDebuggeeValueIfNeeded(obj, v)
+ );
+ return true;
+}
+
+function GenericObject(
+ objectActor,
+ grip,
+ rawObj,
+ specialStringBehavior = false
+) {
+ const { obj, hooks } = objectActor;
+ if (grip.preview || grip.displayString || hooks.getGripDepth() > 1) {
+ return false;
+ }
+
+ const preview = (grip.preview = {
+ kind: "Object",
+ ownProperties: Object.create(null),
+ ownSymbols: [],
+ });
+
+ const names = ObjectUtils.getPropNamesFromObject(obj, rawObj);
+ const symbols = ObjectUtils.getSafeOwnPropertySymbols(obj);
+
+ preview.ownPropertiesLength = names.length;
+ preview.ownSymbolsLength = symbols.length;
+
+ let length,
+ i = 0;
+ if (specialStringBehavior) {
+ length = DevToolsUtils.getProperty(obj, "length");
+ if (typeof length != "number") {
+ specialStringBehavior = false;
+ }
+ }
+
+ for (const name of names) {
+ if (specialStringBehavior && /^[0-9]+$/.test(name)) {
+ const num = parseInt(name, 10);
+ if (num.toString() === name && num >= 0 && num < length) {
+ continue;
+ }
+ }
+
+ const desc = objectActor._propertyDescriptor(name, true);
+ if (!desc) {
+ continue;
+ }
+
+ preview.ownProperties[name] = desc;
+ if (++i == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ for (const symbol of symbols) {
+ const descriptor = objectActor._propertyDescriptor(symbol, true);
+ if (!descriptor) {
+ continue;
+ }
+
+ preview.ownSymbols.push(
+ Object.assign(
+ {
+ descriptor,
+ },
+ hooks.createValueGrip(symbol)
+ )
+ );
+
+ if (++i == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+
+ if (i < OBJECT_PREVIEW_MAX_ITEMS) {
+ preview.safeGetterValues = objectActor._findSafeGetterValues(
+ Object.keys(preview.ownProperties),
+ OBJECT_PREVIEW_MAX_ITEMS - i
+ );
+ }
+
+ return true;
+}
+
+// Preview functions that do not rely on the object class.
+previewers.Object = [
+ function TypedArray({ obj, hooks }, grip) {
+ if (!ObjectUtils.isTypedArray(obj)) {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "ArrayLike",
+ length: ObjectUtils.getArrayLength(obj),
+ };
+
+ if (hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const previewLength = Math.min(
+ OBJECT_PREVIEW_MAX_ITEMS,
+ grip.preview.length
+ );
+ grip.preview.items = [];
+ for (let i = 0; i < previewLength; i++) {
+ const desc = obj.getOwnPropertyDescriptor(i);
+ if (!desc) {
+ break;
+ }
+ grip.preview.items.push(desc.value);
+ }
+
+ return true;
+ },
+
+ function Error({ obj, hooks }, grip) {
+ switch (obj.class) {
+ case "Error":
+ case "EvalError":
+ case "RangeError":
+ case "ReferenceError":
+ case "SyntaxError":
+ case "TypeError":
+ case "URIError":
+ case "InternalError":
+ case "AggregateError":
+ case "CompileError":
+ case "DebuggeeWouldRun":
+ case "LinkError":
+ case "RuntimeError":
+ const name = DevToolsUtils.getProperty(obj, "name");
+ const msg = DevToolsUtils.getProperty(obj, "message");
+ const stack = DevToolsUtils.getProperty(obj, "stack");
+ const fileName = DevToolsUtils.getProperty(obj, "fileName");
+ const lineNumber = DevToolsUtils.getProperty(obj, "lineNumber");
+ const columnNumber = DevToolsUtils.getProperty(obj, "columnNumber");
+ grip.preview = {
+ kind: "Error",
+ name: hooks.createValueGrip(name),
+ message: hooks.createValueGrip(msg),
+ stack: hooks.createValueGrip(stack),
+ fileName: hooks.createValueGrip(fileName),
+ lineNumber: hooks.createValueGrip(lineNumber),
+ columnNumber: hooks.createValueGrip(columnNumber),
+ };
+ return true;
+ default:
+ return false;
+ }
+ },
+
+ function CSSMediaRule({ obj, hooks }, grip, rawObj) {
+ if (isWorker || !rawObj || obj.class != "CSSMediaRule") {
+ return false;
+ }
+ grip.preview = {
+ kind: "ObjectWithText",
+ text: hooks.createValueGrip(rawObj.conditionText),
+ };
+ return true;
+ },
+
+ function CSSStyleRule({ obj, hooks }, grip, rawObj) {
+ if (isWorker || !rawObj || obj.class != "CSSStyleRule") {
+ return false;
+ }
+ grip.preview = {
+ kind: "ObjectWithText",
+ text: hooks.createValueGrip(rawObj.selectorText),
+ };
+ return true;
+ },
+
+ function ObjectWithURL({ obj, hooks }, grip, rawObj) {
+ if (
+ isWorker ||
+ !rawObj ||
+ !(
+ obj.class == "CSSImportRule" ||
+ obj.class == "CSSStyleSheet" ||
+ obj.class == "Location" ||
+ rawObj instanceof Ci.nsIDOMWindow
+ )
+ ) {
+ return false;
+ }
+
+ let url;
+ if (rawObj instanceof Ci.nsIDOMWindow && rawObj.location) {
+ url = rawObj.location.href;
+ } else if (rawObj.href) {
+ url = rawObj.href;
+ } else {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "ObjectWithURL",
+ url: hooks.createValueGrip(url),
+ };
+
+ return true;
+ },
+
+ function ArrayLike({ obj, hooks }, grip, rawObj) {
+ if (
+ isWorker ||
+ !rawObj ||
+ (obj.class != "DOMStringList" &&
+ obj.class != "DOMTokenList" &&
+ obj.class != "CSSRuleList" &&
+ obj.class != "MediaList" &&
+ obj.class != "StyleSheetList" &&
+ obj.class != "NamedNodeMap" &&
+ obj.class != "FileList" &&
+ obj.class != "NodeList")
+ ) {
+ return false;
+ }
+
+ if (typeof rawObj.length != "number") {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "ArrayLike",
+ length: rawObj.length,
+ };
+
+ if (hooks.getGripDepth() > 1) {
+ return true;
+ }
+
+ const items = (grip.preview.items = []);
+
+ for (
+ let i = 0;
+ i < rawObj.length && items.length < OBJECT_PREVIEW_MAX_ITEMS;
+ i++
+ ) {
+ const value = ObjectUtils.makeDebuggeeValueIfNeeded(obj, rawObj[i]);
+ items.push(hooks.createValueGrip(value));
+ }
+
+ return true;
+ },
+
+ function CSSStyleDeclaration({ obj, hooks }, grip, rawObj) {
+ if (
+ isWorker ||
+ !rawObj ||
+ (obj.class != "CSSStyleDeclaration" && obj.class != "CSS2Properties")
+ ) {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "MapLike",
+ size: rawObj.length,
+ };
+
+ const entries = (grip.preview.entries = []);
+
+ for (let i = 0; i < OBJECT_PREVIEW_MAX_ITEMS && i < rawObj.length; i++) {
+ const prop = rawObj[i];
+ const value = rawObj.getPropertyValue(prop);
+ entries.push([prop, hooks.createValueGrip(value)]);
+ }
+
+ return true;
+ },
+
+ function DOMNode({ obj, hooks }, grip, rawObj) {
+ if (
+ isWorker ||
+ obj.class == "Object" ||
+ !rawObj ||
+ !Node.isInstance(rawObj)
+ ) {
+ return false;
+ }
+
+ const preview = (grip.preview = {
+ kind: "DOMNode",
+ nodeType: rawObj.nodeType,
+ nodeName: rawObj.nodeName,
+ isConnected: rawObj.isConnected === true,
+ });
+
+ if (rawObj.nodeType == rawObj.DOCUMENT_NODE && rawObj.location) {
+ preview.location = hooks.createValueGrip(rawObj.location.href);
+ } else if (obj.class == "DocumentFragment") {
+ preview.childNodesLength = rawObj.childNodes.length;
+
+ if (hooks.getGripDepth() < 2) {
+ preview.childNodes = [];
+ for (const node of rawObj.childNodes) {
+ const actor = hooks.createValueGrip(obj.makeDebuggeeValue(node));
+ preview.childNodes.push(actor);
+ if (preview.childNodes.length == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+ }
+ } else if (Element.isInstance(rawObj)) {
+ // For HTML elements (in an HTML document, at least), the nodeName is an
+ // uppercased version of the actual element name. Check for HTML
+ // elements, that is elements in the HTML namespace, and lowercase the
+ // nodeName in that case.
+ if (rawObj.namespaceURI == "http://www.w3.org/1999/xhtml") {
+ preview.nodeName = preview.nodeName.toLowerCase();
+ }
+
+ // Add preview for DOM element attributes.
+ preview.attributes = {};
+ preview.attributesLength = rawObj.attributes.length;
+ for (const attr of rawObj.attributes) {
+ preview.attributes[attr.nodeName] = hooks.createValueGrip(attr.value);
+ }
+ } else if (obj.class == "Attr") {
+ preview.value = hooks.createValueGrip(rawObj.value);
+ } else if (
+ obj.class == "Text" ||
+ obj.class == "CDATASection" ||
+ obj.class == "Comment"
+ ) {
+ preview.textContent = hooks.createValueGrip(rawObj.textContent);
+ }
+
+ return true;
+ },
+
+ function DOMEvent({ obj, hooks }, grip, rawObj) {
+ if (isWorker || !rawObj || !Event.isInstance(rawObj)) {
+ return false;
+ }
+
+ const preview = (grip.preview = {
+ kind: "DOMEvent",
+ type: rawObj.type,
+ properties: Object.create(null),
+ });
+
+ if (hooks.getGripDepth() < 2) {
+ const target = obj.makeDebuggeeValue(rawObj.target);
+ preview.target = hooks.createValueGrip(target);
+ }
+
+ if (obj.class == "KeyboardEvent") {
+ preview.eventKind = "key";
+ preview.modifiers = ObjectUtils.getModifiersForEvent(rawObj);
+ }
+
+ const props = ObjectUtils.getPropsForEvent(obj.class);
+
+ // Add event-specific properties.
+ for (const prop of props) {
+ let value = rawObj[prop];
+ if (ObjectUtils.isObjectOrFunction(value)) {
+ // Skip properties pointing to objects.
+ if (hooks.getGripDepth() > 1) {
+ continue;
+ }
+ value = obj.makeDebuggeeValue(value);
+ }
+ preview.properties[prop] = hooks.createValueGrip(value);
+ }
+
+ // Add any properties we find on the event object.
+ if (!props.length) {
+ let i = 0;
+ for (const prop in rawObj) {
+ let value = rawObj[prop];
+ if (
+ prop == "target" ||
+ prop == "type" ||
+ value === null ||
+ typeof value == "function"
+ ) {
+ continue;
+ }
+ if (value && typeof value == "object") {
+ if (hooks.getGripDepth() > 1) {
+ continue;
+ }
+ value = obj.makeDebuggeeValue(value);
+ }
+ preview.properties[prop] = hooks.createValueGrip(value);
+ if (++i == OBJECT_PREVIEW_MAX_ITEMS) {
+ break;
+ }
+ }
+ }
+
+ return true;
+ },
+
+ function DOMException({ obj, hooks }, grip, rawObj) {
+ if (isWorker || !rawObj || obj.class !== "DOMException") {
+ return false;
+ }
+
+ grip.preview = {
+ kind: "DOMException",
+ name: hooks.createValueGrip(rawObj.name),
+ message: hooks.createValueGrip(rawObj.message),
+ code: hooks.createValueGrip(rawObj.code),
+ result: hooks.createValueGrip(rawObj.result),
+ filename: hooks.createValueGrip(rawObj.filename),
+ lineNumber: hooks.createValueGrip(rawObj.lineNumber),
+ columnNumber: hooks.createValueGrip(rawObj.columnNumber),
+ };
+
+ return true;
+ },
+
+ function Object(objectActor, grip, rawObj) {
+ return GenericObject(
+ objectActor,
+ grip,
+ rawObj,
+ /* specialStringBehavior = */ false
+ );
+ },
+];
+
+module.exports = previewers;
diff --git a/devtools/server/actors/object/property-iterator.js b/devtools/server/actors/object/property-iterator.js
new file mode 100644
index 0000000000..10d8997172
--- /dev/null
+++ b/devtools/server/actors/object/property-iterator.js
@@ -0,0 +1,493 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const protocol = require("devtools/shared/protocol");
+const {
+ propertyIteratorSpec,
+} = require("devtools/shared/specs/property-iterator");
+loader.lazyRequireGetter(this, "ChromeUtils");
+loader.lazyRequireGetter(
+ this,
+ "ObjectUtils",
+ "devtools/server/actors/object/utils"
+);
+
+/**
+ * Creates an actor to iterate over an object's property names and values.
+ *
+ * @param objectActor ObjectActor
+ * The object actor.
+ * @param options Object
+ * A dictionary object with various boolean attributes:
+ * - enumEntries Boolean
+ * If true, enumerates the entries of a Map or Set object
+ * instead of enumerating properties.
+ * - ignoreIndexedProperties Boolean
+ * If true, filters out Array items.
+ * e.g. properties names between `0` and `object.length`.
+ * - ignoreNonIndexedProperties Boolean
+ * If true, filters out items that aren't array items
+ * e.g. properties names that are not a number between `0`
+ * and `object.length`.
+ * - sort Boolean
+ * If true, the iterator will sort the properties by name
+ * before dispatching them.
+ * - query String
+ * If non-empty, will filter the properties by names and values
+ * containing this query string. The match is not case-sensitive.
+ * Regarding value filtering it just compare to the stringification
+ * of the property value.
+ */
+const PropertyIteratorActor = protocol.ActorClassWithSpec(
+ propertyIteratorSpec,
+ {
+ initialize(objectActor, options, conn) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ if (!DevToolsUtils.isSafeDebuggerObject(objectActor.obj)) {
+ this.iterator = {
+ size: 0,
+ propertyName: index => undefined,
+ propertyDescription: index => undefined,
+ };
+ } else if (options.enumEntries) {
+ const cls = objectActor.obj.class;
+ if (cls == "Map") {
+ this.iterator = enumMapEntries(objectActor);
+ } else if (cls == "WeakMap") {
+ this.iterator = enumWeakMapEntries(objectActor);
+ } else if (cls == "Set") {
+ this.iterator = enumSetEntries(objectActor);
+ } else if (cls == "WeakSet") {
+ this.iterator = enumWeakSetEntries(objectActor);
+ } else if (cls == "Storage") {
+ this.iterator = enumStorageEntries(objectActor);
+ } else {
+ throw new Error(
+ "Unsupported class to enumerate entries from: " + cls
+ );
+ }
+ } else if (
+ ObjectUtils.isArray(objectActor.obj) &&
+ options.ignoreNonIndexedProperties &&
+ !options.query
+ ) {
+ this.iterator = enumArrayProperties(objectActor, options);
+ } else {
+ this.iterator = enumObjectProperties(objectActor, options);
+ }
+ },
+
+ form() {
+ return {
+ type: this.typeName,
+ actor: this.actorID,
+ count: this.iterator.size,
+ };
+ },
+
+ names({ indexes }) {
+ const list = [];
+ for (const idx of indexes) {
+ list.push(this.iterator.propertyName(idx));
+ }
+ return indexes;
+ },
+
+ slice({ start, count }) {
+ const ownProperties = Object.create(null);
+ for (let i = start, m = start + count; i < m; i++) {
+ const name = this.iterator.propertyName(i);
+ ownProperties[name] = this.iterator.propertyDescription(i);
+ }
+
+ return {
+ ownProperties,
+ };
+ },
+
+ all() {
+ return this.slice({ start: 0, count: this.iterator.size });
+ },
+ }
+);
+
+function waiveXrays(obj) {
+ return isWorker ? obj : Cu.waiveXrays(obj);
+}
+
+function unwaiveXrays(obj) {
+ return isWorker ? obj : Cu.unwaiveXrays(obj);
+}
+
+/**
+ * Helper function to create a grip from a Map/Set entry
+ */
+function gripFromEntry({ obj, hooks }, entry) {
+ entry = unwaiveXrays(entry);
+ return hooks.createValueGrip(
+ ObjectUtils.makeDebuggeeValueIfNeeded(obj, entry)
+ );
+}
+
+function enumArrayProperties(objectActor, options) {
+ return {
+ size: ObjectUtils.getArrayLength(objectActor.obj),
+ propertyName(index) {
+ return index;
+ },
+ propertyDescription(index) {
+ return objectActor._propertyDescriptor(index);
+ },
+ };
+}
+
+function enumObjectProperties(objectActor, options) {
+ let names = [];
+ try {
+ names = objectActor.obj.getOwnPropertyNames();
+ } catch (ex) {
+ // Calling getOwnPropertyNames() on some wrapped native prototypes is not
+ // allowed: "cannot modify properties of a WrappedNative". See bug 952093.
+ }
+
+ if (options.ignoreNonIndexedProperties || options.ignoreIndexedProperties) {
+ const length = DevToolsUtils.getProperty(objectActor.obj, "length");
+ let sliceIndex;
+
+ const isLengthTrustworthy =
+ isUint32(length) &&
+ (!length || ObjectUtils.isArrayIndex(names[length - 1])) &&
+ !ObjectUtils.isArrayIndex(names[length]);
+
+ if (!isLengthTrustworthy) {
+ // The length property may not reflect what the object looks like, let's find
+ // where indexed properties end.
+
+ if (!ObjectUtils.isArrayIndex(names[0])) {
+ // If the first item is not a number, this means there is no indexed properties
+ // in this object.
+ sliceIndex = 0;
+ } else {
+ sliceIndex = names.length;
+ while (sliceIndex > 0) {
+ if (ObjectUtils.isArrayIndex(names[sliceIndex - 1])) {
+ break;
+ }
+ sliceIndex--;
+ }
+ }
+ } else {
+ sliceIndex = length;
+ }
+
+ // It appears that getOwnPropertyNames always returns indexed properties
+ // first, so we can safely slice `names` for/against indexed properties.
+ // We do such clever operation to optimize very large array inspection.
+ if (options.ignoreIndexedProperties) {
+ // Keep items after `sliceIndex` index
+ names = names.slice(sliceIndex);
+ } else if (options.ignoreNonIndexedProperties) {
+ // Keep `sliceIndex` first items
+ names.length = sliceIndex;
+ }
+ }
+
+ const safeGetterValues = objectActor._findSafeGetterValues(names, 0);
+ const safeGetterNames = Object.keys(safeGetterValues);
+ // Merge the safe getter values into the existing properties list.
+ for (const name of safeGetterNames) {
+ if (!names.includes(name)) {
+ names.push(name);
+ }
+ }
+
+ if (options.query) {
+ let { query } = options;
+ query = query.toLowerCase();
+ names = names.filter(name => {
+ // Filter on attribute names
+ if (name.toLowerCase().includes(query)) {
+ return true;
+ }
+ // and then on attribute values
+ let desc;
+ try {
+ desc = objectActor.obj.getOwnPropertyDescriptor(name);
+ } catch (e) {
+ // Calling getOwnPropertyDescriptor on wrapped native prototypes is not
+ // allowed (bug 560072).
+ }
+ if (desc?.value && String(desc.value).includes(query)) {
+ return true;
+ }
+ return false;
+ });
+ }
+
+ if (options.sort) {
+ names.sort();
+ }
+
+ return {
+ size: names.length,
+ propertyName(index) {
+ return names[index];
+ },
+ propertyDescription(index) {
+ const name = names[index];
+ let desc = objectActor._propertyDescriptor(name);
+ if (!desc) {
+ desc = safeGetterValues[name];
+ } else if (name in safeGetterValues) {
+ // Merge the safe getter values into the existing properties list.
+ const { getterValue, getterPrototypeLevel } = safeGetterValues[name];
+ desc.getterValue = getterValue;
+ desc.getterPrototypeLevel = getterPrototypeLevel;
+ }
+ return desc;
+ },
+ };
+}
+
+function getMapEntries(obj, forPreview) {
+ // Iterating over a Map via .entries goes through various intermediate
+ // objects - an Iterator object, then a 2-element Array object, then the
+ // actual values we care about. We don't have Xrays to Iterator objects,
+ // so we get Opaque wrappers for them. And even though we have Xrays to
+ // Arrays, the semantics often deny access to the entires based on the
+ // nature of the values. So we need waive Xrays for the iterator object
+ // and the tupes, and then re-apply them on the underlying values until
+ // we fix bug 1023984.
+ //
+ // Even then though, we might want to continue waiving Xrays here for the
+ // same reason we do so for Arrays above - this filtering behavior is likely
+ // to be more confusing than beneficial in the case of Object previews.
+ const raw = obj.unsafeDereference();
+ const iterator = obj.makeDebuggeeValue(
+ waiveXrays(Map.prototype.keys.call(raw))
+ );
+ return [...DevToolsUtils.makeDebuggeeIterator(iterator)].map(k => {
+ const key = waiveXrays(ObjectUtils.unwrapDebuggeeValue(k))
+ const value = Map.prototype.get.call(raw, key);
+ return [key, value];
+ });
+}
+
+function enumMapEntries(objectActor, forPreview = false) {
+ const entries = getMapEntries(objectActor.obj, forPreview);
+
+ return {
+ [Symbol.iterator]: function*() {
+ for (const [key, value] of entries) {
+ yield [key, value].map(val => gripFromEntry(objectActor, val));
+ }
+ },
+ size: entries.length,
+ propertyName(index) {
+ return index;
+ },
+ propertyDescription(index) {
+ const [key, val] = entries[index];
+ return {
+ enumerable: true,
+ value: {
+ type: "mapEntry",
+ preview: {
+ key: gripFromEntry(objectActor, key),
+ value: gripFromEntry(objectActor, val),
+ },
+ },
+ };
+ },
+ };
+}
+
+function enumStorageEntries(objectActor) {
+ // Iterating over local / sessionStorage entries goes through various
+ // intermediate objects - an Iterator object, then a 2-element Array object,
+ // then the actual values we care about. We don't have Xrays to Iterator
+ // objects, so we get Opaque wrappers for them.
+ const raw = objectActor.obj.unsafeDereference();
+ const keys = [];
+ for (let i = 0; i < raw.length; i++) {
+ keys.push(raw.key(i));
+ }
+ return {
+ [Symbol.iterator]: function*() {
+ for (const key of keys) {
+ const value = raw.getItem(key);
+ yield [key, value].map(val => gripFromEntry(objectActor, val));
+ }
+ },
+ size: keys.length,
+ propertyName(index) {
+ return index;
+ },
+ propertyDescription(index) {
+ const key = keys[index];
+ const val = raw.getItem(key);
+ return {
+ enumerable: true,
+ value: {
+ type: "storageEntry",
+ preview: {
+ key: gripFromEntry(objectActor, key),
+ value: gripFromEntry(objectActor, val),
+ },
+ },
+ };
+ },
+ };
+}
+
+function getWeakMapEntries(obj, forPreview) {
+ // We currently lack XrayWrappers for WeakMap, so when we iterate over
+ // the values, the temporary iterator objects get created in the target
+ // compartment. However, we _do_ have Xrays to Object now, so we end up
+ // Xraying those temporary objects, and filtering access to |it.value|
+ // based on whether or not it's Xrayable and/or callable, which breaks
+ // the for/of iteration.
+ //
+ // This code is designed to handle untrusted objects, so we can safely
+ // waive Xrays on the iterable, and relying on the Debugger machinery to
+ // make sure we handle the resulting objects carefully.
+ const raw = obj.unsafeDereference();
+ const keys = waiveXrays(ChromeUtils.nondeterministicGetWeakMapKeys(raw));
+
+ return keys.map(k => [k, WeakMap.prototype.get.call(raw, k)]);
+}
+
+function enumWeakMapEntries(objectActor, forPreview = false) {
+ const entries = getWeakMapEntries(objectActor.obj, forPreview);
+
+ return {
+ [Symbol.iterator]: function*() {
+ for (let i = 0; i < entries.length; i++) {
+ yield entries[i].map(val => gripFromEntry(objectActor, val));
+ }
+ },
+ size: entries.length,
+ propertyName(index) {
+ return index;
+ },
+ propertyDescription(index) {
+ const [key, val] = entries[index];
+ return {
+ enumerable: true,
+ value: {
+ type: "mapEntry",
+ preview: {
+ key: gripFromEntry(objectActor, key),
+ value: gripFromEntry(objectActor, val),
+ },
+ },
+ };
+ },
+ };
+}
+
+function getSetValues(obj, forPreview) {
+ // We currently lack XrayWrappers for Set, so when we iterate over
+ // the values, the temporary iterator objects get created in the target
+ // compartment. However, we _do_ have Xrays to Object now, so we end up
+ // Xraying those temporary objects, and filtering access to |it.value|
+ // based on whether or not it's Xrayable and/or callable, which breaks
+ // the for/of iteration.
+ //
+ // This code is designed to handle untrusted objects, so we can safely
+ // waive Xrays on the iterable, and relying on the Debugger machinery to
+ // make sure we handle the resulting objects carefully.
+ const raw = obj.unsafeDereference();
+ const iterator = obj.makeDebuggeeValue(
+ waiveXrays(Set.prototype.values.call(raw))
+ );
+ return [...DevToolsUtils.makeDebuggeeIterator(iterator)];
+}
+
+function enumSetEntries(objectActor, forPreview = false) {
+ const values = getSetValues(objectActor.obj, forPreview).map(v =>
+ waiveXrays(ObjectUtils.unwrapDebuggeeValue(v))
+ );
+
+ return {
+ [Symbol.iterator]: function*() {
+ for (const item of values) {
+ yield gripFromEntry(objectActor, item);
+ }
+ },
+ size: values.length,
+ propertyName(index) {
+ return index;
+ },
+ propertyDescription(index) {
+ const val = values[index];
+ return {
+ enumerable: true,
+ value: gripFromEntry(objectActor, val),
+ };
+ },
+ };
+}
+
+function getWeakSetEntries(obj, forPreview) {
+ // We currently lack XrayWrappers for WeakSet, so when we iterate over
+ // the values, the temporary iterator objects get created in the target
+ // compartment. However, we _do_ have Xrays to Object now, so we end up
+ // Xraying those temporary objects, and filtering access to |it.value|
+ // based on whether or not it's Xrayable and/or callable, which breaks
+ // the for/of iteration.
+ //
+ // This code is designed to handle untrusted objects, so we can safely
+ // waive Xrays on the iterable, and relying on the Debugger machinery to
+ // make sure we handle the resulting objects carefully.
+ const raw = obj.unsafeDereference();
+ return waiveXrays(ChromeUtils.nondeterministicGetWeakSetKeys(raw));
+}
+
+function enumWeakSetEntries(objectActor, forPreview = false) {
+ const keys = getWeakSetEntries(objectActor.obj, forPreview);
+
+ return {
+ [Symbol.iterator]: function*() {
+ for (const item of keys) {
+ yield gripFromEntry(objectActor, item);
+ }
+ },
+ size: keys.length,
+ propertyName(index) {
+ return index;
+ },
+ propertyDescription(index) {
+ const val = keys[index];
+ return {
+ enumerable: true,
+ value: gripFromEntry(objectActor, val),
+ };
+ },
+ };
+}
+
+/**
+ * Returns true if the parameter can be stored as a 32-bit unsigned integer.
+ * If so, it will be suitable for use as the length of an array object.
+ *
+ * @param num Number
+ * The number to test.
+ * @return Boolean
+ */
+function isUint32(num) {
+ return num >>> 0 === num;
+}
+
+module.exports = {
+ PropertyIteratorActor,
+ enumMapEntries,
+ enumSetEntries,
+ enumWeakMapEntries,
+ enumWeakSetEntries,
+};
diff --git a/devtools/server/actors/object/stringifiers.js b/devtools/server/actors/object/stringifiers.js
new file mode 100644
index 0000000000..2b0fab0fe6
--- /dev/null
+++ b/devtools/server/actors/object/stringifiers.js
@@ -0,0 +1,198 @@
+/* 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";
+
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+
+loader.lazyRequireGetter(
+ this,
+ "ObjectUtils",
+ "devtools/server/actors/object/utils"
+);
+
+/**
+ * Stringify a Debugger.Object based on its class.
+ *
+ * @param Debugger.Object obj
+ * The object to stringify.
+ * @return String
+ * The stringification for the object.
+ */
+function stringify(obj) {
+ if (!DevToolsUtils.isSafeDebuggerObject(obj)) {
+ const unwrapped = DevToolsUtils.unwrap(obj);
+ if (unwrapped === undefined) {
+ return "<invisibleToDebugger>";
+ } else if (unwrapped.isProxy) {
+ return "<proxy>";
+ }
+ // The following line should not be reached. It's there just in case somebody
+ // modifies isSafeDebuggerObject to return false for additional kinds of objects.
+ return "[object " + obj.class + "]";
+ } else if (obj.class == "DeadObject") {
+ return "<dead object>";
+ }
+
+ const stringifier = stringifiers[obj.class] || stringifiers.Object;
+
+ try {
+ return stringifier(obj);
+ } catch (e) {
+ DevToolsUtils.reportException("stringify", e);
+ return "<failed to stringify object>";
+ }
+}
+
+/**
+ * Create a function that can safely stringify Debugger.Objects of a given
+ * builtin type.
+ *
+ * @param Function ctor
+ * The builtin class constructor.
+ * @return Function
+ * The stringifier for the class.
+ */
+function createBuiltinStringifier(ctor) {
+ return obj => {
+ try {
+ return ctor.prototype.toString.call(obj.unsafeDereference());
+ } catch (err) {
+ // The debuggee will see a "Function" class if the object is callable and
+ // its compartment is not subsumed. The above will throw if it's not really
+ // a function, e.g. if it's a callable proxy.
+ return "[object " + obj.class + "]";
+ }
+ };
+}
+
+/**
+ * Stringify a Debugger.Object-wrapped Error instance.
+ *
+ * @param Debugger.Object obj
+ * The object to stringify.
+ * @return String
+ * The stringification of the object.
+ */
+function errorStringify(obj) {
+ let name = DevToolsUtils.getProperty(obj, "name");
+ if (name === "" || name === undefined) {
+ name = obj.class;
+ } else if (isObject(name)) {
+ name = stringify(name);
+ }
+
+ let message = DevToolsUtils.getProperty(obj, "message");
+ if (isObject(message)) {
+ message = stringify(message);
+ }
+
+ if (message === "" || message === undefined) {
+ return name;
+ }
+ return name + ": " + message;
+}
+
+// Used to prevent infinite recursion when an array is found inside itself.
+var seen = null;
+
+var stringifiers = {
+ Error: errorStringify,
+ EvalError: errorStringify,
+ RangeError: errorStringify,
+ ReferenceError: errorStringify,
+ SyntaxError: errorStringify,
+ TypeError: errorStringify,
+ URIError: errorStringify,
+ Boolean: createBuiltinStringifier(Boolean),
+ Function: createBuiltinStringifier(Function),
+ Number: createBuiltinStringifier(Number),
+ RegExp: createBuiltinStringifier(RegExp),
+ String: createBuiltinStringifier(String),
+ Object: obj => "[object " + obj.class + "]",
+ Array: obj => {
+ // If we're at the top level then we need to create the Set for tracking
+ // previously stringified arrays.
+ const topLevel = !seen;
+ if (topLevel) {
+ seen = new Set();
+ } else if (seen.has(obj)) {
+ return "";
+ }
+
+ seen.add(obj);
+
+ const len = ObjectUtils.getArrayLength(obj);
+ let string = "";
+
+ // Array.length is always a non-negative safe integer.
+ for (let i = 0; i < len; i++) {
+ const desc = obj.getOwnPropertyDescriptor(i);
+ if (desc) {
+ const { value } = desc;
+ if (value != null) {
+ string += isObject(value) ? stringify(value) : value;
+ }
+ }
+
+ if (i < len - 1) {
+ string += ",";
+ }
+ }
+
+ if (topLevel) {
+ seen = null;
+ }
+
+ return string;
+ },
+ DOMException: obj => {
+ const message = DevToolsUtils.getProperty(obj, "message") || "<no message>";
+ const result = (+DevToolsUtils.getProperty(obj, "result")).toString(16);
+ const code = DevToolsUtils.getProperty(obj, "code");
+ const name = DevToolsUtils.getProperty(obj, "name") || "<unknown>";
+
+ return (
+ '[Exception... "' +
+ message +
+ '" ' +
+ 'code: "' +
+ code +
+ '" ' +
+ 'nsresult: "0x' +
+ result +
+ " (" +
+ name +
+ ')"]'
+ );
+ },
+ Promise: obj => {
+ const { state, value, reason } = ObjectUtils.getPromiseState(obj);
+ let statePreview = state;
+ if (state != "pending") {
+ const settledValue = state === "fulfilled" ? value : reason;
+ statePreview +=
+ ": " +
+ (typeof settledValue === "object" && settledValue !== null
+ ? stringify(settledValue)
+ : settledValue);
+ }
+ return "Promise (" + statePreview + ")";
+ },
+};
+
+/**
+ * Determine if a given value is non-primitive.
+ *
+ * @param Any value
+ * The value to test.
+ * @return Boolean
+ * Whether the value is non-primitive.
+ */
+function isObject(value) {
+ const type = typeof value;
+ return type == "object" ? value !== null : type == "function";
+}
+
+module.exports = stringify;
diff --git a/devtools/server/actors/object/symbol-iterator.js b/devtools/server/actors/object/symbol-iterator.js
new file mode 100644
index 0000000000..5982de2aca
--- /dev/null
+++ b/devtools/server/actors/object/symbol-iterator.js
@@ -0,0 +1,66 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { symbolIteratorSpec } = require("devtools/shared/specs/symbol-iterator");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+
+/**
+ * Creates an actor to iterate over an object's symbols.
+ *
+ * @param objectActor ObjectActor
+ * The object actor.
+ */
+const SymbolIteratorActor = protocol.ActorClassWithSpec(symbolIteratorSpec, {
+ initialize(objectActor, conn) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+
+ let symbols = [];
+ if (DevToolsUtils.isSafeDebuggerObject(objectActor.obj)) {
+ try {
+ symbols = objectActor.obj.getOwnPropertySymbols();
+ } catch (err) {
+ // The above can throw when the debuggee does not subsume the object's
+ // compartment, or for some WrappedNatives like Cu.Sandbox.
+ }
+ }
+
+ this.iterator = {
+ size: symbols.length,
+ symbolDescription(index) {
+ const symbol = symbols[index];
+ return {
+ name: symbol.toString(),
+ descriptor: objectActor._propertyDescriptor(symbol),
+ };
+ },
+ };
+ },
+
+ form() {
+ return {
+ type: this.typeName,
+ actor: this.actorID,
+ count: this.iterator.size,
+ };
+ },
+
+ slice({ start, count }) {
+ const ownSymbols = [];
+ for (let i = start, m = start + count; i < m; i++) {
+ ownSymbols.push(this.iterator.symbolDescription(i));
+ }
+ return {
+ ownSymbols,
+ };
+ },
+
+ all() {
+ return this.slice({ start: 0, count: this.iterator.size });
+ },
+});
+
+exports.SymbolIteratorActor = SymbolIteratorActor;
diff --git a/devtools/server/actors/object/symbol.js b/devtools/server/actors/object/symbol.js
new file mode 100644
index 0000000000..f75a844ca2
--- /dev/null
+++ b/devtools/server/actors/object/symbol.js
@@ -0,0 +1,109 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { symbolSpec } = require("devtools/shared/specs/symbol");
+loader.lazyRequireGetter(
+ this,
+ "createValueGrip",
+ "devtools/server/actors/object/utils",
+ true
+);
+
+/**
+ * Creates an actor for the specified symbol.
+ *
+ * @param {DevToolsServerConnection} conn: The connection to the client.
+ * @param {Symbol} symbol: The symbol we want to create an actor for.
+ */
+const SymbolActor = protocol.ActorClassWithSpec(symbolSpec, {
+ initialize(conn, symbol) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.symbol = symbol;
+ },
+
+ rawValue: function() {
+ return this.symbol;
+ },
+
+ destroy: function() {
+ // Because symbolActors is not a weak map, we won't automatically leave
+ // it so we need to manually leave on destroy so that we don't leak
+ // memory.
+ this._releaseActor();
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Returns a grip for this actor for returning in a protocol message.
+ */
+ form: function() {
+ const form = {
+ type: this.typeName,
+ actor: this.actorID,
+ };
+ const name = getSymbolName(this.symbol);
+ if (name !== undefined) {
+ // Create a grip for the name because it might be a longString.
+ form.name = createValueGrip(name, this.getParent());
+ }
+ return form;
+ },
+
+ /**
+ * Handle a request to release this SymbolActor instance.
+ */
+ release: function() {
+ // TODO: also check if this.getParent() === threadActor.threadLifetimePool
+ // when the web console moves away from manually releasing pause-scoped
+ // actors.
+ this._releaseActor();
+ this.destroy();
+ return {};
+ },
+
+ _releaseActor: function() {
+ const parent = this.getParent();
+ if (parent && parent.symbolActors) {
+ delete parent.symbolActors[this.symbol];
+ }
+ },
+});
+
+const symbolProtoToString = Symbol.prototype.toString;
+
+function getSymbolName(symbol) {
+ const name = symbolProtoToString.call(symbol).slice("Symbol(".length, -1);
+ return name || undefined;
+}
+
+/**
+ * Create a grip for the given symbol.
+ *
+ * @param sym Symbol
+ * The symbol we are creating a grip for.
+ * @param pool Pool
+ * The actor pool where the new actor will be added.
+ */
+function symbolGrip(sym, pool) {
+ if (!pool.symbolActors) {
+ pool.symbolActors = Object.create(null);
+ }
+
+ if (sym in pool.symbolActors) {
+ return pool.symbolActors[sym].form();
+ }
+
+ const actor = new SymbolActor(pool.conn, sym);
+ pool.manage(actor);
+ pool.symbolActors[sym] = actor;
+ return actor.form();
+}
+
+module.exports = {
+ SymbolActor,
+ symbolGrip,
+};
diff --git a/devtools/server/actors/object/utils.js b/devtools/server/actors/object/utils.js
new file mode 100644
index 0000000000..5d943bfd72
--- /dev/null
+++ b/devtools/server/actors/object/utils.js
@@ -0,0 +1,541 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const { assert } = DevToolsUtils;
+
+loader.lazyRequireGetter(
+ this,
+ "LongStringActor",
+ "devtools/server/actors/string",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "symbolGrip",
+ "devtools/server/actors/object/symbol",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "ObjectActor",
+ "devtools/server/actors/object",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "EnvironmentActor",
+ "devtools/server/actors/environment",
+ true
+);
+
+/**
+ * Get thisDebugger.Object referent's `promiseState`.
+ *
+ * @returns Object
+ * An object of one of the following forms:
+ * - { state: "pending" }
+ * - { state: "fulfilled", value }
+ * - { state: "rejected", reason }
+ */
+function getPromiseState(obj) {
+ if (obj.class != "Promise") {
+ throw new Error(
+ "Can't call `getPromiseState` on `Debugger.Object`s that don't " +
+ "refer to Promise objects."
+ );
+ }
+
+ const state = { state: obj.promiseState };
+ if (state.state === "fulfilled") {
+ state.value = obj.promiseValue;
+ } else if (state.state === "rejected") {
+ state.reason = obj.promiseReason;
+ }
+ return state;
+}
+
+/**
+ * Returns true if value is an object or function
+ *
+ * @param value
+ * @returns {boolean}
+ */
+
+function isObjectOrFunction(value) {
+ return value && (typeof value == "object" || typeof value == "function");
+}
+
+/**
+ * Make a debuggee value for the given object, if needed. Primitive values
+ * are left the same.
+ *
+ * Use case: you have a raw JS object (after unsafe dereference) and you want to
+ * send it to the client. In that case you need to use an ObjectActor which
+ * requires a debuggee value. The Debugger.Object.prototype.makeDebuggeeValue()
+ * method works only for JS objects and functions.
+ *
+ * @param Debugger.Object obj
+ * @param any value
+ * @return object
+ */
+function makeDebuggeeValueIfNeeded(obj, value) {
+ if (isObjectOrFunction(value)) {
+ return obj.makeDebuggeeValue(value);
+ }
+ return value;
+}
+
+/**
+ * Convert a debuggee value into the underlying raw object, if needed.
+ */
+function unwrapDebuggeeValue(value) {
+ if (value && typeof value == "object") {
+ return value.unsafeDereference();
+ }
+ return value;
+}
+
+/**
+ * Create a grip for the given debuggee value. If the value is an object or a long string,
+ * it will create an actor and add it to the pool
+ * @param {any} value: The debuggee value.
+ * @param {Pool} pool: The pool where the created actor will be added.
+ * @param {Function} makeObjectGrip: Function that will be called to create the grip for
+ * non-primitive values.
+ */
+function createValueGrip(value, pool, makeObjectGrip) {
+ switch (typeof value) {
+ case "boolean":
+ return value;
+
+ case "string":
+ if (stringIsLong(value)) {
+ for (const child of pool.poolChildren()) {
+ if (child instanceof LongStringActor && child.str == value) {
+ return child.form();
+ }
+ }
+
+ const actor = new LongStringActor(pool.conn, value);
+ pool.manage(actor);
+ return actor.form();
+ }
+ return value;
+
+ case "number":
+ if (value === Infinity) {
+ return { type: "Infinity" };
+ } else if (value === -Infinity) {
+ return { type: "-Infinity" };
+ } else if (Number.isNaN(value)) {
+ return { type: "NaN" };
+ } else if (!value && 1 / value === -Infinity) {
+ return { type: "-0" };
+ }
+ return value;
+
+ case "bigint":
+ return {
+ type: "BigInt",
+ text: value.toString(),
+ };
+
+ case "undefined":
+ return { type: "undefined" };
+
+ case "object":
+ if (value === null) {
+ return { type: "null" };
+ } else if (
+ value.optimizedOut ||
+ value.uninitialized ||
+ value.missingArguments
+ ) {
+ // The slot is optimized out, an uninitialized binding, or
+ // arguments on a dead scope
+ return {
+ type: "null",
+ optimizedOut: value.optimizedOut,
+ uninitialized: value.uninitialized,
+ missingArguments: value.missingArguments,
+ };
+ }
+ return makeObjectGrip(value, pool);
+
+ case "symbol":
+ return symbolGrip(value, pool);
+
+ default:
+ assert(false, "Failed to provide a grip for: " + value);
+ return null;
+ }
+}
+
+/**
+ * of passing the value directly over the protocol.
+ *
+ * @param str String
+ * The string we are checking the length of.
+ */
+function stringIsLong(str) {
+ return str.length >= DevToolsServer.LONG_STRING_LENGTH;
+}
+
+const TYPED_ARRAY_CLASSES = [
+ "Uint8Array",
+ "Uint8ClampedArray",
+ "Uint16Array",
+ "Uint32Array",
+ "Int8Array",
+ "Int16Array",
+ "Int32Array",
+ "Float32Array",
+ "Float64Array",
+ "BigInt64Array",
+ "BigUint64Array",
+];
+
+/**
+ * Returns true if a debuggee object is a typed array.
+ *
+ * @param obj Debugger.Object
+ * The debuggee object to test.
+ * @return Boolean
+ */
+function isTypedArray(object) {
+ return TYPED_ARRAY_CLASSES.includes(object.class);
+}
+
+/**
+ * Returns true if a debuggee object is an array, including a typed array.
+ *
+ * @param obj Debugger.Object
+ * The debuggee object to test.
+ * @return Boolean
+ */
+function isArray(object) {
+ return isTypedArray(object) || object.class === "Array";
+}
+
+/**
+ * Returns the length of an array (or typed array).
+ *
+ * @param object Debugger.Object
+ * The debuggee object of the array.
+ * @return Number
+ * @throws if the object is not an array.
+ */
+function getArrayLength(object) {
+ if (!isArray(object)) {
+ throw new Error("Expected an array, got a " + object.class);
+ }
+
+ // Real arrays have a reliable `length` own property.
+ if (object.class === "Array") {
+ return DevToolsUtils.getProperty(object, "length");
+ }
+
+ // For typed arrays, `DevToolsUtils.getProperty` is not reliable because the `length`
+ // getter could be shadowed by an own property, and `getOwnPropertyNames` is
+ // unnecessarily slow. Obtain the `length` getter safely and call it manually.
+ const typedProto = Object.getPrototypeOf(Uint8Array.prototype);
+ const getter = Object.getOwnPropertyDescriptor(typedProto, "length").get;
+ return getter.call(object.unsafeDereference());
+}
+
+/**
+ * Returns true if the parameter is suitable to be an array index.
+ *
+ * @param str String
+ * @return Boolean
+ */
+function isArrayIndex(str) {
+ // Transform the parameter to a 32-bit unsigned integer.
+ const num = str >>> 0;
+ // Check that the parameter is a canonical Uint32 index.
+ return (
+ num + "" === str &&
+ // Array indices cannot attain the maximum Uint32 value.
+ num != -1 >>> 0
+ );
+}
+
+/**
+ * Returns true if a debuggee object is a local or sessionStorage object.
+ *
+ * @param object Debugger.Object
+ * The debuggee object to test.
+ * @return Boolean
+ */
+function isStorage(object) {
+ return object.class === "Storage";
+}
+
+/**
+ * Returns the length of a local or sessionStorage object.
+ *
+ * @param object Debugger.Object
+ * The debuggee object of the array.
+ * @return Number
+ * @throws if the object is not a local or sessionStorage object.
+ */
+function getStorageLength(object) {
+ if (!isStorage(object)) {
+ throw new Error("Expected a storage object, got a " + object.class);
+ }
+ return DevToolsUtils.getProperty(object, "length");
+}
+
+/**
+ * Returns an array of properties based on event class name.
+ *
+ * @param className
+ * @returns {Array}
+ */
+function getPropsForEvent(className) {
+ const positionProps = ["buttons", "clientX", "clientY", "layerX", "layerY"];
+ const eventToPropsMap = {
+ MouseEvent: positionProps,
+ DragEvent: positionProps,
+ PointerEvent: positionProps,
+ SimpleGestureEvent: positionProps,
+ WheelEvent: positionProps,
+ KeyboardEvent: ["key", "charCode", "keyCode"],
+ TransitionEvent: ["propertyName", "pseudoElement"],
+ AnimationEvent: ["animationName", "pseudoElement"],
+ ClipboardEvent: ["clipboardData"],
+ };
+
+ if (className in eventToPropsMap) {
+ return eventToPropsMap[className];
+ }
+
+ return [];
+}
+
+/**
+ * Returns an array of of all properties of an object
+ *
+ * @param obj
+ * @param rawObj
+ * @returns {Array}
+ */
+function getPropNamesFromObject(obj, rawObj) {
+ let names = [];
+
+ try {
+ if (isStorage(obj)) {
+ // local and session storage cannot be iterated over using
+ // Object.getOwnPropertyNames() because it skips keys that are duplicated
+ // on the prototype e.g. "key", "getKeys" so we need to gather the real
+ // keys using the storage.key() function.
+ for (let j = 0; j < rawObj.length; j++) {
+ names.push(rawObj.key(j));
+ }
+ } else {
+ names = obj.getOwnPropertyNames();
+ }
+ } catch (ex) {
+ // Calling getOwnPropertyNames() on some wrapped native prototypes is not
+ // allowed: "cannot modify properties of a WrappedNative". See bug 952093.
+ }
+
+ return names;
+}
+
+/**
+ * Returns an array of all symbol properties of an object
+ *
+ * @param obj
+ * @returns {Array}
+ */
+function getSafeOwnPropertySymbols(obj) {
+ try {
+ return obj.getOwnPropertySymbols();
+ } catch (ex) {
+ return [];
+ }
+}
+
+/**
+ * Returns an array modifiers based on keys
+ *
+ * @param rawObj
+ * @returns {Array}
+ */
+function getModifiersForEvent(rawObj) {
+ const modifiers = [];
+ const keysToModifiersMap = {
+ altKey: "Alt",
+ ctrlKey: "Control",
+ metaKey: "Meta",
+ shiftKey: "Shift",
+ };
+
+ for (const key in keysToModifiersMap) {
+ if (keysToModifiersMap.hasOwnProperty(key) && rawObj[key]) {
+ modifiers.push(keysToModifiersMap[key]);
+ }
+ }
+
+ return modifiers;
+}
+
+/**
+ * Make a debuggee value for the given value.
+ *
+ * @param TargetActor targetActor
+ * The Target Actor from which this object originates.
+ * @param mixed value
+ * The value you want to get a debuggee value for.
+ * @return object
+ * Debuggee value for |value|.
+ */
+function makeDebuggeeValue(targetActor, value) {
+ if (isObject(value)) {
+ try {
+ const global = Cu.getGlobalForObject(value);
+ const dbgGlobal = targetActor.dbg.makeGlobalObjectReference(global);
+ return dbgGlobal.makeDebuggeeValue(value);
+ } catch (ex) {
+ // The above can throw an exception if value is not an actual object
+ // or 'Object in compartment marked as invisible to Debugger'
+ }
+ }
+ const dbgGlobal = targetActor.dbg.makeGlobalObjectReference(
+ targetActor.window || targetActor.workerGlobal
+ );
+ return dbgGlobal.makeDebuggeeValue(value);
+}
+
+function isObject(value) {
+ return Object(value) === value;
+}
+
+/**
+ * Create a grip for the given string.
+ *
+ * @param TargetActor targetActor
+ * The Target Actor from which this object originates.
+ */
+function createStringGrip(targetActor, string) {
+ if (string && stringIsLong(string)) {
+ const actor = new LongStringActor(targetActor.conn, string);
+ targetActor.manage(actor);
+ return actor.form();
+ }
+ return string;
+}
+
+/**
+ * Create a grip for the given value.
+ *
+ * @param TargetActor targetActor
+ * The Target Actor from which this object originates.
+ * @param mixed value
+ * The value you want to get a debuggee value for.
+ * @param Number depth
+ * Depth of the object compared to the top level object,
+ * when we are inspecting nested attributes.
+ * @return object
+ */
+function createValueGripForTarget(targetActor, value, depth = 0) {
+ return createValueGrip(
+ value,
+ targetActor,
+ createObjectGrip.bind(null, targetActor, depth)
+ );
+}
+
+/**
+ * Create and return an environment actor that corresponds to the provided
+ * Debugger.Environment. This is a straightforward clone of the ThreadActor's
+ * method except that it stores the environment actor in the web console
+ * actor's pool.
+ *
+ * @param Debugger.Environment environment
+ * The lexical environment we want to extract.
+ * @param TargetActor targetActor
+ * The Target Actor to use as parent actor.
+ * @return The EnvironmentActor for |environment| or |undefined| for host
+ * functions or functions scoped to a non-debuggee global.
+ */
+function createEnvironmentActor(environment, targetActor) {
+ if (!environment) {
+ return undefined;
+ }
+
+ if (environment.actor) {
+ return environment.actor;
+ }
+
+ const actor = new EnvironmentActor(environment, targetActor);
+ targetActor.manage(actor);
+ environment.actor = actor;
+
+ return actor;
+}
+
+/**
+ * Create a grip for the given object.
+ *
+ * @param TargetActor targetActor
+ * The Target Actor from which this object originates.
+ * @param Number depth
+ * Depth of the object compared to the top level object,
+ * when we are inspecting nested attributes.
+ * @param object object
+ * The object you want.
+ * @param object pool
+ * A Pool where the new actor instance is added.
+ * @param object
+ * The object grip.
+ */
+function createObjectGrip(targetActor, depth, object, pool) {
+ let gripDepth = depth;
+ const actor = new ObjectActor(
+ object,
+ {
+ thread: targetActor.threadActor,
+ getGripDepth: () => gripDepth,
+ incrementGripDepth: () => gripDepth++,
+ decrementGripDepth: () => gripDepth--,
+ createValueGrip: v => createValueGripForTarget(targetActor, v, gripDepth),
+ createEnvironmentActor: env => createEnvironmentActor(env, targetActor),
+ },
+ targetActor.conn
+ );
+ pool.manage(actor);
+ return actor.form();
+}
+
+module.exports = {
+ getPromiseState,
+ makeDebuggeeValueIfNeeded,
+ unwrapDebuggeeValue,
+ createValueGrip,
+ stringIsLong,
+ isTypedArray,
+ isArray,
+ isStorage,
+ getArrayLength,
+ getStorageLength,
+ isArrayIndex,
+ getPropsForEvent,
+ getPropNamesFromObject,
+ getSafeOwnPropertySymbols,
+ getModifiersForEvent,
+ isObjectOrFunction,
+ createStringGrip,
+ makeDebuggeeValue,
+ createValueGripForTarget,
+};
diff --git a/devtools/server/actors/page-style.js b/devtools/server/actors/page-style.js
new file mode 100644
index 0000000000..6340886d8a
--- /dev/null
+++ b/devtools/server/actors/page-style.js
@@ -0,0 +1,1408 @@
+/* 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";
+
+const Services = require("Services");
+const protocol = require("devtools/shared/protocol");
+const { getCSSLexer } = require("devtools/shared/css/lexer");
+const { LongStringActor } = require("devtools/server/actors/string");
+const InspectorUtils = require("InspectorUtils");
+const TrackChangeEmitter = require("devtools/server/actors/utils/track-change-emitter");
+
+const { pageStyleSpec } = require("devtools/shared/specs/page-style");
+const {
+ style: { ELEMENT_STYLE },
+} = require("devtools/shared/constants");
+
+const {
+ TYPES,
+ getResourceWatcher,
+} = require("devtools/server/actors/resources/index");
+
+loader.lazyRequireGetter(
+ this,
+ "StyleRuleActor",
+ "devtools/server/actors/style-rule",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "getFontPreviewData",
+ "devtools/server/actors/utils/style-utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "SharedCssLogic",
+ "devtools/shared/inspector/css-logic"
+);
+loader.lazyRequireGetter(
+ this,
+ "getDefinedGeometryProperties",
+ "devtools/server/actors/highlighters/geometry-editor",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "UPDATE_GENERAL",
+ "devtools/server/actors/style-sheet",
+ true
+);
+
+loader.lazyGetter(this, "PSEUDO_ELEMENTS", () => {
+ return InspectorUtils.getCSSPseudoElementNames();
+});
+loader.lazyGetter(this, "FONT_VARIATIONS_ENABLED", () => {
+ return Services.prefs.getBoolPref("layout.css.font-variations.enabled");
+});
+
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+const NORMAL_FONT_WEIGHT = 400;
+const BOLD_FONT_WEIGHT = 700;
+
+/**
+ * The PageStyle actor lets the client look at the styles on a page, as
+ * they are applied to a given node.
+ */
+var PageStyleActor = protocol.ActorClassWithSpec(pageStyleSpec, {
+ /**
+ * Create a PageStyleActor.
+ *
+ * @param inspector
+ * The InspectorActor that owns this PageStyleActor.
+ *
+ * @constructor
+ */
+ initialize: function(inspector) {
+ protocol.Actor.prototype.initialize.call(this, null);
+ this.inspector = inspector;
+ if (!this.inspector.walker) {
+ throw Error(
+ "The inspector's WalkerActor must be created before " +
+ "creating a PageStyleActor."
+ );
+ }
+ this.walker = inspector.walker;
+ this.cssLogic = new CssLogic();
+
+ // Stores the association of DOM objects -> actors
+ this.refMap = new Map();
+
+ // Latest node queried for its applied styles.
+ this.selectedElement = null;
+
+ // Maps document elements to style elements, used to add new rules.
+ this.styleElements = new WeakMap();
+
+ this.onFrameUnload = this.onFrameUnload.bind(this);
+ this.onStyleSheetAdded = this.onStyleSheetAdded.bind(this);
+
+ this.inspector.targetActor.on("will-navigate", this.onFrameUnload);
+ this.inspector.targetActor.on("stylesheet-added", this.onStyleSheetAdded);
+
+ this._observedRules = [];
+ this._styleApplied = this._styleApplied.bind(this);
+ this._watchedSheets = new Set();
+
+ const watcher = getResourceWatcher(
+ this.inspector.targetActor,
+ TYPES.STYLESHEET
+ );
+
+ if (watcher) {
+ this.styleSheetWatcher = watcher;
+ this.onResourceUpdated = this.onResourceUpdated.bind(this);
+ this.inspector.targetActor.on(
+ "resource-updated-form",
+ this.onResourceUpdated
+ );
+ }
+ },
+
+ destroy: function() {
+ if (!this.walker) {
+ return;
+ }
+ protocol.Actor.prototype.destroy.call(this);
+ this.inspector.targetActor.off("will-navigate", this.onFrameUnload);
+ this.inspector.targetActor.off("stylesheet-added", this.onStyleSheetAdded);
+ this.inspector = null;
+ this.walker = null;
+ this.refMap = null;
+ this.selectedElement = null;
+ this.cssLogic = null;
+ this.styleElements = null;
+
+ for (const sheet of this._watchedSheets) {
+ sheet.off("style-applied", this._styleApplied);
+ }
+
+ this._observedRules = [];
+ this._watchedSheets.clear();
+ },
+
+ get conn() {
+ return this.inspector.conn;
+ },
+
+ get ownerWindow() {
+ return this.inspector.targetActor.window;
+ },
+
+ form: function() {
+ // We need to use CSS from the inspected window in order to use CSS.supports() and
+ // detect the right platform features from there.
+ const CSS = this.inspector.targetActor.window.CSS;
+
+ return {
+ actor: this.actorID,
+ traits: {
+ // Whether the page supports values of font-stretch from CSS Fonts Level 4.
+ fontStretchLevel4: CSS.supports("font-stretch: 100%"),
+ // Whether the page supports values of font-style from CSS Fonts Level 4.
+ fontStyleLevel4: CSS.supports("font-style: oblique 20deg"),
+ // Whether getAllUsedFontFaces/getUsedFontFaces accepts the includeVariations
+ // argument.
+ fontVariations: FONT_VARIATIONS_ENABLED,
+ // Whether the page supports values of font-weight from CSS Fonts Level 4.
+ // font-weight at CSS Fonts Level 4 accepts values in increments of 1 rather
+ // than 100. However, CSS.supports() returns false positives, so we guard with the
+ // expected support of font-stretch at CSS Fonts Level 4.
+ fontWeightLevel4:
+ CSS.supports("font-weight: 1") && CSS.supports("font-stretch: 100%"),
+ },
+ };
+ },
+
+ /**
+ * Called when a style sheet is updated.
+ */
+ _styleApplied: function(kind, styleSheet) {
+ // No matter what kind of update is done, we need to invalidate
+ // the keyframe cache.
+ this.cssLogic.reset();
+ if (kind === UPDATE_GENERAL) {
+ this.emit("stylesheet-updated");
+ }
+ },
+
+ /**
+ * Return or create a StyleRuleActor for the given item.
+ * @param item Either a CSSStyleRule or a DOM element.
+ */
+ _styleRef: function(item) {
+ if (this.refMap.has(item)) {
+ return this.refMap.get(item);
+ }
+ const actor = StyleRuleActor(this, item);
+ this.manage(actor);
+ this.refMap.set(item, actor);
+
+ return actor;
+ },
+
+ /**
+ * Update the association between a StyleRuleActor and its
+ * corresponding item. This is used when a StyleRuleActor updates
+ * as style sheet and starts using a new rule.
+ *
+ * @param oldItem The old association; either a CSSStyleRule or a
+ * DOM element.
+ * @param item Either a CSSStyleRule or a DOM element.
+ * @param actor a StyleRuleActor
+ */
+ updateStyleRef: function(oldItem, item, actor) {
+ this.refMap.delete(oldItem);
+ this.refMap.set(item, actor);
+ },
+
+ /**
+ * Return or create a StyleSheetActor for the given CSSStyleSheet.
+ * @param {CSSStyleSheet} sheet
+ * The style sheet to create an actor for.
+ * @return {StyleSheetActor}
+ * The actor for this style sheet
+ */
+ _sheetRef: function(sheet) {
+ if (this.styleSheetWatcher) {
+ // We need to clean up this function in bug 1672090 when server-side stylesheet
+ // watcher is enabled.
+ console.warn(
+ "This function should not be called when server-side stylesheet watcher is enabled"
+ );
+ }
+
+ const targetActor = this.inspector.targetActor;
+ const actor = targetActor.createStyleSheetActor(sheet);
+ return actor;
+ },
+
+ /**
+ * Get the StyleRuleActor matching the given rule id or null if no match is found.
+ *
+ * @param {String} ruleId
+ * Actor ID of the StyleRuleActor
+ * @return {StyleRuleActor|null}
+ */
+ getRule: function(ruleId) {
+ let match = null;
+
+ for (const actor of this.refMap.values()) {
+ if (actor.actorID === ruleId) {
+ match = actor;
+ continue;
+ }
+ }
+
+ return match;
+ },
+
+ /**
+ * Get the computed style for a node.
+ *
+ * @param NodeActor node
+ * @param object options
+ * `filter`: A string filter that affects the "matched" handling.
+ * 'user': Include properties from user style sheets.
+ * 'ua': Include properties from user and user-agent sheets.
+ * Default value is 'ua'
+ * `markMatched`: true if you want the 'matched' property to be added
+ * when a computed property has been modified by a style included
+ * by `filter`.
+ * `onlyMatched`: true if unmatched properties shouldn't be included.
+ * `filterProperties`: An array of properties names that you would like
+ * returned.
+ *
+ * @returns a JSON blob with the following form:
+ * {
+ * "property-name": {
+ * value: "property-value",
+ * priority: "!important" <optional>
+ * matched: <true if there are matched selectors for this value>
+ * },
+ * ...
+ * }
+ */
+ getComputed: function(node, options) {
+ const ret = Object.create(null);
+
+ this.cssLogic.sourceFilter = options.filter || SharedCssLogic.FILTER.UA;
+ this.cssLogic.highlight(node.rawNode);
+ const computed = this.cssLogic.computedStyle || [];
+
+ Array.prototype.forEach.call(computed, name => {
+ if (
+ Array.isArray(options.filterProperties) &&
+ !options.filterProperties.includes(name)
+ ) {
+ return;
+ }
+ ret[name] = {
+ value: computed.getPropertyValue(name),
+ priority: computed.getPropertyPriority(name) || undefined,
+ };
+ });
+
+ if (options.markMatched || options.onlyMatched) {
+ const matched = this.cssLogic.hasMatchedSelectors(Object.keys(ret));
+ for (const key in ret) {
+ if (matched[key]) {
+ ret[key].matched = options.markMatched ? true : undefined;
+ } else if (options.onlyMatched) {
+ delete ret[key];
+ }
+ }
+ }
+
+ return ret;
+ },
+
+ /**
+ * Get all the fonts from a page.
+ *
+ * @param object options
+ * `includePreviews`: Whether to also return image previews of the fonts.
+ * `previewText`: The text to display in the previews.
+ * `previewFontSize`: The font size of the text in the previews.
+ *
+ * @returns object
+ * object with 'fontFaces', a list of fonts that apply to this node.
+ */
+ getAllUsedFontFaces: function(options) {
+ const windows = this.inspector.targetActor.windows;
+ let fontsList = [];
+ for (const win of windows) {
+ // Fall back to the documentElement for XUL documents.
+ const node = win.document.body
+ ? win.document.body
+ : win.document.documentElement;
+ fontsList = [...fontsList, ...this.getUsedFontFaces(node, options)];
+ }
+
+ return fontsList;
+ },
+
+ /**
+ * Get the font faces used in an element.
+ *
+ * @param NodeActor node / actual DOM node
+ * The node to get fonts from.
+ * @param object options
+ * `includePreviews`: Whether to also return image previews of the fonts.
+ * `previewText`: The text to display in the previews.
+ * `previewFontSize`: The font size of the text in the previews.
+ *
+ * @returns object
+ * object with 'fontFaces', a list of fonts that apply to this node.
+ */
+ getUsedFontFaces: function(node, options) {
+ // node.rawNode is defined for NodeActor objects
+ const actualNode = node.rawNode || node;
+ const contentDocument = actualNode.ownerDocument;
+ // We don't get fonts for a node, but for a range
+ const rng = contentDocument.createRange();
+ const isPseudoElement = Boolean(
+ CssLogic.getBindingElementAndPseudo(actualNode).pseudo
+ );
+ if (isPseudoElement) {
+ rng.selectNodeContents(actualNode);
+ } else {
+ rng.selectNode(actualNode);
+ }
+ const fonts = InspectorUtils.getUsedFontFaces(rng);
+ const fontsArray = [];
+
+ for (let i = 0; i < fonts.length; i++) {
+ const font = fonts[i];
+ const fontFace = {
+ name: font.name,
+ CSSFamilyName: font.CSSFamilyName,
+ CSSGeneric: font.CSSGeneric || null,
+ srcIndex: font.srcIndex,
+ URI: font.URI,
+ format: font.format,
+ localName: font.localName,
+ metadata: font.metadata,
+ };
+
+ // If this font comes from a @font-face rule
+ if (font.rule) {
+ const styleActor = StyleRuleActor(this, font.rule);
+ this.manage(styleActor);
+ fontFace.rule = styleActor;
+ fontFace.ruleText = font.rule.cssText;
+ }
+
+ // Get the weight and style of this font for the preview and sort order
+ let weight = NORMAL_FONT_WEIGHT,
+ style = "";
+ if (font.rule) {
+ weight =
+ font.rule.style.getPropertyValue("font-weight") || NORMAL_FONT_WEIGHT;
+ if (weight == "bold") {
+ weight = BOLD_FONT_WEIGHT;
+ } else if (weight == "normal") {
+ weight = NORMAL_FONT_WEIGHT;
+ }
+ style = font.rule.style.getPropertyValue("font-style") || "";
+ }
+ fontFace.weight = weight;
+ fontFace.style = style;
+
+ if (options.includePreviews) {
+ const opts = {
+ previewText: options.previewText,
+ previewFontSize: options.previewFontSize,
+ fontStyle: weight + " " + style,
+ fillStyle: options.previewFillStyle,
+ };
+ const { dataURL, size } = getFontPreviewData(
+ font.CSSFamilyName,
+ contentDocument,
+ opts
+ );
+ fontFace.preview = {
+ data: LongStringActor(this.conn, dataURL),
+ size: size,
+ };
+ }
+
+ if (options.includeVariations && FONT_VARIATIONS_ENABLED) {
+ fontFace.variationAxes = font.getVariationAxes();
+ fontFace.variationInstances = font.getVariationInstances();
+ }
+
+ fontsArray.push(fontFace);
+ }
+
+ // @font-face fonts at the top, then alphabetically, then by weight
+ fontsArray.sort(function(a, b) {
+ return a.weight > b.weight ? 1 : -1;
+ });
+ fontsArray.sort(function(a, b) {
+ if (a.CSSFamilyName == b.CSSFamilyName) {
+ return 0;
+ }
+ return a.CSSFamilyName > b.CSSFamilyName ? 1 : -1;
+ });
+ fontsArray.sort(function(a, b) {
+ if ((a.rule && b.rule) || (!a.rule && !b.rule)) {
+ return 0;
+ }
+ return !a.rule && b.rule ? 1 : -1;
+ });
+
+ return fontsArray;
+ },
+
+ /**
+ * Get a list of selectors that match a given property for a node.
+ *
+ * @param NodeActor node
+ * @param string property
+ * @param object options
+ * `filter`: A string filter that affects the "matched" handling.
+ * 'user': Include properties from user style sheets.
+ * 'ua': Include properties from user and user-agent sheets.
+ * Default value is 'ua'
+ *
+ * @returns a JSON object with the following form:
+ * {
+ * // An ordered list of rules that apply
+ * matched: [{
+ * rule: <rule actorid>,
+ * sourceText: <string>, // The source of the selector, relative
+ * // to the node in question.
+ * selector: <string>, // the selector ID that matched
+ * value: <string>, // the value of the property
+ * status: <int>,
+ * // The status of the match - high numbers are better placed
+ * // to provide styling information:
+ * // 3: Best match, was used.
+ * // 2: Matched, but was overridden.
+ * // 1: Rule from a parent matched.
+ * // 0: Unmatched (never returned in this API)
+ * }, ...],
+ *
+ * // The full form of any domrule referenced.
+ * rules: [ <domrule>, ... ], // The full form of any domrule referenced
+ *
+ * // The full form of any sheets referenced.
+ * sheets: [ <domsheet>, ... ]
+ * }
+ */
+ getMatchedSelectors: function(node, property, options) {
+ this.cssLogic.sourceFilter = options.filter || SharedCssLogic.FILTER.UA;
+ this.cssLogic.highlight(node.rawNode);
+
+ const rules = new Set();
+ const sheets = new Set();
+
+ const matched = [];
+ const propInfo = this.cssLogic.getPropertyInfo(property);
+ for (const selectorInfo of propInfo.matchedSelectors) {
+ const cssRule = selectorInfo.selector.cssRule;
+ const domRule = cssRule.sourceElement || cssRule.domRule;
+
+ const rule = this._styleRef(domRule);
+ rules.add(rule);
+
+ matched.push({
+ rule: rule,
+ sourceText: this.getSelectorSource(selectorInfo, node.rawNode),
+ selector: selectorInfo.selector.text,
+ name: selectorInfo.property,
+ value: selectorInfo.value,
+ status: selectorInfo.status,
+ });
+ }
+
+ this.expandSets(rules, sheets);
+
+ return {
+ matched: matched,
+ rules: [...rules],
+ sheets: [...sheets],
+ };
+ },
+
+ // Get a selector source for a CssSelectorInfo relative to a given
+ // node.
+ getSelectorSource: function(selectorInfo, relativeTo) {
+ let result = selectorInfo.selector.text;
+ if (selectorInfo.inlineStyle) {
+ const source = selectorInfo.sourceElement;
+ if (source === relativeTo) {
+ result = "this";
+ } else {
+ result = CssLogic.getShortName(source);
+ }
+ result += ".style";
+ }
+ return result;
+ },
+
+ /**
+ * Get the set of styles that apply to a given node.
+ * @param NodeActor node
+ * @param object options
+ * `filter`: A string filter that affects the "matched" handling.
+ * 'user': Include properties from user style sheets.
+ * 'ua': Include properties from user and user-agent sheets.
+ * Default value is 'ua'
+ * `inherited`: Include styles inherited from parent nodes.
+ * `matchedSelectors`: Include an array of specific selectors that
+ * caused this rule to match its node.
+ * `skipPseudo`: Exclude styles applied to pseudo elements of the provided node.
+ */
+ async getApplied(node, options) {
+ // Clear any previous references to StyleRuleActor instances for CSS rules.
+ // Assume the consumer has switched context to a new node and no longer
+ // interested in state changes of previous rules.
+ this._observedRules = [];
+ this.selectedElement = node.rawNode;
+
+ if (!node) {
+ return { entries: [], rules: [], sheets: [] };
+ }
+
+ this.cssLogic.highlight(node.rawNode);
+ let entries = [];
+ entries = entries.concat(
+ this._getAllElementRules(node, undefined, options)
+ );
+
+ const result = this.getAppliedProps(node, entries, options);
+ for (const rule of result.rules) {
+ // See the comment in |form| to understand this.
+ await rule.getAuthoredCssText();
+ }
+
+ // Reference to instances of StyleRuleActor for CSS rules matching the node.
+ // Assume these are used by a consumer which wants to be notified when their
+ // state or declarations change either directly or indirectly.
+ this._observedRules = result.rules;
+
+ return result;
+ },
+
+ _hasInheritedProps: function(style) {
+ return Array.prototype.some.call(style, prop => {
+ return InspectorUtils.isInheritedProperty(prop);
+ });
+ },
+
+ async isPositionEditable(node) {
+ if (!node || node.rawNode.nodeType !== node.rawNode.ELEMENT_NODE) {
+ return false;
+ }
+
+ const props = getDefinedGeometryProperties(node.rawNode);
+
+ // Elements with only `width` and `height` are currently not considered
+ // editable.
+ return (
+ props.has("top") ||
+ props.has("right") ||
+ props.has("left") ||
+ props.has("bottom")
+ );
+ },
+
+ /**
+ * Helper function for getApplied, gets all the rules from a given
+ * element. See getApplied for documentation on parameters.
+ * @param NodeActor node
+ * @param bool inherited
+ * @param object options
+
+ * @return Array The rules for a given element. Each item in the
+ * array has the following signature:
+ * - rule RuleActor
+ * - isSystem Boolean
+ * - inherited Boolean
+ * - pseudoElement String
+ */
+ _getAllElementRules: function(node, inherited, options) {
+ const { bindingElement, pseudo } = CssLogic.getBindingElementAndPseudo(
+ node.rawNode
+ );
+ const rules = [];
+
+ if (!bindingElement || !bindingElement.style) {
+ return rules;
+ }
+
+ const elementStyle = this._styleRef(bindingElement);
+ const showElementStyles = !inherited && !pseudo;
+ const showInheritedStyles =
+ inherited && this._hasInheritedProps(bindingElement.style);
+
+ const rule = {
+ rule: elementStyle,
+ pseudoElement: null,
+ isSystem: false,
+ inherited: false,
+ };
+
+ // First any inline styles
+ if (showElementStyles) {
+ rules.push(rule);
+ }
+
+ // Now any inherited styles
+ if (showInheritedStyles) {
+ rule.inherited = inherited;
+ rules.push(rule);
+ }
+
+ // Add normal rules. Typically this is passing in the node passed into the
+ // function, unless if that node was ::before/::after. In which case,
+ // it will pass in the parentNode along with "::before"/"::after".
+ this._getElementRules(bindingElement, pseudo, inherited, options).forEach(
+ oneRule => {
+ // The only case when there would be a pseudo here is
+ // ::before/::after, and in this case we want to tell the
+ // view that it belongs to the element (which is a
+ // _moz_generated_content native anonymous element).
+ oneRule.pseudoElement = null;
+ rules.push(oneRule);
+ }
+ );
+
+ // Now any pseudos.
+ if (showElementStyles && !options.skipPseudo) {
+ for (const readPseudo of PSEUDO_ELEMENTS) {
+ if (this._pseudoIsRelevant(bindingElement, readPseudo)) {
+ this._getElementRules(
+ bindingElement,
+ readPseudo,
+ inherited,
+ options
+ ).forEach(oneRule => {
+ rules.push(oneRule);
+ });
+ }
+ }
+ }
+
+ return rules;
+ },
+
+ _nodeIsTextfieldLike(node) {
+ if (node.nodeName == "TEXTAREA") {
+ return true;
+ }
+ return (
+ node.mozIsTextField &&
+ (node.mozIsTextField(false) || node.type == "number")
+ );
+ },
+
+ _nodeIsButtonLike(node) {
+ if (node.nodeName == "BUTTON") {
+ return true;
+ }
+ return (
+ node.nodeName == "INPUT" &&
+ ["submit", "color", "button"].includes(node.type)
+ );
+ },
+
+ _nodeIsListItem(node) {
+ const display = CssLogic.getComputedStyle(node).getPropertyValue("display");
+ // This is written this way to handle `inline list-item` and such.
+ return display.split(" ").includes("list-item");
+ },
+
+ // eslint-disable-next-line complexity
+ _pseudoIsRelevant(node, pseudo) {
+ switch (pseudo) {
+ case ":after":
+ case ":before":
+ case ":first-letter":
+ case ":first-line":
+ case ":selection":
+ return true;
+ case ":marker":
+ return this._nodeIsListItem(node);
+ case ":backdrop":
+ return node.matches(":fullscreen");
+ case ":cue":
+ return node.nodeName == "VIDEO";
+ case ":file-selector-button":
+ return node.nodeName == "INPUT" && node.type == "file";
+ case ":placeholder":
+ case ":-moz-placeholder":
+ return this._nodeIsTextfieldLike(node);
+ case ":-moz-focus-inner":
+ return this._nodeIsButtonLike(node);
+ case ":-moz-meter-bar":
+ return node.nodeName == "METER";
+ case ":-moz-progress-bar":
+ return node.nodeName == "PROGRESS";
+ case ":-moz-color-swatch":
+ return node.nodeName == "INPUT" && node.type == "color";
+ case ":-moz-range-progress":
+ case ":-moz-range-thumb":
+ case ":-moz-range-track":
+ return node.nodeName == "INPUT" && node.type == "range";
+ default:
+ throw Error("Unhandled pseudo-element " + pseudo);
+ }
+ },
+
+ /**
+ * Helper function for _getAllElementRules, returns the rules from a given
+ * element. See getApplied for documentation on parameters.
+ * @param DOMNode node
+ * @param string pseudo
+ * @param DOMNode inherited
+ * @param object options
+ *
+ * @returns Array
+ */
+ _getElementRules: function(node, pseudo, inherited, options) {
+ const domRules = InspectorUtils.getCSSStyleRules(
+ node,
+ pseudo,
+ CssLogic.hasVisitedState(node)
+ );
+
+ if (!domRules) {
+ return [];
+ }
+
+ const rules = [];
+
+ // getCSSStyleRules returns ordered from least-specific to
+ // most-specific.
+ for (let i = domRules.length - 1; i >= 0; i--) {
+ const domRule = domRules[i];
+
+ const isSystem = SharedCssLogic.isAgentStylesheet(
+ domRule.parentStyleSheet
+ );
+
+ if (isSystem && options.filter != SharedCssLogic.FILTER.UA) {
+ continue;
+ }
+
+ if (inherited) {
+ // Don't include inherited rules if none of its properties
+ // are inheritable.
+ const hasInherited = [...domRule.style].some(prop =>
+ InspectorUtils.isInheritedProperty(prop)
+ );
+ if (!hasInherited) {
+ continue;
+ }
+ }
+
+ const ruleActor = this._styleRef(domRule);
+
+ rules.push({
+ rule: ruleActor,
+ inherited,
+ isSystem,
+ pseudoElement: pseudo,
+ });
+ }
+ return rules;
+ },
+
+ /**
+ * Given a node and a CSS rule, walk up the DOM looking for a
+ * matching element rule. Return an array of all found entries, in
+ * the form generated by _getAllElementRules. Note that this will
+ * always return an array of either zero or one element.
+ *
+ * @param {NodeActor} node the node
+ * @param {CSSStyleRule} filterRule the rule to filter for
+ * @return {Array} array of zero or one elements; if one, the element
+ * is the entry as returned by _getAllElementRules.
+ */
+ findEntryMatchingRule: function(node, filterRule) {
+ const options = { matchedSelectors: true, inherited: true };
+ let entries = [];
+ let parent = this.walker.parentNode(node);
+ while (parent && parent.rawNode.nodeType != Node.DOCUMENT_NODE) {
+ entries = entries.concat(
+ this._getAllElementRules(parent, parent, options)
+ );
+ parent = this.walker.parentNode(parent);
+ }
+
+ return entries.filter(entry => entry.rule.rawRule === filterRule);
+ },
+
+ /**
+ * Helper function for getApplied that fetches a set of style properties that
+ * apply to the given node and associated rules
+ * @param NodeActor node
+ * @param object options
+ * `filter`: A string filter that affects the "matched" handling.
+ * 'user': Include properties from user style sheets.
+ * 'ua': Include properties from user and user-agent sheets.
+ * Default value is 'ua'
+ * `inherited`: Include styles inherited from parent nodes.
+ * `matchedSelectors`: Include an array of specific selectors that
+ * caused this rule to match its node.
+ * `skipPseudo`: Exclude styles applied to pseudo elements of the provided node.
+ * @param array entries
+ * List of appliedstyle objects that lists the rules that apply to the
+ * node. If adding a new rule to the stylesheet, only the new rule entry
+ * is provided and only the style properties that apply to the new
+ * rule is fetched.
+ * @returns Object containing the list of rule entries, rule actors and
+ * stylesheet actors that applies to the given node and its associated
+ * rules.
+ */
+ getAppliedProps: function(node, entries, options) {
+ if (options.inherited) {
+ let parent = this.walker.parentNode(node);
+ while (parent && parent.rawNode.nodeType != Node.DOCUMENT_NODE) {
+ entries = entries.concat(
+ this._getAllElementRules(parent, parent, options)
+ );
+ parent = this.walker.parentNode(parent);
+ }
+ }
+
+ if (options.matchedSelectors) {
+ for (const entry of entries) {
+ if (entry.rule.type === ELEMENT_STYLE) {
+ continue;
+ }
+
+ const domRule = entry.rule.rawRule;
+ const selectors = CssLogic.getSelectors(domRule);
+ const element = entry.inherited
+ ? entry.inherited.rawNode
+ : node.rawNode;
+
+ const { bindingElement, pseudo } = CssLogic.getBindingElementAndPseudo(
+ element
+ );
+ const relevantLinkVisited = CssLogic.hasVisitedState(bindingElement);
+ entry.matchedSelectors = [];
+
+ for (let i = 0; i < selectors.length; i++) {
+ if (
+ InspectorUtils.selectorMatchesElement(
+ bindingElement,
+ domRule,
+ i,
+ pseudo,
+ relevantLinkVisited
+ )
+ ) {
+ entry.matchedSelectors.push(selectors[i]);
+ }
+ }
+ }
+ }
+
+ // Add all the keyframes rule associated with the element
+ const computedStyle = this.cssLogic.computedStyle;
+ if (computedStyle) {
+ let animationNames = computedStyle.animationName.split(",");
+ animationNames = animationNames.map(name => name.trim());
+
+ if (animationNames) {
+ // Traverse through all the available keyframes rule and add
+ // the keyframes rule that matches the computed animation name
+ for (const keyframesRule of this.cssLogic.keyframesRules) {
+ if (animationNames.indexOf(keyframesRule.name) > -1) {
+ for (const rule of keyframesRule.cssRules) {
+ entries.push({
+ rule: this._styleRef(rule),
+ keyframes: this._styleRef(keyframesRule),
+ });
+ }
+ }
+ }
+ }
+ }
+
+ const rules = new Set();
+ const sheets = new Set();
+ entries.forEach(entry => rules.add(entry.rule));
+ this.expandSets(rules, sheets);
+
+ return {
+ entries: entries,
+ rules: [...rules],
+ sheets: [...sheets],
+ };
+ },
+
+ /**
+ * Expand Sets of rules and sheets to include all parent rules and sheets.
+ */
+ expandSets: function(ruleSet, sheetSet) {
+ // Sets include new items in their iteration
+ for (const rule of ruleSet) {
+ if (rule.rawRule.parentRule) {
+ const parent = this._styleRef(rule.rawRule.parentRule);
+ if (!ruleSet.has(parent)) {
+ ruleSet.add(parent);
+ }
+ }
+ }
+
+ // We need to clean up the following codes when server-side stylesheet
+ // watcher is enabled in bug 1672090.
+ if (this.styleSheetWatcher) {
+ return;
+ }
+
+ for (const rule of ruleSet) {
+ if (rule.rawRule.parentStyleSheet) {
+ const parent = this._sheetRef(rule.rawRule.parentStyleSheet);
+ if (!sheetSet.has(parent)) {
+ sheetSet.add(parent);
+ }
+ }
+ }
+
+ for (const sheet of sheetSet) {
+ if (sheet.rawSheet.parentStyleSheet) {
+ const parent = this._sheetRef(sheet.rawSheet.parentStyleSheet);
+ if (!sheetSet.has(parent)) {
+ sheetSet.add(parent);
+ }
+ }
+ }
+ },
+
+ /**
+ * Get layout-related information about a node.
+ * This method returns an object with properties giving information about
+ * the node's margin, border, padding and content region sizes, as well
+ * as information about the type of box, its position, z-index, etc...
+ * @param {NodeActor} node
+ * @param {Object} options The only available option is autoMargins.
+ * If set to true, the element's margins will receive an extra check to see
+ * whether they are set to "auto" (knowing that the computed-style in this
+ * case would return "0px").
+ * The returned object will contain an extra property (autoMargins) listing
+ * all margins that are set to auto, e.g. {top: "auto", left: "auto"}.
+ * @return {Object}
+ */
+ getLayout: function(node, options) {
+ this.cssLogic.highlight(node.rawNode);
+
+ const layout = {};
+
+ // First, we update the first part of the box model view, with
+ // the size of the element.
+
+ const clientRect = node.rawNode.getBoundingClientRect();
+ layout.width = parseFloat(clientRect.width.toPrecision(6));
+ layout.height = parseFloat(clientRect.height.toPrecision(6));
+
+ // We compute and update the values of margins & co.
+ const style = CssLogic.getComputedStyle(node.rawNode);
+ for (const prop of [
+ "position",
+ "top",
+ "right",
+ "bottom",
+ "left",
+ "margin-top",
+ "margin-right",
+ "margin-bottom",
+ "margin-left",
+ "padding-top",
+ "padding-right",
+ "padding-bottom",
+ "padding-left",
+ "border-top-width",
+ "border-right-width",
+ "border-bottom-width",
+ "border-left-width",
+ "z-index",
+ "box-sizing",
+ "display",
+ "float",
+ "line-height",
+ ]) {
+ layout[prop] = style.getPropertyValue(prop);
+ }
+
+ if (options.autoMargins) {
+ layout.autoMargins = this.processMargins(this.cssLogic);
+ }
+
+ for (const i in this.map) {
+ const property = this.map[i].property;
+ this.map[i].value = parseFloat(style.getPropertyValue(property));
+ }
+
+ return layout;
+ },
+
+ /**
+ * Find 'auto' margin properties.
+ */
+ processMargins: function(cssLogic) {
+ const margins = {};
+
+ for (const prop of ["top", "bottom", "left", "right"]) {
+ const info = cssLogic.getPropertyInfo("margin-" + prop);
+ const selectors = info.matchedSelectors;
+ if (selectors && selectors.length > 0 && selectors[0].value == "auto") {
+ margins[prop] = "auto";
+ }
+ }
+
+ return margins;
+ },
+
+ /**
+ * On page navigation, tidy up remaining objects.
+ */
+ onFrameUnload: function() {
+ this.styleElements = new WeakMap();
+ },
+
+ /**
+ * When a stylesheet is added, handle the related StyleSheetActor to listen for changes.
+ * @param {StyleSheetActor} actor
+ * The actor for the added stylesheet.
+ */
+ onStyleSheetAdded: function(actor) {
+ if (!this._watchedSheets.has(actor)) {
+ this._watchedSheets.add(actor);
+ actor.on("style-applied", this._styleApplied);
+ }
+ },
+
+ onResourceUpdated(resources) {
+ const kinds = new Set();
+
+ for (const resource of resources) {
+ if (resource.resourceType !== TYPES.STYLESHEET) {
+ continue;
+ }
+
+ if (resource.updateType !== "style-applied") {
+ continue;
+ }
+
+ const kind = resource.event.kind;
+ kinds.add(kind);
+
+ for (const styleActor of [...this.refMap.values()]) {
+ const resourceId = this.styleSheetWatcher.getResourceId(
+ styleActor._parentSheet
+ );
+ if (resource.resourceId === resourceId) {
+ styleActor._onStyleApplied(kind);
+ }
+ }
+ }
+
+ for (const kind of kinds) {
+ this._styleApplied(kind);
+ }
+ },
+
+ /**
+ * Helper function to addNewRule to get or create a style tag in the provided
+ * document.
+ *
+ * @param {Document} document
+ * The document in which the style element should be appended.
+ * @returns DOMElement of the style tag
+ */
+ getStyleElement: function(document) {
+ if (!this.styleElements.has(document)) {
+ const style = document.createElementNS(XHTML_NS, "style");
+ style.setAttribute("type", "text/css");
+ style.setDevtoolsAsTriggeringPrincipal();
+ document.documentElement.appendChild(style);
+ this.styleElements.set(document, style);
+ }
+
+ return this.styleElements.get(document);
+ },
+
+ /**
+ * Helper function for adding a new rule and getting its applied style
+ * properties
+ * @param NodeActor node
+ * @param CSSStyleRule rule
+ * @returns Object containing its applied style properties
+ */
+ getNewAppliedProps: function(node, rule) {
+ const ruleActor = this._styleRef(rule);
+ return this.getAppliedProps(node, [{ rule: ruleActor }], {
+ matchedSelectors: true,
+ });
+ },
+
+ /**
+ * Adds a new rule, and returns the new StyleRuleActor.
+ * @param {NodeActor} node
+ * @param {String} pseudoClasses The list of pseudo classes to append to the
+ * new selector.
+ * @returns {StyleRuleActor} the new rule
+ */
+ async addNewRule(node, pseudoClasses) {
+ let sheet = null;
+ if (this.styleSheetWatcher) {
+ const doc = node.rawNode.ownerDocument;
+ if (this.styleElements.has(doc)) {
+ sheet = this.styleElements.get(doc);
+ } else {
+ sheet = await this.styleSheetWatcher.addStyleSheet(doc);
+ this.styleElements.set(doc, sheet);
+ }
+ } else {
+ const style = this.getStyleElement(node.rawNode.ownerDocument);
+ sheet = style.sheet;
+ }
+
+ const cssRules = sheet.cssRules;
+ const rawNode = node.rawNode;
+ const classes = [...rawNode.classList];
+
+ let selector;
+ if (rawNode.id) {
+ selector = "#" + CSS.escape(rawNode.id);
+ } else if (classes.length > 0) {
+ selector = "." + classes.map(c => CSS.escape(c)).join(".");
+ } else {
+ selector = rawNode.localName;
+ }
+
+ if (pseudoClasses && pseudoClasses.length > 0) {
+ selector += pseudoClasses.join("");
+ }
+
+ const index = sheet.insertRule(selector + " {}", cssRules.length);
+
+ if (this.styleSheetWatcher) {
+ const resourceId = this.styleSheetWatcher.getResourceId(sheet);
+ let authoredText = await this.styleSheetWatcher.getText(resourceId);
+ authoredText += "\n" + selector + " {\n" + "}";
+ await this.styleSheetWatcher.update(resourceId, authoredText, false);
+ } else {
+ // If inserting the rule succeeded, go ahead and edit the source
+ // text if requested.
+ const sheetActor = this._sheetRef(sheet);
+ let { str: authoredText } = await sheetActor.getText();
+ authoredText += "\n" + selector + " {\n" + "}";
+ await sheetActor.update(authoredText, false);
+ }
+
+ const cssRule = sheet.cssRules.item(index);
+ const ruleActor = this._styleRef(cssRule);
+
+ TrackChangeEmitter.trackChange({
+ ...ruleActor.metadata,
+ type: "rule-add",
+ add: null,
+ remove: null,
+ selector,
+ });
+
+ return this.getNewAppliedProps(node, cssRule);
+ },
+
+ /**
+ * Cause all StyleRuleActor instances of observed CSS rules to check whether the
+ * states of their declarations have changed.
+ *
+ * Observed rules are the latest rules returned by a call to PageStyleActor.getApplied()
+ *
+ * This is necessary because changes in one rule can cause the declarations in another
+ * to not be applicable (inactive CSS). The observers of those rules should be notified.
+ * Rules will fire a "rule-updated" event if any of their declarations changed state.
+ *
+ * Call this method whenever a CSS rule is mutated:
+ * - a CSS declaration is added/changed/disabled/removed
+ * - a selector is added/changed/removed
+ */
+ refreshObservedRules() {
+ for (const rule of this._observedRules) {
+ rule.refresh();
+ }
+ },
+
+ /**
+ * Get an array of existing attribute values in a node document.
+ *
+ * @param {String} search: A string to filter attribute value on.
+ * @param {String} attributeType: The type of attribute we want to retrieve the values.
+ * @param {Element} node: The element we want to get possible attributes for. This will
+ * be used to get the document where the search is happening.
+ * @returns {Array<String>} An array of strings
+ */
+ getAttributesInOwnerDocument(search, attributeType, node) {
+ if (!search) {
+ throw new Error("search is mandatory");
+ }
+
+ // In a non-fission world, a node from an iframe shares the same `rootNode` as a node
+ // in the top-level document. So here we need to retrieve the document from the node
+ // in parameter in order to retrieve the right document.
+ // This may change once we have a dedicated walker for every target in a tab, as we'll
+ // be able to directly talk to the "right" walker actor.
+ const targetDocument = node.rawNode.ownerDocument;
+
+ // We store the result in a Set which will contain the attribute value
+ const result = new Set();
+ const lcSearch = search.toLowerCase();
+ this._collectAttributesFromDocumentDOM(
+ result,
+ lcSearch,
+ attributeType,
+ targetDocument
+ );
+ this._collectAttributesFromDocumentStyleSheets(
+ result,
+ lcSearch,
+ attributeType,
+ targetDocument
+ );
+
+ return Array.from(result).sort();
+ },
+
+ /**
+ * Collect attribute values from the document DOM tree, matching the passed filter and
+ * type, to the result Set.
+ *
+ * @param {Set<String>} result: A Set to which the results will be added.
+ * @param {String} search: A string to filter attribute value on.
+ * @param {String} attributeType: The type of attribute we want to retrieve the values.
+ * @param {Document} targetDocument: The document the search occurs in.
+ */
+ _collectAttributesFromDocumentDOM(
+ result,
+ search,
+ attributeType,
+ targetDocument
+ ) {
+ // In order to retrieve attributes from DOM elements in the document, we're going to
+ // do a query on the root node using attributes selector, to directly get the elements
+ // matching the attributes we're looking for.
+
+ // For classes, we need something a bit different as the className we're looking
+ // for might not be the first in the attribute value, meaning we can't use the
+ // "attribute starts with X" selector.
+ const attributeSelectorPositionChar = attributeType === "class" ? "*" : "^";
+ const selector = `[${attributeType}${attributeSelectorPositionChar}=${search} i]`;
+
+ const matchingElements = targetDocument.querySelectorAll(selector);
+
+ for (const element of matchingElements) {
+ // For class attribute, we need to add the elements of the classList that match
+ // the filter string.
+ if (attributeType === "class") {
+ for (const cls of element.classList) {
+ if (!result.has(cls) && cls.toLowerCase().startsWith(search)) {
+ result.add(cls);
+ }
+ }
+ } else {
+ const { value } = element.attributes[attributeType];
+ // For other attributes, we can directly use the attribute value.
+ result.add(value);
+ }
+ }
+ },
+
+ /**
+ * Collect attribute values from the document stylesheets, matching the passed filter
+ * and type, to the result Set.
+ *
+ * @param {Set<String>} result: A Set to which the results will be added.
+ * @param {String} search: A string to filter attribute value on.
+ * @param {String} attributeType: The type of attribute we want to retrieve the values.
+ * It only supports "class" and "id" at the moment.
+ * @param {Document} targetDocument: The document the search occurs in.
+ */
+ _collectAttributesFromDocumentStyleSheets(
+ result,
+ search,
+ attributeType,
+ targetDocument
+ ) {
+ if (attributeType !== "class" && attributeType !== "id") {
+ return;
+ }
+
+ // We loop through all the stylesheets and their rules, and then use the lexer to only
+ // get the attributes we're looking for.
+ for (const styleSheet of targetDocument.styleSheets) {
+ for (const rule of styleSheet.rules) {
+ this._collectAttributesFromRule(result, rule, search, attributeType);
+ }
+ }
+ },
+
+ /**
+ * Collect attribute values from the rule, matching the passed filter and type, to the
+ * result Set.
+ *
+ * @param {Set<String>} result: A Set to which the results will be added.
+ * @param {Rule} rule: The rule the search occurs in.
+ * @param {String} search: A string to filter attribute value on.
+ * @param {String} attributeType: The type of attribute we want to retrieve the values.
+ * It only supports "class" and "id" at the moment.
+ */
+ _collectAttributesFromRule(result, rule, search, attributeType) {
+ const shouldRetrieveClasses = attributeType === "class";
+ const shouldRetrieveIds = attributeType === "id";
+
+ const { selectorText } = rule;
+ // If there's no selectorText, or if the selectorText does not include the
+ // filter, we can bail out.
+ if (!selectorText || !selectorText.toLowerCase().includes(search)) {
+ return;
+ }
+
+ // Check if we should parse the selectorText (do we need to check for class/id and
+ // if so, does the selector contains class/id related chars).
+ const parseForClasses =
+ shouldRetrieveClasses &&
+ selectorText.toLowerCase().includes(`.${search}`);
+ const parseForIds =
+ shouldRetrieveIds && selectorText.toLowerCase().includes(`#${search}`);
+
+ if (!parseForClasses && !parseForIds) {
+ return;
+ }
+
+ const lexer = getCSSLexer(selectorText);
+ let token;
+ while ((token = lexer.nextToken())) {
+ if (
+ token.tokenType === "symbol" &&
+ ((shouldRetrieveClasses && token.text === ".") ||
+ (shouldRetrieveIds && token.text === "#"))
+ ) {
+ token = lexer.nextToken();
+ if (
+ token.tokenType === "ident" &&
+ token.text.toLowerCase().startsWith(search)
+ ) {
+ result.add(token.text);
+ }
+ }
+ }
+ },
+});
+exports.PageStyleActor = PageStyleActor;
diff --git a/devtools/server/actors/pause-scoped.js b/devtools/server/actors/pause-scoped.js
new file mode 100644
index 0000000000..1eaaec66c8
--- /dev/null
+++ b/devtools/server/actors/pause-scoped.js
@@ -0,0 +1,98 @@
+/* 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";
+
+const { extend } = require("devtools/shared/extend");
+const { ObjectActorProto } = require("devtools/server/actors/object");
+const protocol = require("devtools/shared/protocol");
+const { ActorClassWithSpec } = protocol;
+const { objectSpec } = require("devtools/shared/specs/object");
+
+/**
+ * Protocol.js expects only the prototype object, and does not maintain the prototype
+ * chain when it constructs the ActorClass. For this reason we are using extend to
+ * maintain the properties of ObjectActorProto.
+ **/
+const proto = extend({}, ObjectActorProto);
+
+Object.assign(proto, {
+ /**
+ * Creates a pause-scoped actor for the specified object.
+ * @see ObjectActor
+ */
+ initialize: function(obj, hooks, conn) {
+ ObjectActorProto.initialize.call(this, obj, hooks, conn);
+ this.hooks.promote = hooks.promote;
+ this.hooks.isThreadLifetimePool = hooks.isThreadLifetimePool;
+ },
+
+ isPaused: function() {
+ return this.threadActor ? this.threadActor.state === "paused" : true;
+ },
+
+ withPaused: function(method) {
+ return function() {
+ if (this.isPaused()) {
+ return method.apply(this, arguments);
+ }
+
+ return {
+ error: "wrongState",
+ message:
+ this.constructor.name +
+ " actors can only be accessed while the thread is paused.",
+ };
+ };
+ },
+});
+
+const guardWithPaused = [
+ "decompile",
+ "displayString",
+ "ownPropertyNames",
+ "parameterNames",
+ "property",
+ "prototype",
+ "prototypeAndProperties",
+ "scope",
+];
+
+guardWithPaused.forEach(f => {
+ proto[f] = proto.withPaused(ObjectActorProto[f]);
+});
+
+Object.assign(proto, {
+ /**
+ * Handle a protocol request to promote a pause-lifetime grip to a
+ * thread-lifetime grip.
+ *
+ * @param request object
+ * The protocol request object.
+ */
+ threadGrip: proto.withPaused(function(request) {
+ this.hooks.promote();
+ return {};
+ }),
+
+ /**
+ * Handle a protocol request to release a thread-lifetime grip.
+ *
+ * @param request object
+ * The protocol request object.
+ */
+ destroy: proto.withPaused(function(request) {
+ if (this.hooks.isThreadLifetimePool()) {
+ return {
+ error: "notReleasable",
+ message: "Only thread-lifetime actors can be released.",
+ };
+ }
+
+ return protocol.Actor.prototype.destroy.call(this);
+ }),
+});
+
+exports.PauseScopedObjectActor = ActorClassWithSpec(objectSpec, proto);
+// ActorClassWithSpec(objectSpec, {...ObjectActorProto, ...proto});
diff --git a/devtools/server/actors/perf.js b/devtools/server/actors/perf.js
new file mode 100644
index 0000000000..95c539a3c6
--- /dev/null
+++ b/devtools/server/actors/perf.js
@@ -0,0 +1,62 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { ActorClassWithSpec, Actor } = protocol;
+const { actorBridgeWithSpec } = require("devtools/server/actors/common");
+const { perfSpec } = require("devtools/shared/specs/perf");
+const {
+ ActorReadyGeckoProfilerInterface,
+} = require("devtools/shared/performance-new/gecko-profiler-interface");
+
+/**
+ * Pass on the events from the bridge to the actor.
+ * @param {Object} actor The perf actor
+ * @param {Array<string>} names The event names
+ */
+function _bridgeEvents(actor, names) {
+ for (const name of names) {
+ actor.bridge.on(name, (...args) => actor.emit(name, ...args));
+ }
+}
+
+/**
+ * The PerfActor wraps the Gecko Profiler interface
+ */
+exports.PerfActor = ActorClassWithSpec(perfSpec, {
+ initialize: function(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+ // The "bridge" is the actual implementation of the actor. It is abstracted
+ // out into its own class so that it can be re-used with the profiler popup.
+ this.bridge = new ActorReadyGeckoProfilerInterface({
+ // Do not use the gzipped API from the Profiler to capture profiles.
+ gzipped: false,
+ });
+
+ _bridgeEvents(this, [
+ "profile-locked-by-private-browsing",
+ "profile-unlocked-from-private-browsing",
+ "profiler-started",
+ "profiler-stopped",
+ ]);
+ },
+
+ destroy: function(conn) {
+ Actor.prototype.destroy.call(this, conn);
+ this.bridge.destroy();
+ },
+
+ // Connect the rest of the ActorReadyGeckoProfilerInterface's methods to the PerfActor.
+ startProfiler: actorBridgeWithSpec("startProfiler"),
+ stopProfilerAndDiscardProfile: actorBridgeWithSpec(
+ "stopProfilerAndDiscardProfile"
+ ),
+ getSymbolTable: actorBridgeWithSpec("getSymbolTable"),
+ getProfileAndStopProfiler: actorBridgeWithSpec("getProfileAndStopProfiler"),
+ isActive: actorBridgeWithSpec("isActive"),
+ isSupportedPlatform: actorBridgeWithSpec("isSupportedPlatform"),
+ isLockedForPrivateBrowsing: actorBridgeWithSpec("isLockedForPrivateBrowsing"),
+ getSupportedFeatures: actorBridgeWithSpec("getSupportedFeatures"),
+});
diff --git a/devtools/server/actors/performance-recording.js b/devtools/server/actors/performance-recording.js
new file mode 100644
index 0000000000..f5adfef4a2
--- /dev/null
+++ b/devtools/server/actors/performance-recording.js
@@ -0,0 +1,163 @@
+/* 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";
+
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const {
+ performanceRecordingSpec,
+} = require("devtools/shared/specs/performance-recording");
+
+loader.lazyRequireGetter(
+ this,
+ "RecordingUtils",
+ "devtools/shared/performance/recording-utils"
+);
+loader.lazyRequireGetter(
+ this,
+ "PerformanceRecordingCommon",
+ "devtools/shared/performance/recording-common",
+ true
+);
+
+/**
+ * This actor wraps the Performance module at devtools/shared/shared/performance.js
+ * and provides RDP definitions.
+ *
+ * @see devtools/shared/shared/performance.js for documentation.
+ */
+const PerformanceRecordingActor = ActorClassWithSpec(
+ performanceRecordingSpec,
+ Object.assign(
+ {
+ form: function() {
+ const form = {
+ // actorID is set when this is added to a pool
+ actor: this.actorID,
+ configuration: this._configuration,
+ startingBufferStatus: this._startingBufferStatus,
+ console: this._console,
+ label: this._label,
+ startTime: this._startTime,
+ localStartTime: this._localStartTime,
+ recording: this._recording,
+ completed: this._completed,
+ duration: this._duration,
+ };
+
+ // Only send profiler data once it exists and it has
+ // not yet been sent
+ if (this._profile && !this._sentFinalizedData) {
+ form.finalizedData = true;
+ form.profile = this.getProfile();
+ form.systemHost = this.getHostSystemInfo();
+ form.systemClient = this.getClientSystemInfo();
+ this._sentFinalizedData = true;
+ }
+
+ return form;
+ },
+
+ /**
+ * @param {object} conn
+ * @param {object} options
+ * A hash of features that this recording is utilizing.
+ * @param {object} meta
+ * A hash of temporary metadata for a recording that is recording
+ * (as opposed to an imported recording).
+ */
+ initialize: function(conn, options, meta) {
+ Actor.prototype.initialize.call(this, conn);
+ this._configuration = {
+ withMarkers: options.withMarkers || false,
+ withTicks: options.withTicks || false,
+ withMemory: options.withMemory || false,
+ withAllocations: options.withAllocations || false,
+ allocationsSampleProbability:
+ options.allocationsSampleProbability || 0,
+ allocationsMaxLogLength: options.allocationsMaxLogLength || 0,
+ bufferSize: options.bufferSize || 0,
+ sampleFrequency: options.sampleFrequency || 1000,
+ };
+
+ this._console = !!options.console;
+ this._label = options.label || "";
+
+ if (meta) {
+ // Store the start time roughly with Date.now() so when we
+ // are checking the duration during a recording, we can get close
+ // to the approximate duration to render elements without
+ // making a real request
+ this._localStartTime = Date.now();
+
+ this._startTime = meta.startTime;
+ this._startingBufferStatus = {
+ position: meta.position,
+ totalSize: meta.totalSize,
+ generation: meta.generation,
+ };
+
+ this._recording = true;
+ this._markers = [];
+ this._frames = [];
+ this._memory = [];
+ this._ticks = [];
+ this._allocations = {
+ sites: [],
+ timestamps: [],
+ frames: [],
+ sizes: [],
+ };
+
+ this._systemHost = meta.systemHost || {};
+ this._systemClient = meta.systemClient || {};
+ }
+ },
+
+ destroy: function() {
+ Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Internal utility called by the PerformanceActor and PerformanceFront on state changes
+ * to update the internal state of the PerformanceRecording.
+ *
+ * @param {string} state
+ * @param {object} extraData
+ */
+ _setState: function(state, extraData) {
+ switch (state) {
+ case "recording-started": {
+ this._recording = true;
+ break;
+ }
+ case "recording-stopping": {
+ this._recording = false;
+ break;
+ }
+ case "recording-stopped": {
+ this._profile = extraData.profile;
+ this._duration = extraData.duration;
+
+ // We filter out all samples that fall out of current profile's range
+ // since the profiler is continuously running. Because of this, sample
+ // times are not guaranteed to have a zero epoch, so offset the
+ // timestamps.
+ RecordingUtils.offsetSampleTimes(this._profile, this._startTime);
+
+ // Markers need to be sorted ascending by time, to be properly displayed
+ // in a waterfall view.
+ this._markers = this._markers.sort((a, b) => a.start > b.start);
+
+ this._completed = true;
+ break;
+ }
+ }
+ },
+ },
+ PerformanceRecordingCommon
+ )
+);
+
+exports.PerformanceRecordingActor = PerformanceRecordingActor;
diff --git a/devtools/server/actors/performance.js b/devtools/server/actors/performance.js
new file mode 100644
index 0000000000..0107cc0c34
--- /dev/null
+++ b/devtools/server/actors/performance.js
@@ -0,0 +1,163 @@
+/* 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";
+
+const { Actor, ActorClassWithSpec } = require("devtools/shared/protocol");
+const { actorBridgeWithSpec } = require("devtools/server/actors/common");
+const { performanceSpec } = require("devtools/shared/specs/performance");
+
+loader.lazyRequireGetter(
+ this,
+ "PerformanceRecorder",
+ "devtools/server/performance/recorder",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "normalizePerformanceFeatures",
+ "devtools/shared/performance/recording-utils",
+ true
+);
+
+const PIPE_TO_FRONT_EVENTS = new Set([
+ "recording-started",
+ "recording-stopping",
+ "recording-stopped",
+ "profiler-status",
+ "timeline-data",
+ "console-profile-start",
+]);
+
+const RECORDING_STATE_CHANGE_EVENTS = new Set([
+ "recording-started",
+ "recording-stopping",
+ "recording-stopped",
+]);
+
+/**
+ * This actor wraps the Performance module at devtools/shared/shared/performance.js
+ * and provides RDP definitions.
+ *
+ * @see devtools/shared/shared/performance.js for documentation.
+ */
+var PerformanceActor = ActorClassWithSpec(performanceSpec, {
+ traits: {
+ features: {
+ withMarkers: true,
+ withTicks: true,
+ withMemory: true,
+ withFrames: true,
+ withGCEvents: true,
+ withDocLoadingEvents: true,
+ withAllocations: true,
+ },
+ },
+
+ initialize: function(conn, targetActor) {
+ Actor.prototype.initialize.call(this, conn);
+
+ this._onRecordingStarted = this._onRecordingStarted.bind(this);
+ this._onRecordingStopping = this._onRecordingStopping.bind(this);
+ this._onRecordingStopped = this._onRecordingStopped.bind(this);
+ this._onProfilerStatus = this._onProfilerStatus.bind(this);
+ this._onTimelineData = this._onTimelineData.bind(this);
+ this._onConsoleProfileStart = this._onConsoleProfileStart.bind(this);
+
+ this.bridge = new PerformanceRecorder(conn, targetActor);
+
+ this.bridge.on("recording-started", this._onRecordingStarted);
+ this.bridge.on("recording-stopping", this._onRecordingStopping);
+ this.bridge.on("recording-stopped", this._onRecordingStopped);
+ this.bridge.on("profiler-status", this._onProfilerStatus);
+ this.bridge.on("timeline-data", this._onTimelineData);
+ this.bridge.on("console-profile-start", this._onConsoleProfileStart);
+ },
+
+ destroy: function() {
+ this.bridge.off("recording-started", this._onRecordingStarted);
+ this.bridge.off("recording-stopping", this._onRecordingStopping);
+ this.bridge.off("recording-stopped", this._onRecordingStopped);
+ this.bridge.off("profiler-status", this._onProfilerStatus);
+ this.bridge.off("timeline-data", this._onTimelineData);
+ this.bridge.off("console-profile-start", this._onConsoleProfileStart);
+
+ this.bridge.destroy();
+ Actor.prototype.destroy.call(this);
+ },
+
+ connect: function(config) {
+ this.bridge.connect({ systemClient: config.systemClient });
+ return { traits: this.traits };
+ },
+
+ canCurrentlyRecord: function() {
+ return this.bridge.canCurrentlyRecord();
+ },
+
+ async startRecording(options = {}) {
+ if (!this.bridge.canCurrentlyRecord().success) {
+ return null;
+ }
+
+ const normalizedOptions = normalizePerformanceFeatures(
+ options,
+ this.traits.features
+ );
+ const recording = await this.bridge.startRecording(normalizedOptions);
+ this.manage(recording);
+
+ return recording;
+ },
+
+ stopRecording: actorBridgeWithSpec("stopRecording"),
+ isRecording: actorBridgeWithSpec("isRecording"),
+ getRecordings: actorBridgeWithSpec("getRecordings"),
+ getConfiguration: actorBridgeWithSpec("getConfiguration"),
+ setProfilerStatusInterval: actorBridgeWithSpec("setProfilerStatusInterval"),
+
+ /**
+ * Filter which events get piped to the front.
+ */
+ _onRecordingStarted: function(...data) {
+ this._onRecorderEvent("recording-started", data);
+ },
+
+ _onRecordingStopping: function(...data) {
+ this._onRecorderEvent("recording-stopping", data);
+ },
+
+ _onRecordingStopped: function(...data) {
+ this._onRecorderEvent("recording-stopped", data);
+ },
+
+ _onProfilerStatus: function(...data) {
+ this._onRecorderEvent("profiler-status", data);
+ },
+
+ _onTimelineData: function(...data) {
+ this._onRecorderEvent("timeline-data", data);
+ },
+
+ _onConsoleProfileStart: function(...data) {
+ this._onRecorderEvent("console-profile-start", data);
+ },
+
+ _onRecorderEvent: function(eventName, data) {
+ // If this is a recording state change, call
+ // a method on the related PerformanceRecordingActor so it can
+ // update its internal state.
+ if (RECORDING_STATE_CHANGE_EVENTS.has(eventName)) {
+ const recording = data[0];
+ const extraData = data[1];
+ recording._setState(eventName, extraData);
+ }
+
+ if (PIPE_TO_FRONT_EVENTS.has(eventName)) {
+ this.emit(eventName, ...data);
+ }
+ },
+});
+
+exports.PerformanceActor = PerformanceActor;
diff --git a/devtools/server/actors/preference.js b/devtools/server/actors/preference.js
new file mode 100644
index 0000000000..8bea39eccb
--- /dev/null
+++ b/devtools/server/actors/preference.js
@@ -0,0 +1,104 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const Services = require("Services");
+const { preferenceSpec } = require("devtools/shared/specs/preference");
+
+const { PREF_STRING, PREF_INT, PREF_BOOL } = Services.prefs;
+
+function ensurePrefType(name, expectedType) {
+ const type = Services.prefs.getPrefType(name);
+ if (type !== expectedType) {
+ throw new Error(`preference is not of the right type: ${name}`);
+ }
+}
+
+/**
+ * Normally the preferences are set using Services.prefs, but this actor allows
+ * a devtools client to set preferences on the debuggee. This is particularly useful
+ * when remote debugging, and the preferences should persist to the remote target
+ * and not to the client. If used for a local target, it effectively behaves the same
+ * as using Services.prefs.
+ *
+ * This actor is used as a global-scoped actor, targeting the entire browser, not an
+ * individual tab.
+ */
+var PreferenceActor = protocol.ActorClassWithSpec(preferenceSpec, {
+ getTraits: function() {
+ // The *Pref traits are used to know if remote-debugging bugs related to
+ // specific preferences are fixed on the server or if the client should set
+ // default values for them. See the about:debugging module
+ // runtime-default-preferences.js
+ return {};
+ },
+
+ getBoolPref: function(name) {
+ ensurePrefType(name, PREF_BOOL);
+ return Services.prefs.getBoolPref(name);
+ },
+
+ getCharPref: function(name) {
+ ensurePrefType(name, PREF_STRING);
+ return Services.prefs.getCharPref(name);
+ },
+
+ getIntPref: function(name) {
+ ensurePrefType(name, PREF_INT);
+ return Services.prefs.getIntPref(name);
+ },
+
+ getAllPrefs: function() {
+ const prefs = {};
+ Services.prefs.getChildList("").forEach(function(name, index) {
+ // append all key/value pairs into a huge json object.
+ try {
+ let value;
+ switch (Services.prefs.getPrefType(name)) {
+ case PREF_STRING:
+ value = Services.prefs.getCharPref(name);
+ break;
+ case PREF_INT:
+ value = Services.prefs.getIntPref(name);
+ break;
+ case PREF_BOOL:
+ value = Services.prefs.getBoolPref(name);
+ break;
+ default:
+ }
+ prefs[name] = {
+ value: value,
+ hasUserValue: Services.prefs.prefHasUserValue(name),
+ };
+ } catch (e) {
+ // pref exists but has no user or default value
+ }
+ });
+ return prefs;
+ },
+
+ setBoolPref: function(name, value) {
+ Services.prefs.setBoolPref(name, value);
+ Services.prefs.savePrefFile(null);
+ },
+
+ setCharPref: function(name, value) {
+ Services.prefs.setCharPref(name, value);
+ Services.prefs.savePrefFile(null);
+ },
+
+ setIntPref: function(name, value) {
+ Services.prefs.setIntPref(name, value);
+ Services.prefs.savePrefFile(null);
+ },
+
+ clearUserPref: function(name) {
+ Services.prefs.clearUserPref(name);
+ Services.prefs.savePrefFile(null);
+ },
+});
+
+exports.PreferenceActor = PreferenceActor;
diff --git a/devtools/server/actors/process.js b/devtools/server/actors/process.js
new file mode 100644
index 0000000000..71c49eed09
--- /dev/null
+++ b/devtools/server/actors/process.js
@@ -0,0 +1,79 @@
+/* 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";
+
+const { Cc } = require("chrome");
+const Services = require("Services");
+
+loader.lazyGetter(this, "ppmm", () => {
+ return Cc["@mozilla.org/parentprocessmessagemanager;1"].getService();
+});
+
+function ProcessActorList() {
+ this._actors = new Map();
+ this._onListChanged = null;
+ this._mustNotify = false;
+ this._hasObserver = false;
+}
+
+ProcessActorList.prototype = {
+ getList: function() {
+ const processes = [];
+ for (let i = 0; i < ppmm.childCount; i++) {
+ const mm = ppmm.getChildAt(i);
+ processes.push({
+ // An ID of zero is always used for the parent. It would be nice to fix
+ // this so that the pid is also used for the parent, see bug 1587443.
+ id: mm.isInProcess ? 0 : mm.osPid,
+ parent: mm.isInProcess,
+ // TODO: exposes process message manager on frameloaders in order to compute this
+ tabCount: undefined,
+ });
+ }
+ this._mustNotify = true;
+ this._checkListening();
+
+ return processes;
+ },
+
+ get onListChanged() {
+ return this._onListChanged;
+ },
+
+ set onListChanged(onListChanged) {
+ if (typeof onListChanged !== "function" && onListChanged !== null) {
+ throw new Error("onListChanged must be either a function or null.");
+ }
+ if (onListChanged === this._onListChanged) {
+ return;
+ }
+
+ this._onListChanged = onListChanged;
+ this._checkListening();
+ },
+
+ _checkListening: function() {
+ if (this._onListChanged !== null && this._mustNotify) {
+ if (!this._hasObserver) {
+ Services.obs.addObserver(this, "ipc:content-created");
+ Services.obs.addObserver(this, "ipc:content-shutdown");
+ this._hasObserver = true;
+ }
+ } else if (this._hasObserver) {
+ Services.obs.removeObserver(this, "ipc:content-created");
+ Services.obs.removeObserver(this, "ipc:content-shutdown");
+ this._hasObserver = false;
+ }
+ },
+
+ observe() {
+ if (this._mustNotify) {
+ this._onListChanged();
+ this._mustNotify = false;
+ }
+ },
+};
+
+exports.ProcessActorList = ProcessActorList;
diff --git a/devtools/server/actors/reflow.js b/devtools/server/actors/reflow.js
new file mode 100644
index 0000000000..cd4ff74c5a
--- /dev/null
+++ b/devtools/server/actors/reflow.js
@@ -0,0 +1,514 @@
+/* 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";
+
+/**
+ * About the types of objects in this file:
+ *
+ * - ReflowActor: the actor class used for protocol purposes.
+ * Mostly empty, just gets an instance of LayoutChangesObserver and forwards
+ * its "reflows" events to clients.
+ *
+ * - LayoutChangesObserver: extends Observable and uses the ReflowObserver, to
+ * track reflows on the page.
+ * Used by the LayoutActor, but is also exported on the module, so can be used
+ * by any other actor that needs it.
+ *
+ * - Observable: A utility parent class, meant at being extended by classes that
+ * need a to observe something on the targetActor's windows.
+ *
+ * - Dedicated observers: There's only one of them for now: ReflowObserver which
+ * listens to reflow events via the docshell,
+ * These dedicated classes are used by the LayoutChangesObserver.
+ */
+
+const ChromeUtils = require("ChromeUtils");
+const protocol = require("devtools/shared/protocol");
+const EventEmitter = require("devtools/shared/event-emitter");
+const { reflowSpec } = require("devtools/shared/specs/reflow");
+
+/**
+ * The reflow actor tracks reflows and emits events about them.
+ */
+exports.ReflowActor = protocol.ActorClassWithSpec(reflowSpec, {
+ initialize: function(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+
+ this.targetActor = targetActor;
+ this._onReflow = this._onReflow.bind(this);
+ this.observer = getLayoutChangesObserver(targetActor);
+ this._isStarted = false;
+ },
+
+ destroy: function() {
+ this.stop();
+ releaseLayoutChangesObserver(this.targetActor);
+ this.observer = null;
+ this.targetActor = null;
+
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Start tracking reflows and sending events to clients about them.
+ * This is a oneway method, do not expect a response and it won't return a
+ * promise.
+ */
+ start: function() {
+ if (!this._isStarted) {
+ this.observer.on("reflows", this._onReflow);
+ this._isStarted = true;
+ }
+ },
+
+ /**
+ * Stop tracking reflows and sending events to clients about them.
+ * This is a oneway method, do not expect a response and it won't return a
+ * promise.
+ */
+ stop: function() {
+ if (this._isStarted) {
+ this.observer.off("reflows", this._onReflow);
+ this._isStarted = false;
+ }
+ },
+
+ _onReflow: function(reflows) {
+ if (this._isStarted) {
+ this.emit("reflows", reflows);
+ }
+ },
+});
+
+/**
+ * Base class for all sorts of observers that need to listen to events on the
+ * targetActor's windows.
+ * @param {BrowsingContextTargetActor} targetActor
+ * @param {Function} callback Executed everytime the observer observes something
+ */
+function Observable(targetActor, callback) {
+ this.targetActor = targetActor;
+ this.callback = callback;
+
+ this._onWindowReady = this._onWindowReady.bind(this);
+ this._onWindowDestroyed = this._onWindowDestroyed.bind(this);
+
+ this.targetActor.on("window-ready", this._onWindowReady);
+ this.targetActor.on("window-destroyed", this._onWindowDestroyed);
+}
+
+Observable.prototype = {
+ /**
+ * Is the observer currently observing
+ */
+ isObserving: false,
+
+ /**
+ * Stop observing and detroy this observer instance
+ */
+ destroy: function() {
+ if (this.isDestroyed) {
+ return;
+ }
+ this.isDestroyed = true;
+
+ this.stop();
+
+ this.targetActor.off("window-ready", this._onWindowReady);
+ this.targetActor.off("window-destroyed", this._onWindowDestroyed);
+
+ this.callback = null;
+ this.targetActor = null;
+ },
+
+ /**
+ * Start observing whatever it is this observer is supposed to observe
+ */
+ start: function() {
+ if (this.isObserving) {
+ return;
+ }
+ this.isObserving = true;
+
+ this._startListeners(this.targetActor.windows);
+ },
+
+ /**
+ * Stop observing
+ */
+ stop: function() {
+ if (!this.isObserving) {
+ return;
+ }
+ this.isObserving = false;
+
+ if (this.targetActor.attached && this.targetActor.docShell) {
+ // It's only worth stopping if the targetActor is still attached
+ this._stopListeners(this.targetActor.windows);
+ }
+ },
+
+ _onWindowReady: function({ window }) {
+ if (this.isObserving) {
+ this._startListeners([window]);
+ }
+ },
+
+ _onWindowDestroyed: function({ window }) {
+ if (this.isObserving) {
+ this._stopListeners([window]);
+ }
+ },
+
+ _startListeners: function(windows) {
+ // To be implemented by sub-classes.
+ },
+
+ _stopListeners: function(windows) {
+ // To be implemented by sub-classes.
+ },
+
+ /**
+ * To be called by sub-classes when something has been observed
+ */
+ notifyCallback: function(...args) {
+ this.isObserving && this.callback && this.callback.apply(null, args);
+ },
+};
+
+/**
+ * The LayouChangesObserver will observe reflows as soon as it is started.
+ * Some devtools actors may cause reflows and it may be wanted to "hide" these
+ * reflows from the LayouChangesObserver consumers.
+ * If this is the case, such actors should require this module and use this
+ * global function to turn the ignore mode on and off temporarily.
+ *
+ * Note that if a node is provided, it will be used to force a sync reflow to
+ * make sure all reflows which occurred before switching the mode on or off are
+ * either observed or ignored depending on the current mode.
+ *
+ * @param {Boolean} ignore
+ * @param {DOMNode} syncReflowNode The node to use to force a sync reflow
+ */
+var gIgnoreLayoutChanges = false;
+exports.setIgnoreLayoutChanges = function(ignore, syncReflowNode) {
+ if (syncReflowNode) {
+ let forceSyncReflow = syncReflowNode.offsetWidth; // eslint-disable-line
+ }
+ gIgnoreLayoutChanges = ignore;
+};
+
+/**
+ * The LayoutChangesObserver class is instantiated only once per given tab
+ * and is used to track reflows and dom and style changes in that tab.
+ * The LayoutActor uses this class to send reflow events to its clients.
+ *
+ * This class isn't exported on the module because it shouldn't be instantiated
+ * to avoid creating several instances per tabs.
+ * Use `getLayoutChangesObserver(targetActor)`
+ * and `releaseLayoutChangesObserver(targetActor)`
+ * which are exported to get and release instances.
+ *
+ * The observer loops every EVENT_BATCHING_DELAY ms and checks if layout changes
+ * have happened since the last loop iteration. If there are, it sends the
+ * corresponding events:
+ *
+ * - "reflows", with an array of all the reflows that occured,
+ * - "resizes", with an array of all the resizes that occured,
+ *
+ * @param {BrowsingContextTargetActor} targetActor
+ */
+function LayoutChangesObserver(targetActor) {
+ this.targetActor = targetActor;
+
+ this._startEventLoop = this._startEventLoop.bind(this);
+ this._onReflow = this._onReflow.bind(this);
+ this._onResize = this._onResize.bind(this);
+
+ // Creating the various observers we're going to need
+ // For now, just the reflow observer, but later we can add markupMutation,
+ // styleSheetChanges and styleRuleChanges
+ this.reflowObserver = new ReflowObserver(this.targetActor, this._onReflow);
+ this.resizeObserver = new WindowResizeObserver(
+ this.targetActor,
+ this._onResize
+ );
+
+ EventEmitter.decorate(this);
+}
+
+exports.LayoutChangesObserver = LayoutChangesObserver;
+
+LayoutChangesObserver.prototype = {
+ /**
+ * How long does this observer waits before emitting batched events.
+ * The lower the value, the more event packets will be sent to clients,
+ * potentially impacting performance.
+ * The higher the value, the more time we'll wait, this is better for
+ * performance but has an effect on how soon changes are shown in the toolbox.
+ */
+ EVENT_BATCHING_DELAY: 300,
+
+ /**
+ * Destroying this instance of LayoutChangesObserver will stop the batched
+ * events from being sent.
+ */
+ destroy: function() {
+ this.isObserving = false;
+
+ this.reflowObserver.destroy();
+ this.reflows = null;
+
+ this.resizeObserver.destroy();
+ this.hasResized = false;
+
+ this.targetActor = null;
+ },
+
+ start: function() {
+ if (this.isObserving) {
+ return;
+ }
+ this.isObserving = true;
+
+ this.reflows = [];
+ this.hasResized = false;
+
+ this._startEventLoop();
+
+ this.reflowObserver.start();
+ this.resizeObserver.start();
+ },
+
+ stop: function() {
+ if (!this.isObserving) {
+ return;
+ }
+ this.isObserving = false;
+
+ this._stopEventLoop();
+
+ this.reflows = [];
+ this.hasResized = false;
+
+ this.reflowObserver.stop();
+ this.resizeObserver.stop();
+ },
+
+ /**
+ * Start the event loop, which regularly checks if there are any observer
+ * events to be sent as batched events
+ * Calls itself in a loop.
+ */
+ _startEventLoop: function() {
+ // Avoid emitting events if the targetActor has been detached (may happen
+ // during shutdown)
+ if (!this.targetActor || !this.targetActor.attached) {
+ return;
+ }
+
+ // Send any reflows we have
+ if (this.reflows && this.reflows.length) {
+ this.emit("reflows", this.reflows);
+ this.reflows = [];
+ }
+
+ // Send any resizes we have
+ if (this.hasResized) {
+ this.emit("resize");
+ this.hasResized = false;
+ }
+
+ this.eventLoopTimer = this._setTimeout(
+ this._startEventLoop,
+ this.EVENT_BATCHING_DELAY
+ );
+ },
+
+ _stopEventLoop: function() {
+ this._clearTimeout(this.eventLoopTimer);
+ },
+
+ // Exposing set/clearTimeout here to let tests override them if needed
+ _setTimeout: function(cb, ms) {
+ return setTimeout(cb, ms);
+ },
+ _clearTimeout: function(t) {
+ return clearTimeout(t);
+ },
+
+ /**
+ * Executed whenever a reflow is observed. Only stacks the reflow in the
+ * reflows array.
+ * The EVENT_BATCHING_DELAY loop will take care of it later.
+ * @param {Number} start When the reflow started
+ * @param {Number} end When the reflow ended
+ * @param {Boolean} isInterruptible
+ */
+ _onReflow: function(start, end, isInterruptible) {
+ if (gIgnoreLayoutChanges) {
+ return;
+ }
+
+ // XXX: when/if bug 997092 gets fixed, we will be able to know which
+ // elements have been reflowed, which would be a nice thing to add here.
+ this.reflows.push({
+ start: start,
+ end: end,
+ isInterruptible: isInterruptible,
+ });
+ },
+
+ /**
+ * Executed whenever a resize is observed. Only store a flag saying that a
+ * resize occured.
+ * The EVENT_BATCHING_DELAY loop will take care of it later.
+ */
+ _onResize: function() {
+ if (gIgnoreLayoutChanges) {
+ return;
+ }
+
+ this.hasResized = true;
+ },
+};
+
+/**
+ * Get a LayoutChangesObserver instance for a given window. This function makes
+ * sure there is only one instance per window.
+ * @param {BrowsingContextTargetActor} targetActor
+ * @return {LayoutChangesObserver}
+ */
+var observedWindows = new Map();
+function getLayoutChangesObserver(targetActor) {
+ const observerData = observedWindows.get(targetActor);
+ if (observerData) {
+ observerData.refCounting++;
+ return observerData.observer;
+ }
+
+ const obs = new LayoutChangesObserver(targetActor);
+ observedWindows.set(targetActor, {
+ observer: obs,
+ // counting references allows to stop the observer when no targetActor owns an
+ // instance.
+ refCounting: 1,
+ });
+ obs.start();
+ return obs;
+}
+exports.getLayoutChangesObserver = getLayoutChangesObserver;
+
+/**
+ * Release a LayoutChangesObserver instance that was retrieved by
+ * getLayoutChangesObserver. This is required to ensure the targetActor reference
+ * is removed and the observer is eventually stopped and destroyed.
+ * @param {BrowsingContextTargetActor} targetActor
+ */
+function releaseLayoutChangesObserver(targetActor) {
+ const observerData = observedWindows.get(targetActor);
+ if (!observerData) {
+ return;
+ }
+
+ observerData.refCounting--;
+ if (!observerData.refCounting) {
+ observerData.observer.destroy();
+ observedWindows.delete(targetActor);
+ }
+}
+exports.releaseLayoutChangesObserver = releaseLayoutChangesObserver;
+
+/**
+ * Reports any reflow that occurs in the targetActor's docshells.
+ * @extends Observable
+ * @param {BrowsingContextTargetActor} targetActor
+ * @param {Function} callback Executed everytime a reflow occurs
+ */
+class ReflowObserver extends Observable {
+ constructor(targetActor, callback) {
+ super(targetActor, callback);
+ }
+
+ _startListeners(windows) {
+ for (const window of windows) {
+ window.docShell.addWeakReflowObserver(this);
+ }
+ }
+
+ _stopListeners(windows) {
+ for (const window of windows) {
+ try {
+ window.docShell.removeWeakReflowObserver(this);
+ } catch (e) {
+ // Corner cases where a global has already been freed may happen, in
+ // which case, no need to remove the observer.
+ }
+ }
+ }
+
+ reflow(start, end) {
+ this.notifyCallback(start, end, false);
+ }
+
+ reflowInterruptible(start, end) {
+ this.notifyCallback(start, end, true);
+ }
+}
+
+ReflowObserver.prototype.QueryInterface = ChromeUtils.generateQI([
+ "nsIReflowObserver",
+ "nsISupportsWeakReference",
+]);
+
+/**
+ * Reports window resize events on the targetActor's windows.
+ * @extends Observable
+ * @param {BrowsingContextTargetActor} targetActor
+ * @param {Function} callback Executed everytime a resize occurs
+ */
+class WindowResizeObserver extends Observable {
+ constructor(targetActor, callback) {
+ super(targetActor, callback);
+
+ this.onNavigate = this.onNavigate.bind(this);
+ this.onResize = this.onResize.bind(this);
+
+ this.targetActor.on("navigate", this.onNavigate);
+ }
+
+ _startListeners() {
+ this.listenerTarget.addEventListener("resize", this.onResize);
+ }
+
+ _stopListeners() {
+ this.listenerTarget.removeEventListener("resize", this.onResize);
+ }
+
+ onNavigate() {
+ if (this.isObserving) {
+ this._stopListeners();
+ this._startListeners();
+ }
+ }
+
+ onResize() {
+ this.notifyCallback();
+ }
+
+ destroy() {
+ this.targetActor.off("navigate", this.onNavigate);
+ }
+
+ get listenerTarget() {
+ // For the rootActor, return its window.
+ if (this.targetActor.isRootActor) {
+ return this.targetActor.window;
+ }
+
+ // Otherwise, get the targetActor's chromeEventHandler.
+ return this.targetActor.chromeEventHandler;
+ }
+}
diff --git a/devtools/server/actors/resources/console-messages.js b/devtools/server/actors/resources/console-messages.js
new file mode 100644
index 0000000000..e5d92d729c
--- /dev/null
+++ b/devtools/server/actors/resources/console-messages.js
@@ -0,0 +1,247 @@
+/* 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";
+
+const {
+ TYPES: { CONSOLE_MESSAGE },
+} = require("devtools/server/actors/resources/index");
+const { WebConsoleUtils } = require("devtools/server/actors/webconsole/utils");
+
+const consoleAPIListenerModule = isWorker
+ ? "devtools/server/actors/webconsole/worker-listeners"
+ : "devtools/server/actors/webconsole/listeners/console-api";
+const { ConsoleAPIListener } = require(consoleAPIListenerModule);
+
+const { isArray } = require("devtools/server/actors/object/utils");
+
+const {
+ makeDebuggeeValue,
+ createValueGripForTarget,
+} = require("devtools/server/actors/object/utils");
+
+const {
+ getActorIdForInternalSourceId,
+} = require("devtools/server/actors/utils/dbg-source");
+
+/**
+ * Start watching for all console messages related to a given Target Actor.
+ * This will notify about existing console messages, but also the one created in future.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe console messages
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+class ConsoleMessageWatcher {
+ async watch(targetActor, { onAvailable }) {
+ // The following code expects the ThreadActor to be instantiated, via:
+ // prepareConsoleMessageForRemote > SourcesManager.getActorIdForInternalSourceId
+ // The Thread Actor is instantiated via Target.attach, but we should
+ // probably review this and only instantiate the actor instead of attaching the target.
+ if (!targetActor.threadActor) {
+ targetActor.attach();
+ }
+
+ // Bug 1642297: Maybe we could merge ConsoleAPI Listener into this module?
+ const onConsoleAPICall = message => {
+ onAvailable([
+ {
+ resourceType: CONSOLE_MESSAGE,
+ message: prepareConsoleMessageForRemote(targetActor, message),
+ },
+ ]);
+ };
+
+ // Create the consoleAPIListener
+ // (and apply the filtering options defined in the target actor).
+ const listener = new ConsoleAPIListener(
+ targetActor.window,
+ onConsoleAPICall,
+ targetActor.consoleAPIListenerOptions
+ );
+ this.listener = listener;
+ listener.init();
+
+ // It can happen that the targetActor does not have a window reference (e.g. in worker
+ // thread, targetActor exposes a workerGlobal property)
+ const winStartTime =
+ targetActor.window?.performance?.timing?.navigationStart || 0;
+
+ const cachedMessages = listener.getCachedMessages(!targetActor.isRootActor);
+ const messages = [];
+ // Filter out messages that came from a ServiceWorker but happened
+ // before the page was requested.
+ for (const message of cachedMessages) {
+ if (
+ message.innerID === "ServiceWorker" &&
+ winStartTime > message.timeStamp
+ ) {
+ continue;
+ }
+ messages.push({
+ resourceType: CONSOLE_MESSAGE,
+ message: prepareConsoleMessageForRemote(targetActor, message),
+ });
+ }
+ onAvailable(messages);
+ }
+
+ /**
+ * Stop watching for console messages.
+ */
+ destroy() {
+ if (this.listener) {
+ this.listener.destroy();
+ }
+ }
+
+ /**
+ * Called by devtools/server/actors/utils/logEvent.js, whenever a new
+ * log point is triggered and request to spawn a console message
+ *
+ * @param Object message
+ * A fake nsIConsoleMessage, which looks like the one being generated by
+ * the platform API.
+ */
+ onLogPoint(message) {
+ if (!this.listener) {
+ throw new Error("This target actor isn't listening to console messages");
+ }
+ this.listener.handler(message);
+ }
+}
+
+module.exports = ConsoleMessageWatcher;
+
+/**
+ * Return the properties needed to display the appropriate table for a given
+ * console.table call.
+ * This function does a little more than creating an ObjectActor for the first
+ * parameter of the message. When layout out the console table in the output, we want
+ * to be able to look into sub-properties so the table can have a different layout (
+ * for arrays of arrays, objects with objects properties, arrays of objects, …).
+ * So here we need to retrieve the properties of the first parameter, and also all the
+ * sub-properties we might need.
+ *
+ * @param {TargetActor} targetActor: The Target Actor from which this object originates.
+ * @param {Object} result: The console.table message.
+ * @returns {Object} An object containing the properties of the first argument of the
+ * console.table call.
+ */
+function getConsoleTableMessageItems(targetActor, result) {
+ if (
+ !result ||
+ !Array.isArray(result.arguments) ||
+ result.arguments.length == 0
+ ) {
+ return null;
+ }
+
+ const [tableItemGrip] = result.arguments;
+ const dataType = tableItemGrip.class;
+ const needEntries = ["Map", "WeakMap", "Set", "WeakSet"].includes(dataType);
+ const ignoreNonIndexedProperties = isArray(tableItemGrip);
+
+ const tableItemActor = targetActor.getActorByID(tableItemGrip.actor);
+ if (!tableItemActor) {
+ return null;
+ }
+
+ // Retrieve the properties (or entries for Set/Map) of the console table first arg.
+ const iterator = needEntries
+ ? tableItemActor.enumEntries()
+ : tableItemActor.enumProperties({
+ ignoreNonIndexedProperties,
+ });
+ const { ownProperties } = iterator.all();
+
+ // The iterator returns a descriptor for each property, wherein the value could be
+ // in one of those sub-property.
+ const descriptorKeys = ["safeGetterValues", "getterValue", "value"];
+
+ Object.values(ownProperties).forEach(desc => {
+ if (typeof desc !== "undefined") {
+ descriptorKeys.forEach(key => {
+ if (desc && desc.hasOwnProperty(key)) {
+ const grip = desc[key];
+
+ // We need to load sub-properties as well to render the table in a nice way.
+ const actor = grip && targetActor.getActorByID(grip.actor);
+ if (actor) {
+ const res = actor
+ .enumProperties({
+ ignoreNonIndexedProperties: isArray(grip),
+ })
+ .all();
+ if (res?.ownProperties) {
+ desc[key].ownProperties = res.ownProperties;
+ }
+ }
+ }
+ });
+ }
+ });
+
+ return ownProperties;
+}
+
+/**
+ * Prepare a message from the console API to be sent to the remote Web Console
+ * instance.
+ *
+ * @param TargetActor targetActor
+ * The related target actor
+ * @param object message
+ * The original message received from console-api-log-event.
+ * @return object
+ * The object that can be sent to the remote client.
+ */
+function prepareConsoleMessageForRemote(targetActor, message) {
+ const result = WebConsoleUtils.cloneObject(message);
+
+ result.workerType = WebConsoleUtils.getWorkerType(result) || "none";
+ result.sourceId = getActorIdForInternalSourceId(targetActor, result.sourceId);
+
+ delete result.wrappedJSObject;
+ delete result.ID;
+ delete result.innerID;
+ delete result.consoleID;
+
+ if (result.stacktrace) {
+ result.stacktrace = result.stacktrace.map(frame => {
+ return {
+ ...frame,
+ sourceId: getActorIdForInternalSourceId(targetActor, frame.sourceId),
+ };
+ });
+ }
+
+ result.arguments = (message.arguments || []).map(obj => {
+ const dbgObj = makeDebuggeeValue(targetActor, obj);
+ return createValueGripForTarget(targetActor, dbgObj);
+ });
+
+ result.styles = (message.styles || []).map(string => {
+ return createValueGripForTarget(targetActor, string);
+ });
+
+ if (result.level === "table") {
+ const tableItems = getConsoleTableMessageItems(targetActor, result);
+ if (tableItems) {
+ result.arguments[0].ownProperties = tableItems;
+ result.arguments[0].preview = null;
+ }
+
+ // Only return the 2 first params.
+ result.arguments = result.arguments.slice(0, 2);
+ }
+
+ result.category = message.category || "webdev";
+ result.innerWindowID = message.innerID;
+
+ return result;
+}
diff --git a/devtools/server/actors/resources/css-changes.js b/devtools/server/actors/resources/css-changes.js
new file mode 100644
index 0000000000..ba4d424ffb
--- /dev/null
+++ b/devtools/server/actors/resources/css-changes.js
@@ -0,0 +1,42 @@
+/* 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";
+
+const {
+ TYPES: { CSS_CHANGE },
+} = require("devtools/server/actors/resources/index");
+const TrackChangeEmitter = require("devtools/server/actors/utils/track-change-emitter");
+
+/**
+ * Start watching for all css changes related to a given Target Actor.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe css changes.
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+class CSSChangeWatcher {
+ constructor() {
+ this.onTrackChange = this.onTrackChange.bind(this);
+ }
+
+ async watch(targetActor, { onAvailable }) {
+ this.onAvailable = onAvailable;
+ TrackChangeEmitter.on("track-change", this.onTrackChange);
+ }
+
+ onTrackChange(change) {
+ change.resourceType = CSS_CHANGE;
+ this.onAvailable([change]);
+ }
+
+ destroy() {
+ TrackChangeEmitter.off("track-change", this.onTrackChange);
+ }
+}
+
+module.exports = CSSChangeWatcher;
diff --git a/devtools/server/actors/resources/css-messages.js b/devtools/server/actors/resources/css-messages.js
new file mode 100644
index 0000000000..1e3f901880
--- /dev/null
+++ b/devtools/server/actors/resources/css-messages.js
@@ -0,0 +1,133 @@
+/* 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";
+
+const nsIConsoleListenerWatcher = require("devtools/server/actors/resources/utils/nsi-console-listener-watcher");
+const { Ci } = require("chrome");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const { createStringGrip } = require("devtools/server/actors/object/utils");
+const {
+ getActorIdForInternalSourceId,
+} = require("devtools/server/actors/utils/dbg-source");
+
+const {
+ TYPES: { CSS_MESSAGE },
+} = require("devtools/server/actors/resources/index");
+
+const { MESSAGE_CATEGORY } = require("devtools/shared/constants");
+
+class CSSMessageWatcher extends nsIConsoleListenerWatcher {
+ /**
+ * Start watching for all CSS messages related to a given Target Actor.
+ * This will notify about existing messages, but also the one created in future.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe messages
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+ async watch(targetActor, { onAvailable }) {
+ super.watch(targetActor, { onAvailable });
+
+ // Calling ensureCSSErrorReportingEnabled will make the server parse the stylesheets to
+ // retrieve the warnings if the docShell wasn't already watching for CSS messages.
+ if (targetActor.ensureCSSErrorReportingEnabled) {
+ targetActor.ensureCSSErrorReportingEnabled();
+ }
+ }
+
+ /**
+ * Returns true if the message is considered a CSS message, and as a result, should
+ * be sent to the client.
+ *
+ * @param {nsIConsoleMessage|nsIScriptError} message
+ */
+ shouldHandleMessage(targetActor, message) {
+ // The listener we use can be called either with a nsIConsoleMessage or as nsIScriptError.
+ // In this file, we want to ignore anything but nsIScriptError.
+ if (
+ // We only care about CSS Parser nsIScriptError
+ !(message instanceof Ci.nsIScriptError) ||
+ message.category !== MESSAGE_CATEGORY.CSS_PARSER
+ ) {
+ return false;
+ }
+
+ // Process targets listen for everything but messages from private windows.
+ if (this.isProcessTarget(targetActor)) {
+ return !message.isFromPrivateWindow;
+ }
+
+ if (!message.innerWindowID) {
+ return false;
+ }
+
+ const { window } = targetActor;
+ const win = window?.WindowGlobalChild?.getByInnerWindowId(
+ message.innerWindowID
+ );
+ return targetActor.browserId === win?.browsingContext?.browserId;
+ }
+
+ /**
+ * Prepare an nsIScriptError to be sent to the client.
+ *
+ * @param nsIScriptError error
+ * The page error we need to send to the client.
+ * @return object
+ * The object you can send to the remote client.
+ */
+ buildResource(targetActor, error) {
+ const stack = this.prepareStackForRemote(targetActor, error.stack);
+ let lineText = error.sourceLine;
+ if (
+ lineText &&
+ lineText.length > DevToolsServer.LONG_STRING_INITIAL_LENGTH
+ ) {
+ lineText = lineText.substr(0, DevToolsServer.LONG_STRING_INITIAL_LENGTH);
+ }
+
+ const notesArray = this.prepareNotesForRemote(targetActor, error.notes);
+
+ // If there is no location information in the error but we have a stack,
+ // fill in the location with the first frame on the stack.
+ let { sourceName, sourceId, lineNumber, columnNumber } = error;
+ if (!sourceName && !sourceId && !lineNumber && !columnNumber && stack) {
+ sourceName = stack[0].filename;
+ sourceId = stack[0].sourceId;
+ lineNumber = stack[0].lineNumber;
+ columnNumber = stack[0].columnNumber;
+ }
+
+ const pageError = {
+ errorMessage: createStringGrip(targetActor, error.errorMessage),
+ sourceName,
+ sourceId: getActorIdForInternalSourceId(targetActor, sourceId),
+ lineText,
+ lineNumber,
+ columnNumber,
+ category: error.category,
+ innerWindowID: error.innerWindowID,
+ timeStamp: error.timeStamp,
+ warning: !!(error.flags & error.warningFlag),
+ error: !(error.flags & (error.warningFlag | error.infoFlag)),
+ info: !!(error.flags & error.infoFlag),
+ private: error.isFromPrivateWindow,
+ stacktrace: stack,
+ notes: notesArray,
+ chromeContext: error.isFromChromeContext,
+ isForwardedFromContentProcess: error.isForwardedFromContentProcess,
+ };
+
+ return {
+ pageError,
+ resourceType: CSS_MESSAGE,
+ cssSelectors: error.cssSelectors,
+ };
+ }
+}
+module.exports = CSSMessageWatcher;
diff --git a/devtools/server/actors/resources/document-event.js b/devtools/server/actors/resources/document-event.js
new file mode 100644
index 0000000000..f39d7f3f9a
--- /dev/null
+++ b/devtools/server/actors/resources/document-event.js
@@ -0,0 +1,52 @@
+/* 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";
+
+const {
+ TYPES: { DOCUMENT_EVENT },
+} = require("devtools/server/actors/resources/index");
+const {
+ DocumentEventsListener,
+} = require("devtools/server/actors/webconsole/listeners/document-events");
+
+class DocumentEventWatcher {
+ /**
+ * Start watching for all document event related to a given Target Actor.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe document event
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+ async watch(targetActor, { onAvailable }) {
+ if (isWorker) {
+ return;
+ }
+
+ const onDocumentEvent = (name, time) => {
+ onAvailable([
+ {
+ resourceType: DOCUMENT_EVENT,
+ name,
+ time,
+ },
+ ]);
+ };
+
+ this.listener = new DocumentEventsListener(targetActor);
+ this.listener.on("*", onDocumentEvent);
+ this.listener.listen();
+ }
+
+ destroy() {
+ if (this.listener) {
+ this.listener.destroy();
+ }
+ }
+}
+
+module.exports = DocumentEventWatcher;
diff --git a/devtools/server/actors/resources/error-messages.js b/devtools/server/actors/resources/error-messages.js
new file mode 100644
index 0000000000..bd388bb415
--- /dev/null
+++ b/devtools/server/actors/resources/error-messages.js
@@ -0,0 +1,158 @@
+/* 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";
+
+const nsIConsoleListenerWatcher = require("devtools/server/actors/resources/utils/nsi-console-listener-watcher");
+const { Ci } = require("chrome");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const ErrorDocs = require("devtools/server/actors/errordocs");
+const {
+ createStringGrip,
+ makeDebuggeeValue,
+ createValueGripForTarget,
+} = require("devtools/server/actors/object/utils");
+const {
+ getActorIdForInternalSourceId,
+} = require("devtools/server/actors/utils/dbg-source");
+
+const {
+ TYPES: { ERROR_MESSAGE },
+} = require("devtools/server/actors/resources/index");
+const { MESSAGE_CATEGORY } = require("devtools/shared/constants");
+
+const PLATFORM_SPECIFIC_CATEGORIES = [
+ "XPConnect JavaScript",
+ "component javascript",
+ "chrome javascript",
+ "chrome registration",
+];
+
+class ErrorMessageWatcher extends nsIConsoleListenerWatcher {
+ shouldHandleMessage(targetActor, message) {
+ // The listener we use can be called either with a nsIConsoleMessage or a nsIScriptError.
+ // In this file, we only want to handle nsIScriptError.
+ if (
+ // We only care about nsIScriptError
+ !(message instanceof Ci.nsIScriptError) ||
+ !this.isCategoryAllowed(targetActor, message.category) ||
+ // Block any error that was triggered by eager evaluation
+ message.sourceName === "debugger eager eval code"
+ ) {
+ return false;
+ }
+
+ // Process targets listen for everything but messages from private windows
+ if (this.isProcessTarget(targetActor)) {
+ return !message.isFromPrivateWindow;
+ }
+
+ if (!message.innerWindowID) {
+ return false;
+ }
+
+ const { window } = targetActor;
+ const win = window?.WindowGlobalChild?.getByInnerWindowId(
+ message.innerWindowID
+ );
+ return targetActor.browserId === win?.browsingContext?.browserId;
+ }
+
+ /**
+ * Check if the given message category is allowed to be tracked or not.
+ * We ignore chrome-originating errors as we only care about content.
+ *
+ * @param string category
+ * The message category you want to check.
+ * @return boolean
+ * True if the category is allowed to be logged, false otherwise.
+ */
+ isCategoryAllowed(targetActor, category) {
+ // CSS Parser errors will be handled by the CSSMessageWatcher.
+ if (!category || category === MESSAGE_CATEGORY.CSS_PARSER) {
+ return false;
+ }
+
+ // We listen for everything on Process targets
+ if (this.isProcessTarget(targetActor)) {
+ return true;
+ }
+
+ // For non-process targets, we filter-out platform-specific errors.
+ return !PLATFORM_SPECIFIC_CATEGORIES.includes(category);
+ }
+
+ /**
+ * Prepare an nsIScriptError to be sent to the client.
+ *
+ * @param nsIScriptError error
+ * The page error we need to send to the client.
+ * @return object
+ * The object you can send to the remote client.
+ */
+ buildResource(targetActor, error) {
+ const stack = this.prepareStackForRemote(targetActor, error.stack);
+ let lineText = error.sourceLine;
+ if (
+ lineText &&
+ lineText.length > DevToolsServer.LONG_STRING_INITIAL_LENGTH
+ ) {
+ lineText = lineText.substr(0, DevToolsServer.LONG_STRING_INITIAL_LENGTH);
+ }
+
+ const notesArray = this.prepareNotesForRemote(targetActor, error.notes);
+
+ // If there is no location information in the error but we have a stack,
+ // fill in the location with the first frame on the stack.
+ let { sourceName, sourceId, lineNumber, columnNumber } = error;
+ if (!sourceName && !sourceId && !lineNumber && !columnNumber && stack) {
+ sourceName = stack[0].filename;
+ sourceId = stack[0].sourceId;
+ lineNumber = stack[0].lineNumber;
+ columnNumber = stack[0].columnNumber;
+ }
+
+ const pageError = {
+ errorMessage: createStringGrip(targetActor, error.errorMessage),
+ errorMessageName: error.errorMessageName,
+ exceptionDocURL: ErrorDocs.GetURL(error),
+ sourceName,
+ sourceId: getActorIdForInternalSourceId(targetActor, sourceId),
+ lineText,
+ lineNumber,
+ columnNumber,
+ category: error.category,
+ innerWindowID: error.innerWindowID,
+ timeStamp: error.timeStamp,
+ warning: !!(error.flags & error.warningFlag),
+ error: !(error.flags & (error.warningFlag | error.infoFlag)),
+ info: !!(error.flags & error.infoFlag),
+ private: error.isFromPrivateWindow,
+ stacktrace: stack,
+ notes: notesArray,
+ chromeContext: error.isFromChromeContext,
+ isPromiseRejection: error.isPromiseRejection,
+ isForwardedFromContentProcess: error.isForwardedFromContentProcess,
+ };
+
+ // If the pageError does have an exception object, we want to return the grip for it,
+ // but only if we do manage to get the grip, as we're checking the property on the
+ // client to render things differently.
+ if (error.hasException) {
+ try {
+ const obj = makeDebuggeeValue(targetActor, error.exception);
+ if (obj?.class !== "DeadObject") {
+ pageError.exception = createValueGripForTarget(targetActor, obj);
+ pageError.hasException = true;
+ }
+ } catch (e) {}
+ }
+
+ return {
+ pageError,
+ resourceType: ERROR_MESSAGE,
+ };
+ }
+}
+module.exports = ErrorMessageWatcher;
diff --git a/devtools/server/actors/resources/index.js b/devtools/server/actors/resources/index.js
new file mode 100644
index 0000000000..3d5adf98f5
--- /dev/null
+++ b/devtools/server/actors/resources/index.js
@@ -0,0 +1,301 @@
+/* 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";
+
+const Targets = require("devtools/server/actors/targets/index");
+
+const TYPES = {
+ CONSOLE_MESSAGE: "console-message",
+ CSS_CHANGE: "css-change",
+ CSS_MESSAGE: "css-message",
+ DOCUMENT_EVENT: "document-event",
+ ERROR_MESSAGE: "error-message",
+ LOCAL_STORAGE: "local-storage",
+ PLATFORM_MESSAGE: "platform-message",
+ NETWORK_EVENT: "network-event",
+ SESSION_STORAGE: "session-storage",
+ STYLESHEET: "stylesheet",
+ NETWORK_EVENT_STACKTRACE: "network-event-stacktrace",
+ SOURCE: "source",
+};
+exports.TYPES = TYPES;
+
+// Helper dictionaries, which will contain data specific to each resource type.
+// - `path` is the absolute path to the module defining the Resource Watcher class,
+// Also see the attributes added by `augmentResourceDictionary` for each type:
+// - `watchers` is a weak map which will store Resource Watchers
+// (i.e. devtools/server/actors/resources/ class instances)
+// keyed by target actor -or- watcher actor.
+// - `WatcherClass` is a shortcut to the Resource Watcher module.
+// Each module exports a Resource Watcher class.
+// These lists are specific for the parent process and each target type.
+const FrameTargetResources = augmentResourceDictionary({
+ [TYPES.CONSOLE_MESSAGE]: {
+ path: "devtools/server/actors/resources/console-messages",
+ },
+ [TYPES.CSS_CHANGE]: {
+ path: "devtools/server/actors/resources/css-changes",
+ },
+ [TYPES.CSS_MESSAGE]: {
+ path: "devtools/server/actors/resources/css-messages",
+ },
+ [TYPES.DOCUMENT_EVENT]: {
+ path: "devtools/server/actors/resources/document-event",
+ },
+ [TYPES.ERROR_MESSAGE]: {
+ path: "devtools/server/actors/resources/error-messages",
+ },
+ [TYPES.LOCAL_STORAGE]: {
+ path: "devtools/server/actors/resources/storage-local-storage",
+ },
+ [TYPES.PLATFORM_MESSAGE]: {
+ path: "devtools/server/actors/resources/platform-messages",
+ },
+ [TYPES.SESSION_STORAGE]: {
+ path: "devtools/server/actors/resources/storage-session-storage",
+ },
+ [TYPES.STYLESHEET]: {
+ path: "devtools/server/actors/resources/stylesheets",
+ },
+ [TYPES.NETWORK_EVENT_STACKTRACE]: {
+ path: "devtools/server/actors/resources/network-events-stacktraces",
+ },
+ [TYPES.SOURCE]: {
+ path: "devtools/server/actors/resources/sources",
+ },
+});
+const ProcessTargetResources = augmentResourceDictionary({
+ [TYPES.CONSOLE_MESSAGE]: {
+ path: "devtools/server/actors/resources/console-messages",
+ },
+ [TYPES.CSS_MESSAGE]: {
+ path: "devtools/server/actors/resources/css-messages",
+ },
+ [TYPES.ERROR_MESSAGE]: {
+ path: "devtools/server/actors/resources/error-messages",
+ },
+ [TYPES.PLATFORM_MESSAGE]: {
+ path: "devtools/server/actors/resources/platform-messages",
+ },
+ [TYPES.SOURCE]: {
+ path: "devtools/server/actors/resources/sources",
+ },
+});
+
+// We'll only support a few resource types in Workers (console-message, source,
+// breakpoints, …) as error and platform messages are not supported since we need access
+// to Ci, which isn't available in worker context.
+// Errors are emitted from the content process main thread so the user would still get them.
+const WorkerTargetResources = augmentResourceDictionary({
+ [TYPES.CONSOLE_MESSAGE]: {
+ path: "devtools/server/actors/resources/console-messages",
+ },
+ [TYPES.SOURCE]: {
+ path: "devtools/server/actors/resources/sources",
+ },
+});
+
+const ParentProcessResources = augmentResourceDictionary({
+ [TYPES.NETWORK_EVENT]: {
+ path: "devtools/server/actors/resources/network-events",
+ },
+});
+
+function augmentResourceDictionary(dict) {
+ for (const resource of Object.values(dict)) {
+ resource.watchers = new WeakMap();
+
+ loader.lazyRequireGetter(resource, "WatcherClass", resource.path);
+ }
+ return dict;
+}
+
+/**
+ * For a given actor, return the related dictionary defined just before,
+ * that contains info about how to listen for a given resource type, from a given actor.
+ *
+ * @param Actor watcherOrTargetActor
+ * Either a WatcherActor or a TargetActor which can be listening to a resource.
+ */
+function getResourceTypeDictionary(watcherOrTargetActor) {
+ const { typeName } = watcherOrTargetActor;
+ if (typeName == "watcher") {
+ return ParentProcessResources;
+ }
+ const { targetType } = watcherOrTargetActor;
+ return getResourceTypeDictionaryForTargetType(targetType);
+}
+
+/**
+ * For a targetType, return the related dictionary.
+ *
+ * @param String targetType
+ * A targetType string (See Targets.TYPES)
+ */
+function getResourceTypeDictionaryForTargetType(targetType) {
+ switch (targetType) {
+ case Targets.TYPES.FRAME:
+ return FrameTargetResources;
+ case Targets.TYPES.PROCESS:
+ return ProcessTargetResources;
+ case Targets.TYPES.WORKER:
+ return WorkerTargetResources;
+ default:
+ throw new Error(`Unsupported target actor typeName '${targetType}'`);
+ }
+}
+
+/**
+ * For a given actor, return the object stored in one of the previous dictionary
+ * that contains info about how to listen for a given resource type, from a given actor.
+ *
+ * @param Actor watcherOrTargetActor
+ * Either a WatcherActor or a TargetActor which can be listening to a resource.
+ * @param String resourceType
+ * The resource type to be observed.
+ */
+function getResourceTypeEntry(watcherOrTargetActor, resourceType) {
+ const dict = getResourceTypeDictionary(watcherOrTargetActor);
+ if (!(resourceType in dict)) {
+ throw new Error(
+ `Unsupported resource type '${resourceType}' for ${watcherOrTargetActor.typeName}`
+ );
+ }
+ return dict[resourceType];
+}
+
+/**
+ * Start watching for a new list of resource types.
+ * This will also emit all already existing resources before resolving.
+ *
+ * @param Actor watcherOrTargetActor
+ * Either a WatcherActor or a TargetActor which can be listening to a resource.
+ * WatcherActor will be used for resources listened from the parent process,
+ * and TargetActor will be used for resources listened from the content process.
+ * This actor:
+ * - defines what context to observe (browsing context, process, worker, ...)
+ * Via browsingContextID, windows, docShells attributes for the target actor.
+ * Via browserId or browserElement attributes for the watcher actor.
+ * - exposes `notifyResourceAvailable` method to be notified about the available resources
+ * @param Array<String> resourceTypes
+ * List of all type of resource to listen to.
+ */
+async function watchResources(watcherOrTargetActor, resourceTypes) {
+ // If we are given a target actor, filter out the resource types supported by the target.
+ // When using sharedData to pass types between processes, we are passing them for all target types.
+ const { targetType } = watcherOrTargetActor;
+ if (targetType) {
+ resourceTypes = getResourceTypesForTargetType(resourceTypes, targetType);
+ }
+ for (const resourceType of resourceTypes) {
+ const { watchers, WatcherClass } = getResourceTypeEntry(
+ watcherOrTargetActor,
+ resourceType
+ );
+
+ // Ignore resources we're already listening to
+ if (watchers.has(watcherOrTargetActor)) {
+ continue;
+ }
+
+ const watcher = new WatcherClass();
+ await watcher.watch(watcherOrTargetActor, {
+ onAvailable: watcherOrTargetActor.notifyResourceAvailable,
+ onDestroyed: watcherOrTargetActor.notifyResourceDestroyed,
+ onUpdated: watcherOrTargetActor.notifyResourceUpdated,
+ });
+ watchers.set(watcherOrTargetActor, watcher);
+ }
+}
+exports.watchResources = watchResources;
+
+function getParentProcessResourceTypes(resourceTypes) {
+ return resourceTypes.filter(resourceType => {
+ return resourceType in ParentProcessResources;
+ });
+}
+exports.getParentProcessResourceTypes = getParentProcessResourceTypes;
+
+function getResourceTypesForTargetType(resourceTypes, targetType) {
+ const resourceDictionnary = getResourceTypeDictionaryForTargetType(
+ targetType
+ );
+ return resourceTypes.filter(resourceType => {
+ return resourceType in resourceDictionnary;
+ });
+}
+exports.getResourceTypesForTargetType = getResourceTypesForTargetType;
+
+function hasResourceTypesForTargets(resourceTypes) {
+ return resourceTypes.some(resourceType => {
+ return resourceType in FrameTargetResources;
+ });
+}
+exports.hasResourceTypesForTargets = hasResourceTypesForTargets;
+
+/**
+ * Stop watching for a list of resource types.
+ *
+ * @param Actor watcherOrTargetActor
+ * The related actor, already passed to watchResources.
+ * @param Array<String> resourceTypes
+ * List of all type of resource to stop listening to.
+ */
+function unwatchResources(watcherOrTargetActor, resourceTypes) {
+ for (const resourceType of resourceTypes) {
+ // Pull all info about this resource type from `Resources` global object
+ const { watchers } = getResourceTypeEntry(
+ watcherOrTargetActor,
+ resourceType
+ );
+
+ const watcher = watchers.get(watcherOrTargetActor);
+ if (watcher) {
+ watcher.destroy();
+ watchers.delete(watcherOrTargetActor);
+ }
+ }
+}
+exports.unwatchResources = unwatchResources;
+
+/**
+ * Stop watching for all watched resources on a given actor.
+ *
+ * @param Actor watcherOrTargetActor
+ * The related actor, already passed to watchResources.
+ */
+function unwatchAllTargetResources(watcherOrTargetActor) {
+ for (const { watchers } of Object.values(
+ getResourceTypeDictionary(watcherOrTargetActor)
+ )) {
+ const watcher = watchers.get(watcherOrTargetActor);
+ if (watcher) {
+ watcher.destroy();
+ watchers.delete(watcherOrTargetActor);
+ }
+ }
+}
+exports.unwatchAllTargetResources = unwatchAllTargetResources;
+
+/**
+ * If we are watching for the given resource type,
+ * return the current ResourceWatcher instance used by this target actor
+ * in order to observe this resource type.
+ *
+ * @param Actor watcherOrTargetActor
+ * Either a WatcherActor or a TargetActor which can be listening to a resource.
+ * WatcherActor will be used for resources listened from the parent process,
+ * and TargetActor will be used for resources listened from the content process.
+ * @param String resourceType
+ * The resource type to query
+ * @return ResourceWatcher
+ * The resource watcher instance, defined in devtools/server/actors/resources/
+ */
+function getResourceWatcher(watcherOrTargetActor, resourceType) {
+ const { watchers } = getResourceTypeEntry(watcherOrTargetActor, resourceType);
+
+ return watchers.get(watcherOrTargetActor);
+}
+exports.getResourceWatcher = getResourceWatcher;
diff --git a/devtools/server/actors/resources/moz.build b/devtools/server/actors/resources/moz.build
new file mode 100644
index 0000000000..964456ee63
--- /dev/null
+++ b/devtools/server/actors/resources/moz.build
@@ -0,0 +1,28 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "utils",
+]
+
+DevToolsModules(
+ "console-messages.js",
+ "css-changes.js",
+ "css-messages.js",
+ "document-event.js",
+ "error-messages.js",
+ "index.js",
+ "network-events-stacktraces.js",
+ "network-events.js",
+ "platform-messages.js",
+ "sources.js",
+ "storage-local-storage.js",
+ "storage-session-storage.js",
+ "stylesheets.js",
+)
+
+with Files("*-messages.js"):
+ BUG_COMPONENT = ("DevTools", "Console")
diff --git a/devtools/server/actors/resources/network-events-stacktraces.js b/devtools/server/actors/resources/network-events-stacktraces.js
new file mode 100644
index 0000000000..4dbaa55ebd
--- /dev/null
+++ b/devtools/server/actors/resources/network-events-stacktraces.js
@@ -0,0 +1,203 @@
+/* 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";
+
+const {
+ TYPES: { NETWORK_EVENT_STACKTRACE },
+} = require("devtools/server/actors/resources/index");
+
+const { Ci, components } = require("chrome");
+const Services = require("Services");
+
+loader.lazyRequireGetter(
+ this,
+ "ChannelEventSinkFactory",
+ "devtools/server/actors/network-monitor/channel-event-sink",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "matchRequest",
+ "devtools/server/actors/network-monitor/network-observer",
+ true
+);
+
+class NetworkEventStackTracesWatcher {
+ /**
+ * Start watching for all network event's stack traces related to a given Target actor.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe the strack traces
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory
+ * This will be called for each resource.
+ */
+ async watch(targetActor, { onAvailable }) {
+ Services.obs.addObserver(this, "http-on-opening-request");
+ Services.obs.addObserver(this, "document-on-opening-request");
+ Services.obs.addObserver(this, "network-monitor-alternate-stack");
+ ChannelEventSinkFactory.getService().registerCollector(this);
+
+ this.targetActor = targetActor;
+ this.onStackTraceAvailable = onAvailable;
+
+ this.stacktraces = new Map();
+ }
+
+ /**
+ * Stop watching for network event's strack traces related to a given Target Actor.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should stop observing the strack traces
+ */
+ destroy(targetActor) {
+ Services.obs.removeObserver(this, "http-on-opening-request");
+ Services.obs.removeObserver(this, "document-on-opening-request");
+ Services.obs.removeObserver(this, "network-monitor-alternate-stack");
+ ChannelEventSinkFactory.getService().unregisterCollector(this);
+ }
+
+ onChannelRedirect(oldChannel, newChannel, flags) {
+ // We can be called with any nsIChannel, but are interested only in HTTP channels
+ try {
+ oldChannel.QueryInterface(Ci.nsIHttpChannel);
+ newChannel.QueryInterface(Ci.nsIHttpChannel);
+ } catch (ex) {
+ return;
+ }
+
+ const oldId = oldChannel.channelId;
+ const stacktrace = this.stacktraces.get(oldId);
+ if (stacktrace) {
+ this._setStackTrace(newChannel.channelId, stacktrace);
+ }
+ }
+
+ observe(subject, topic, data) {
+ let channel, id;
+ try {
+ // We need to QI nsIHttpChannel in order to load the interface's
+ // methods / attributes for later code that could assume we are dealing
+ // with a nsIHttpChannel.
+ channel = subject.QueryInterface(Ci.nsIHttpChannel);
+ id = channel.channelId;
+ } catch (e1) {
+ try {
+ channel = subject.QueryInterface(Ci.nsIIdentChannel);
+ id = channel.channelId;
+ } catch (e2) {
+ // WebSocketChannels do not have IDs, so use the serial. When a WebSocket is
+ // opened in a content process, a channel is created locally but the HTTP
+ // channel for the connection lives entirely in the parent process. When
+ // the server code running in the parent sees that HTTP channel, it will
+ // look for the creation stack using the websocket's serial.
+ try {
+ channel = subject.QueryInterface(Ci.nsIWebSocketChannel);
+ id = channel.serial;
+ } catch (e3) {
+ // Channels which don't implement the above interfaces can appear here,
+ // such as nsIFileChannel. Ignore these channels.
+ return;
+ }
+ }
+ }
+
+ // XXX: is window the best filter to use?
+ if (!matchRequest(channel, { window: this.targetActor.window })) {
+ return;
+ }
+
+ if (this.stacktraces.has(id)) {
+ // We can get up to two stack traces for the same channel: one each from
+ // the two observer topics we are listening to. Use the first stack trace
+ // which is specified, and ignore any later one.
+ return;
+ }
+
+ const stacktrace = [];
+ switch (topic) {
+ case "http-on-opening-request":
+ case "document-on-opening-request": {
+ // The channel is being opened on the main thread, associate the current
+ // stack with it.
+ //
+ // Convert the nsIStackFrame XPCOM objects to a nice JSON that can be
+ // passed around through message managers etc.
+ let frame = components.stack;
+ if (frame?.caller) {
+ frame = frame.caller;
+ while (frame) {
+ stacktrace.push({
+ filename: frame.filename,
+ lineNumber: frame.lineNumber,
+ columnNumber: frame.columnNumber,
+ functionName: frame.name,
+ asyncCause: frame.asyncCause,
+ });
+ frame = frame.caller || frame.asyncCaller;
+ }
+ }
+ break;
+ }
+ case "network-monitor-alternate-stack": {
+ // An alternate stack trace is being specified for this channel.
+ // The topic data is the JSON for the saved frame stack we should use,
+ // so convert this into the expected format.
+ //
+ // This topic is used in the following cases:
+ //
+ // - The HTTP channel is opened asynchronously or on a different thread
+ // from the code which triggered its creation, in which case the stack
+ // from components.stack will be empty. The alternate stack will be
+ // for the point we want to associate with the channel.
+ //
+ // - The channel is not a nsIHttpChannel, and we will receive no
+ // opening request notification for it.
+ let frame = JSON.parse(data);
+ while (frame) {
+ stacktrace.push({
+ filename: frame.source,
+ lineNumber: frame.line,
+ columnNumber: frame.column,
+ functionName: frame.functionDisplayName,
+ asyncCause: frame.asyncCause,
+ });
+ frame = frame.parent || frame.asyncParent;
+ }
+ break;
+ }
+ default:
+ throw new Error("Unexpected observe() topic");
+ }
+
+ this._setStackTrace(id, stacktrace);
+ }
+
+ _setStackTrace(resourceId, stacktrace) {
+ this.stacktraces.set(resourceId, stacktrace);
+ this.onStackTraceAvailable([
+ {
+ resourceType: NETWORK_EVENT_STACKTRACE,
+ resourceId,
+ targetFront: this.targetFront,
+ stacktraceAvailable: stacktrace && stacktrace.length > 0,
+ lastFrame:
+ stacktrace && stacktrace.length > 0 ? stacktrace[0] : undefined,
+ },
+ ]);
+ }
+
+ getStackTrace(id) {
+ let stacktrace = [];
+ if (this.stacktraces.has(id)) {
+ stacktrace = this.stacktraces.get(id);
+ this.stacktraces.delete(id);
+ }
+ return stacktrace;
+ }
+}
+module.exports = NetworkEventStackTracesWatcher;
diff --git a/devtools/server/actors/resources/network-events.js b/devtools/server/actors/resources/network-events.js
new file mode 100644
index 0000000000..306af8c7da
--- /dev/null
+++ b/devtools/server/actors/resources/network-events.js
@@ -0,0 +1,233 @@
+/* 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";
+
+loader.lazyRequireGetter(
+ this,
+ "NetworkObserver",
+ "devtools/server/actors/network-monitor/network-observer",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "NetworkEventActor",
+ "devtools/server/actors/network-monitor/network-event-actor",
+ true
+);
+
+class NetworkEventWatcher {
+ /**
+ * Start watching for all network events related to a given Watcher Actor.
+ *
+ * @param WatcherActor watcherActor
+ * The watcher actor in the parent process from which we should
+ * observe network events.
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ * - onUpdated: optional function
+ * This would be called multiple times for each resource.
+ */
+ async watch(watcherActor, { onAvailable, onUpdated }) {
+ this.networkEvents = new Map();
+
+ this.watcherActor = watcherActor;
+ this.onNetworkEventAvailable = onAvailable;
+ this.onNetworkEventUpdated = onUpdated;
+
+ this.listener = new NetworkObserver(
+ { browserId: watcherActor.browserId },
+ { onNetworkEvent: this.onNetworkEvent.bind(this) }
+ );
+
+ this.listener.init();
+ }
+
+ /**
+ * Gets the throttle settings
+ *
+ * @return {*} data
+ *
+ */
+ getThrottleData() {
+ return this.listener.throttleData;
+ }
+
+ /**
+ * Sets the throttle data
+ *
+ * @param {*} data
+ *
+ */
+ setThrottleData(data) {
+ this.listener.throttleData = data;
+ }
+
+ /**
+ * Block requests based on the filters
+ * @param {Object} filters
+ */
+ blockRequest(filters) {
+ this.listener.blockRequest(filters);
+ }
+
+ /**
+ * Unblock requests based on the fitlers
+ * @param {Object} filters
+ */
+ unblockRequest(filters) {
+ this.listener.unblockRequest(filters);
+ }
+
+ /**
+ * Calls the listener to set blocked urls
+ *
+ * @param {Array} urls
+ * The urls to block
+ */
+
+ setBlockedUrls(urls) {
+ this.listener.setBlockedUrls(urls);
+ }
+
+ /**
+ * Calls the listener to get the blocked urls
+ *
+ * @return {Array} urls
+ * The blocked urls
+ */
+
+ getBlockedUrls() {
+ return this.listener.getBlockedUrls();
+ }
+
+ onNetworkEvent(event) {
+ const { channelId } = event;
+
+ if (this.networkEvents.has(channelId)) {
+ throw new Error(
+ `Got notified about channel ${channelId} more than once.`
+ );
+ }
+ const actor = new NetworkEventActor(
+ this,
+ {
+ onNetworkEventUpdate: this.onNetworkEventUpdate.bind(this),
+ onNetworkEventDestroy: this.onNetworkEventDestroy.bind(this),
+ },
+ event
+ );
+ this.watcherActor.manage(actor);
+
+ const resource = actor.asResource();
+
+ this.networkEvents.set(resource.resourceId, {
+ resourceId: resource.resourceId,
+ resourceType: resource.resourceType,
+ isBlocked: !!resource.blockedReason,
+ types: [],
+ resourceUpdates: {},
+ });
+
+ this.onNetworkEventAvailable([resource]);
+ return actor;
+ }
+
+ onNetworkEventUpdate(updateResource) {
+ const networkEvent = this.networkEvents.get(updateResource.resourceId);
+
+ if (!networkEvent) {
+ return;
+ }
+
+ const {
+ resourceId,
+ resourceType,
+ resourceUpdates,
+ types,
+ isBlocked,
+ } = networkEvent;
+
+ switch (updateResource.updateType) {
+ case "responseStart":
+ resourceUpdates.httpVersion = updateResource.httpVersion;
+ resourceUpdates.status = updateResource.status;
+ resourceUpdates.statusText = updateResource.statusText;
+ resourceUpdates.remoteAddress = updateResource.remoteAddress;
+ resourceUpdates.remotePort = updateResource.remotePort;
+ // The mimetype is only set when then the contentType is available
+ // in the _onResponseHeader and not for cached/service worker requests
+ // in _httpResponseExaminer.
+ resourceUpdates.mimeType = updateResource.mimeType;
+ resourceUpdates.waitingTime = updateResource.waitingTime;
+ break;
+ case "responseContent":
+ resourceUpdates.contentSize = updateResource.contentSize;
+ resourceUpdates.transferredSize = updateResource.transferredSize;
+ resourceUpdates.mimeType = updateResource.mimeType;
+ resourceUpdates.blockingExtension = updateResource.blockingExtension;
+ resourceUpdates.blockedReason = updateResource.blockedReason;
+ break;
+ case "eventTimings":
+ resourceUpdates.totalTime = updateResource.totalTime;
+ break;
+ case "securityInfo":
+ resourceUpdates.securityState = updateResource.state;
+ resourceUpdates.isRacing = updateResource.isRacing;
+ break;
+ }
+
+ resourceUpdates[`${updateResource.updateType}Available`] = true;
+ types.push(updateResource.updateType);
+
+ if (isBlocked) {
+ // Blocked requests
+ if (
+ !types.includes("requestHeaders") ||
+ !types.includes("requestCookies")
+ ) {
+ return;
+ }
+ } else if (
+ // Un-blocked requests
+ !types.includes("requestHeaders") ||
+ !types.includes("requestCookies") ||
+ !types.includes("eventTimings") ||
+ !types.includes("responseContent")
+ ) {
+ return;
+ }
+
+ this.onNetworkEventUpdated([
+ {
+ resourceType,
+ resourceId,
+ resourceUpdates,
+ },
+ ]);
+ }
+
+ onNetworkEventDestroy(channelId) {
+ if (this.networkEvents.has(channelId)) {
+ this.networkEvents.delete(channelId);
+ }
+ }
+
+ /**
+ * Stop watching for network event related to a given Watcher Actor.
+ *
+ * @param WatcherActor watcherActor
+ * The watcher actor from which we should stop observing network events
+ */
+ destroy(watcherActor) {
+ if (this.listener) {
+ this.listener.destroy();
+ }
+ }
+}
+
+module.exports = NetworkEventWatcher;
diff --git a/devtools/server/actors/resources/platform-messages.js b/devtools/server/actors/resources/platform-messages.js
new file mode 100644
index 0000000000..9e2e4d1aa2
--- /dev/null
+++ b/devtools/server/actors/resources/platform-messages.js
@@ -0,0 +1,53 @@
+/* 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";
+
+const nsIConsoleListenerWatcher = require("devtools/server/actors/resources/utils/nsi-console-listener-watcher");
+const { Ci } = require("chrome");
+
+const {
+ TYPES: { PLATFORM_MESSAGE },
+} = require("devtools/server/actors/resources/index");
+
+const { createStringGrip } = require("devtools/server/actors/object/utils");
+
+class PlatformMessageWatcher extends nsIConsoleListenerWatcher {
+ shouldHandleTarget(targetActor) {
+ return this.isProcessTarget(targetActor);
+ }
+
+ /**
+ * Returns true if the message is considered a platform message, and as a result, should
+ * be sent to the client.
+ *
+ * @param {TargetActor} targetActor
+ * @param {nsIConsoleMessage} message
+ */
+ shouldHandleMessage(targetActor, message) {
+ // The listener we use can be called either with a nsIConsoleMessage or as nsIScriptError.
+ // In this file, we want to ignore nsIScriptError, which are handled by the
+ // error-messages resource handler (See Bug 1644186).
+ if (message instanceof Ci.nsIScriptError) {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Returns an object from the nsIConsoleMessage.
+ *
+ * @param {Actor} targetActor
+ * @param {nsIConsoleMessage} message
+ */
+ buildResource(targetActor, message) {
+ return {
+ message: createStringGrip(targetActor, message.message),
+ timeStamp: message.timeStamp,
+ resourceType: PLATFORM_MESSAGE,
+ };
+ }
+}
+module.exports = PlatformMessageWatcher;
diff --git a/devtools/server/actors/resources/sources.js b/devtools/server/actors/resources/sources.js
new file mode 100644
index 0000000000..04ee4a1cc7
--- /dev/null
+++ b/devtools/server/actors/resources/sources.js
@@ -0,0 +1,69 @@
+/* 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";
+
+const {
+ TYPES: { SOURCE },
+} = require("devtools/server/actors/resources/index");
+
+/**
+ * Start watching for all JS sources related to a given Target Actor.
+ * This will notify about existing sources, but also the ones created in future.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe sources
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+class SourceWatcher {
+ constructor() {
+ this.onNewSource = this.onNewSource.bind(this);
+ }
+
+ async watch(targetActor, { onAvailable }) {
+ // Force attaching the target in order to ensure it instantiates the ThreadActor
+ targetActor.attach();
+
+ const { threadActor } = targetActor;
+ this.threadActor = threadActor;
+ this.onAvailable = onAvailable;
+
+ // Disable `ThreadActor.newSource` RDP event in order to avoid unnecessary traffic
+ threadActor.disableNewSourceEvents();
+
+ threadActor.sourcesManager.on("newSource", this.onNewSource);
+
+ // Before fetching all sources, process existing ones.
+ // The ThreadActor is already up and running before this code runs
+ // and have sources already registered and for which newSource event already fired.
+ onAvailable(
+ threadActor.sourcesManager.iter().map(s => {
+ const resource = s.form();
+ resource.resourceType = SOURCE;
+ return resource;
+ })
+ );
+
+ // Requesting all sources should end up emitting newSource on threadActor.sourcesManager
+ threadActor.addAllSources();
+ }
+
+ /**
+ * Stop watching for sources
+ */
+ destroy() {
+ this.threadActor.sourcesManager.off("newSource", this.onNewSource);
+ }
+
+ onNewSource(source) {
+ const resource = source.form();
+ resource.resourceType = SOURCE;
+ this.onAvailable([resource]);
+ }
+}
+
+module.exports = SourceWatcher;
diff --git a/devtools/server/actors/resources/storage-local-storage.js b/devtools/server/actors/resources/storage-local-storage.js
new file mode 100644
index 0000000000..0a582cba79
--- /dev/null
+++ b/devtools/server/actors/resources/storage-local-storage.js
@@ -0,0 +1,19 @@
+/* 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";
+
+const {
+ TYPES: { LOCAL_STORAGE },
+} = require("devtools/server/actors/resources/index");
+
+const ContentProcessStorage = require("devtools/server/actors/resources/utils/content-process-storage");
+
+class LocalStorageWatcher extends ContentProcessStorage {
+ constructor() {
+ super("localStorage", LOCAL_STORAGE);
+ }
+}
+
+module.exports = LocalStorageWatcher;
diff --git a/devtools/server/actors/resources/storage-session-storage.js b/devtools/server/actors/resources/storage-session-storage.js
new file mode 100644
index 0000000000..e6ad3eef88
--- /dev/null
+++ b/devtools/server/actors/resources/storage-session-storage.js
@@ -0,0 +1,19 @@
+/* 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";
+
+const {
+ TYPES: { SESSION_STORAGE },
+} = require("devtools/server/actors/resources/index");
+
+const ContentProcessStorage = require("devtools/server/actors/resources/utils/content-process-storage");
+
+class SessionStorageWatcher extends ContentProcessStorage {
+ constructor() {
+ super("sessionStorage", SESSION_STORAGE);
+ }
+}
+
+module.exports = SessionStorageWatcher;
diff --git a/devtools/server/actors/resources/stylesheets.js b/devtools/server/actors/resources/stylesheets.js
new file mode 100644
index 0000000000..40d3bf33f1
--- /dev/null
+++ b/devtools/server/actors/resources/stylesheets.js
@@ -0,0 +1,703 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const { fetch } = require("devtools/shared/DevToolsUtils");
+const InspectorUtils = require("InspectorUtils");
+const {
+ getSourcemapBaseURL,
+} = require("devtools/server/actors/utils/source-map-utils");
+
+const {
+ TYPES: { STYLESHEET },
+} = require("devtools/server/actors/resources/index");
+
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/shared/inspector/css-logic"
+);
+
+loader.lazyRequireGetter(
+ this,
+ ["addPseudoClassLock", "removePseudoClassLock"],
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "loadSheet",
+ "devtools/shared/layout/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["UPDATE_GENERAL", "UPDATE_PRESERVING_RULES"],
+ "devtools/server/actors/style-sheet",
+ true
+);
+
+const TRANSITION_PSEUDO_CLASS = ":-moz-styleeditor-transitioning";
+const TRANSITION_DURATION_MS = 500;
+const TRANSITION_BUFFER_MS = 1000;
+const TRANSITION_RULE_SELECTOR = `:root${TRANSITION_PSEUDO_CLASS}, :root${TRANSITION_PSEUDO_CLASS} *`;
+const TRANSITION_SHEET =
+ "data:text/css;charset=utf-8," +
+ encodeURIComponent(`
+ ${TRANSITION_RULE_SELECTOR} {
+ transition-duration: ${TRANSITION_DURATION_MS}ms !important;
+ transition-delay: 0ms !important;
+ transition-timing-function: ease-out !important;
+ transition-property: all !important;
+ }
+`);
+
+// If the user edits a stylesheet, we stash a copy of the edited text
+// here, keyed by the stylesheet. This way, if the tools are closed
+// and then reopened, the edited text will be available. A weak map
+// is used so that navigation by the user will eventually cause the
+// edited text to be collected.
+const modifiedStyleSheets = new WeakMap();
+
+class StyleSheetWatcher {
+ constructor() {
+ this._resourceCount = 0;
+ // The _styleSheetMap maps resourceId and following value.
+ // {
+ // styleSheet: Raw StyleSheet object.
+ // }
+ this._styleSheetMap = new Map();
+ // List of all watched media queries. Change listeners are being registered from _getMediaRules.
+ this._mqlList = [];
+
+ this._onApplicableStateChanged = this._onApplicableStateChanged.bind(this);
+ }
+
+ /**
+ * Start watching for all stylesheets related to a given Target Actor.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe css changes.
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+ async watch(targetActor, { onAvailable, onUpdated }) {
+ this._targetActor = targetActor;
+ this._onAvailable = onAvailable;
+ this._onUpdated = onUpdated;
+
+ // Listen for new stylesheet being added via StyleSheetApplicableStateChanged
+ this._targetActor.chromeEventHandler.addEventListener(
+ "StyleSheetApplicableStateChanged",
+ this._onApplicableStateChanged,
+ true
+ );
+
+ const styleSheets = [];
+
+ for (const window of this._targetActor.windows) {
+ // We have to set this flag in order to get the
+ // StyleSheetApplicableStateChanged events. See Document.webidl.
+ window.document.styleSheetChangeEventsEnabled = true;
+
+ styleSheets.push(...(await this._getStyleSheets(window)));
+ }
+
+ await this._notifyResourcesAvailable(styleSheets);
+ }
+
+ /**
+ * Create a new style sheet in the document with the given text.
+ *
+ * @param {Document} document
+ * Document that the new style sheet belong to.
+ * @param {string} text
+ * Content of style sheet.
+ * @param {string} fileName
+ * If the stylesheet adding is from file, `fileName` indicates the path.
+ */
+ async addStyleSheet(document, text, fileName) {
+ const parent = document.documentElement;
+ const style = document.createElementNS(
+ "http://www.w3.org/1999/xhtml",
+ "style"
+ );
+ style.setAttribute("type", "text/css");
+
+ if (text) {
+ style.appendChild(document.createTextNode(text));
+ }
+
+ // This triggers StyleSheetApplicableStateChanged event.
+ parent.appendChild(style);
+
+ // This promise will be resolved when the resource for this stylesheet is available.
+ let resolve = null;
+ const promise = new Promise(r => {
+ resolve = r;
+ });
+
+ if (!this._stylesheetCreationData) {
+ this._stylesheetCreationData = new WeakMap();
+ }
+ this._stylesheetCreationData.set(style.sheet, {
+ isCreatedByDevTools: true,
+ fileName,
+ resolve,
+ });
+
+ await promise;
+
+ return style.sheet;
+ }
+
+ async ensureResourceAvailable(styleSheet) {
+ if (this.getResourceId(styleSheet)) {
+ return;
+ }
+
+ await this._notifyResourcesAvailable([styleSheet]);
+ }
+
+ /**
+ * Return resourceId of the given style sheet.
+ */
+ getResourceId(styleSheet) {
+ for (const [resourceId, value] of this._styleSheetMap.entries()) {
+ if (styleSheet === value.styleSheet) {
+ return resourceId;
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Return owner node of the style sheet of the given resource id.
+ */
+ getOwnerNode(resourceId) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ return styleSheet.ownerNode;
+ }
+
+ /**
+ * Return the style sheet of the given resource id.
+ */
+ getStyleSheet(resourceId) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ return styleSheet;
+ }
+
+ /**
+ * Return the index of given stylesheet of the given resource id.
+ */
+ getStyleSheetIndex(resourceId) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ return this._getStyleSheetIndex(styleSheet);
+ }
+
+ /**
+ * Protocol method to get the text of stylesheet of resourceId.
+ */
+ async getText(resourceId) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+
+ const modifiedText = modifiedStyleSheets.get(styleSheet);
+
+ // modifiedText is the content of the stylesheet updated by update function.
+ // In case not updating, this is undefined.
+ if (modifiedText !== undefined) {
+ return modifiedText;
+ }
+
+ if (!styleSheet.href) {
+ // this is an inline <style> sheet
+ return styleSheet.ownerNode.textContent;
+ }
+
+ return this._fetchStylesheet(styleSheet);
+ }
+
+ /**
+ * Toggle the disabled property of the stylesheet
+ *
+ * @return {Boolean} the disabled state after toggling.
+ */
+ toggleDisabled(resourceId) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ styleSheet.disabled = !styleSheet.disabled;
+
+ this._notifyPropertyChanged(resourceId, "disabled", styleSheet.disabled);
+
+ return styleSheet.disabled;
+ }
+
+ /**
+ * Update the style sheet in place with new text.
+ *
+ * @param {String} resourceId
+ * @param {String} text
+ * New text.
+ * @param {Boolean} transition
+ * Whether to do CSS transition for change.
+ * @param {Number} kind
+ * Either UPDATE_PRESERVING_RULES or UPDATE_GENERAL
+ * @param {String} cause
+ * Indicates the cause of this update (e.g. "styleeditor") if this was called
+ * from the stylesheet to be edited by the user from the StyleEditor.
+ */
+ async update(
+ resourceId,
+ text,
+ transition,
+ kind = UPDATE_GENERAL,
+ cause = ""
+ ) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ InspectorUtils.parseStyleSheet(styleSheet, text);
+ modifiedStyleSheets.set(styleSheet, text);
+
+ if (kind !== UPDATE_PRESERVING_RULES) {
+ this._notifyPropertyChanged(
+ resourceId,
+ "ruleCount",
+ styleSheet.cssRules.length
+ );
+ }
+
+ if (transition) {
+ this._startTransition(resourceId, kind, cause);
+ } else {
+ this._notifyResourceUpdated(resourceId, "style-applied", {
+ event: { kind, cause },
+ });
+ }
+
+ // Remove event handler from all media query list we set to.
+ for (const mql of this._mqlList) {
+ mql.onchange = null;
+ }
+
+ const mediaRules = await this._getMediaRules(resourceId, styleSheet);
+ this._notifyResourceUpdated(resourceId, "media-rules-changed", {
+ resourceUpdates: { mediaRules },
+ });
+ }
+
+ _startTransition(resourceId, kind, cause) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ const document = styleSheet.ownerNode.ownerDocument;
+ const window = styleSheet.ownerNode.ownerGlobal;
+
+ if (!this._transitionSheetLoaded) {
+ this._transitionSheetLoaded = true;
+ // We don't remove this sheet. It uses an internal selector that
+ // we only apply via locks, so there's no need to load and unload
+ // it all the time.
+ loadSheet(window, TRANSITION_SHEET);
+ }
+
+ addPseudoClassLock(document.documentElement, TRANSITION_PSEUDO_CLASS);
+
+ // Set up clean up and commit after transition duration (+buffer)
+ // @see _onTransitionEnd
+ window.clearTimeout(this._transitionTimeout);
+ this._transitionTimeout = window.setTimeout(
+ this._onTransitionEnd.bind(this, resourceId, kind, cause),
+ TRANSITION_DURATION_MS + TRANSITION_BUFFER_MS
+ );
+ }
+
+ _onTransitionEnd(resourceId, kind, cause) {
+ const { styleSheet } = this._styleSheetMap.get(resourceId);
+ const document = styleSheet.ownerNode.ownerDocument;
+
+ this._transitionTimeout = null;
+ removePseudoClassLock(document.documentElement, TRANSITION_PSEUDO_CLASS);
+ this._notifyResourceUpdated(resourceId, "style-applied", {
+ event: { kind, cause },
+ });
+ }
+
+ async _fetchStylesheet(styleSheet) {
+ const href = styleSheet.href;
+
+ const options = {
+ loadFromCache: true,
+ policy: Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET,
+ charset: this._getCSSCharset(styleSheet),
+ };
+
+ // Bug 1282660 - We use the system principal to load the default internal
+ // stylesheets instead of the content principal since such stylesheets
+ // require system principal to load. At meanwhile, we strip the loadGroup
+ // for preventing the assertion of the userContextId mismatching.
+
+ // chrome|file|resource|moz-extension protocols rely on the system principal.
+ const excludedProtocolsRe = /^(chrome|file|resource|moz-extension):\/\//;
+ if (!excludedProtocolsRe.test(href)) {
+ // Stylesheets using other protocols should use the content principal.
+ if (styleSheet.ownerNode) {
+ // eslint-disable-next-line mozilla/use-ownerGlobal
+ options.window = styleSheet.ownerNode.ownerDocument.defaultView;
+ options.principal = styleSheet.ownerNode.ownerDocument.nodePrincipal;
+ }
+ }
+
+ let result;
+
+ try {
+ result = await fetch(href, options);
+ } catch (e) {
+ // The list of excluded protocols can be missing some protocols, try to use the
+ // system principal if the first fetch failed.
+ console.error(
+ `stylesheets: fetch failed for ${href},` +
+ ` using system principal instead.`
+ );
+ options.window = undefined;
+ options.principal = undefined;
+ result = await fetch(href, options);
+ }
+
+ return result.content;
+ }
+
+ _getCSSCharset(styleSheet) {
+ if (styleSheet) {
+ // charset attribute of <link> or <style> element, if it exists
+ if (styleSheet.ownerNode?.getAttribute) {
+ const linkCharset = styleSheet.ownerNode.getAttribute("charset");
+ if (linkCharset != null) {
+ return linkCharset;
+ }
+ }
+
+ // charset of referring document.
+ if (styleSheet.ownerNode?.ownerDocument.characterSet) {
+ return styleSheet.ownerNode.ownerDocument.characterSet;
+ }
+ }
+
+ return "UTF-8";
+ }
+
+ _getCSSRules(styleSheet) {
+ try {
+ return styleSheet.cssRules;
+ } catch (e) {
+ // sheet isn't loaded yet
+ }
+
+ if (!styleSheet.ownerNode) {
+ return Promise.resolve([]);
+ }
+
+ return new Promise(resolve => {
+ styleSheet.ownerNode.addEventListener(
+ "load",
+ () => resolve(styleSheet.cssRules),
+ { once: true }
+ );
+ });
+ }
+
+ async _getImportedStyleSheets(document, styleSheet) {
+ const importedStyleSheets = [];
+
+ for (const rule of await this._getCSSRules(styleSheet)) {
+ if (rule.type == CSSRule.IMPORT_RULE) {
+ // With the Gecko style system, the associated styleSheet may be null
+ // if it has already been seen because an import cycle for the same
+ // URL. With Stylo, the styleSheet will exist (which is correct per
+ // the latest CSSOM spec), so we also need to check ancestors for the
+ // same URL to avoid cycles.
+ if (
+ !rule.styleSheet ||
+ this._haveAncestorWithSameURL(rule.styleSheet) ||
+ !this._shouldListSheet(rule.styleSheet)
+ ) {
+ continue;
+ }
+
+ importedStyleSheets.push(rule.styleSheet);
+
+ // recurse imports in this stylesheet as well
+ const children = await this._getImportedStyleSheets(
+ document,
+ rule.styleSheet
+ );
+ importedStyleSheets.push(...children);
+ } else if (rule.type != CSSRule.CHARSET_RULE) {
+ // @import rules must precede all others except @charset
+ break;
+ }
+ }
+
+ return importedStyleSheets;
+ }
+
+ async _getMediaRules(resourceId, styleSheet) {
+ this._mqlList = [];
+
+ const mediaRules = Array.from(await this._getCSSRules(styleSheet)).filter(
+ rule => rule.type === CSSRule.MEDIA_RULE
+ );
+
+ return mediaRules.map((rule, index) => {
+ let matches = false;
+
+ try {
+ const window = styleSheet.ownerNode.ownerGlobal;
+ const mql = window.matchMedia(rule.media.mediaText);
+ matches = mql.matches;
+ mql.onchange = this._onMatchesChange.bind(this, resourceId, index);
+ this._mqlList.push(mql);
+ } catch (e) {
+ // Ignored
+ }
+
+ return {
+ mediaText: rule.media.mediaText,
+ conditionText: rule.conditionText,
+ matches,
+ line: InspectorUtils.getRuleLine(rule),
+ column: InspectorUtils.getRuleColumn(rule),
+ };
+ });
+ }
+
+ _onMatchesChange(resourceId, index, mql) {
+ this._notifyResourceUpdated(resourceId, "matches-change", {
+ nestedResourceUpdates: [
+ {
+ path: ["mediaRules", index, "matches"],
+ value: mql.matches,
+ },
+ ],
+ });
+ }
+
+ _getNodeHref(styleSheet) {
+ const { ownerNode } = styleSheet;
+ if (!ownerNode) {
+ return null;
+ }
+
+ if (ownerNode.nodeType == ownerNode.DOCUMENT_NODE) {
+ return ownerNode.location.href;
+ } else if (ownerNode.ownerDocument?.location) {
+ return ownerNode.ownerDocument.location.href;
+ }
+
+ return null;
+ }
+
+ _getSourcemapBaseURL(styleSheet) {
+ // When the style is imported, `styleSheet.ownerNode` is null,
+ // so retrieve the topmost parent style sheet which has an ownerNode
+ let parentStyleSheet = styleSheet;
+ while (parentStyleSheet.parentStyleSheet) {
+ parentStyleSheet = parentStyleSheet.parentStyleSheet;
+ }
+
+ // When the style is injected via nsIDOMWindowUtils.loadSheet, even
+ // the parent style sheet has no owner, so default back to target actor
+ // document
+ const ownerDocument = parentStyleSheet.ownerNode
+ ? parentStyleSheet.ownerNode.ownerDocument
+ : this._targetActor.window;
+
+ return getSourcemapBaseURL(
+ // Technically resolveSourceURL should be used here alongside
+ // "this.rawSheet.sourceURL", but the style inspector does not support
+ // /*# sourceURL=*/ in CSS, so we're omitting it here (bug 880831).
+ styleSheet.href || this._getNodeHref(styleSheet),
+ ownerDocument
+ );
+ }
+
+ _getStyleSheetIndex(styleSheet) {
+ const styleSheets = InspectorUtils.getAllStyleSheets(
+ this._targetActor.window.document,
+ true
+ );
+ return styleSheets.indexOf(styleSheet);
+ }
+
+ async _getStyleSheets({ document }) {
+ const documentOnly = !document.nodePrincipal.isSystemPrincipal;
+
+ const styleSheets = [];
+
+ for (const styleSheet of InspectorUtils.getAllStyleSheets(
+ document,
+ documentOnly
+ )) {
+ if (!this._shouldListSheet(styleSheet)) {
+ continue;
+ }
+
+ styleSheets.push(styleSheet);
+
+ // Get all sheets, including imported ones
+ const importedStyleSheets = await this._getImportedStyleSheets(
+ document,
+ styleSheet
+ );
+ styleSheets.push(...importedStyleSheets);
+ }
+
+ return styleSheets;
+ }
+
+ _haveAncestorWithSameURL(styleSheet) {
+ const href = styleSheet.href;
+ while (styleSheet.parentStyleSheet) {
+ if (styleSheet.parentStyleSheet.href == href) {
+ return true;
+ }
+ styleSheet = styleSheet.parentStyleSheet;
+ }
+ return false;
+ }
+
+ _notifyPropertyChanged(resourceId, property, value) {
+ this._notifyResourceUpdated(resourceId, "property-change", {
+ resourceUpdates: { [property]: value },
+ });
+ }
+
+ /**
+ * Event handler that is called when the state of applicable of style sheet is changed.
+ *
+ * For now, StyleSheetApplicableStateChanged event will be called at following timings.
+ * - Append <link> of stylesheet to document
+ * - Append <style> to document
+ * - Change disable attribute of stylesheet object
+ * - Change disable attribute of <link> to false
+ * When appending <link>, <style> or changing `disable` attribute to false, `applicable`
+ * is passed as true. The other hand, when changing `disable` to true, this will be
+ * false.
+ * NOTE: For now, StyleSheetApplicableStateChanged will not be called when removing the
+ * link and style element.
+ *
+ * @param {StyleSheetApplicableStateChanged}
+ * The triggering event.
+ */
+ async _onApplicableStateChanged({ applicable, stylesheet: styleSheet }) {
+ for (const existing of this._styleSheetMap.values()) {
+ if (existing.styleSheet === styleSheet) {
+ return;
+ }
+ }
+
+ if (
+ // Have interest in applicable stylesheet only.
+ applicable &&
+ // No ownerNode means that this stylesheet is *not* associated to a DOM Element.
+ styleSheet.ownerNode &&
+ this._shouldListSheet(styleSheet) &&
+ !this._haveAncestorWithSameURL(styleSheet)
+ ) {
+ await this._notifyResourcesAvailable([styleSheet]);
+ }
+ }
+
+ _shouldListSheet(styleSheet) {
+ // Special case about:PreferenceStyleSheet, as it is generated on the
+ // fly and the URI is not registered with the about: handler.
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=935803#c37
+ if (styleSheet.href?.toLowerCase() === "about:preferencestylesheet") {
+ return false;
+ }
+
+ return true;
+ }
+
+ async _toResource(
+ styleSheet,
+ { isCreatedByDevTools = false, fileName = null } = {}
+ ) {
+ const resourceId = `stylesheet:${this._resourceCount++}`;
+
+ const resource = {
+ resourceId,
+ resourceType: STYLESHEET,
+ disabled: styleSheet.disabled,
+ fileName,
+ href: styleSheet.href,
+ isNew: isCreatedByDevTools,
+ mediaRules: await this._getMediaRules(resourceId, styleSheet),
+ nodeHref: this._getNodeHref(styleSheet),
+ ruleCount: styleSheet.cssRules.length,
+ sourceMapBaseURL: this._getSourcemapBaseURL(styleSheet),
+ sourceMapURL: styleSheet.sourceMapURL,
+ styleSheetIndex: this._getStyleSheetIndex(styleSheet),
+ system: CssLogic.isAgentStylesheet(styleSheet),
+ title: styleSheet.title,
+ };
+
+ return resource;
+ }
+
+ async _notifyResourcesAvailable(styleSheets) {
+ const resources = await Promise.all(
+ styleSheets.map(async styleSheet => {
+ const creationData = this._stylesheetCreationData?.get(styleSheet);
+
+ const resource = await this._toResource(styleSheet, {
+ isCreatedByDevTools: creationData?.isCreatedByDevTools,
+ fileName: creationData?.fileName,
+ });
+
+ this._styleSheetMap.set(resource.resourceId, { styleSheet });
+ return resource;
+ })
+ );
+
+ await this._onAvailable(resources);
+
+ for (const styleSheet of styleSheets) {
+ const creationData = this._stylesheetCreationData?.get(styleSheet);
+ creationData?.resolve();
+ this._stylesheetCreationData?.delete(styleSheet);
+ }
+ }
+
+ _notifyResourceUpdated(
+ resourceId,
+ updateType,
+ { resourceUpdates, nestedResourceUpdates, event }
+ ) {
+ this._onUpdated([
+ {
+ resourceType: STYLESHEET,
+ resourceId,
+ updateType,
+ resourceUpdates,
+ nestedResourceUpdates,
+ event,
+ },
+ ]);
+ }
+
+ destroy() {
+ if (!this._targetActor.docShell) {
+ return;
+ }
+
+ this._targetActor.chromeEventHandler.removeEventListener(
+ "StyleSheetApplicableStateChanged",
+ this._onApplicableStateChanged,
+ true
+ );
+ }
+}
+
+module.exports = StyleSheetWatcher;
diff --git a/devtools/server/actors/resources/utils/content-process-storage.js b/devtools/server/actors/resources/utils/content-process-storage.js
new file mode 100644
index 0000000000..cf07fe3e48
--- /dev/null
+++ b/devtools/server/actors/resources/utils/content-process-storage.js
@@ -0,0 +1,218 @@
+/* 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";
+
+const { storageTypePool } = require("devtools/server/actors/storage");
+
+// ms of delay to throttle updates
+const BATCH_DELAY = 200;
+
+class ContentProcessStorage {
+ constructor(storageKey, storageType) {
+ this.storageKey = storageKey;
+ this.storageType = storageType;
+ }
+
+ async watch(targetActor, { onAvailable, onUpdated, onDestroyed }) {
+ const ActorConstructor = storageTypePool.get(this.storageKey);
+ this.actor = new ActorConstructor({
+ get conn() {
+ return targetActor.conn;
+ },
+ get windows() {
+ // about:blank pages that are included via an iframe, do not get their
+ // own process, and they will be present in targetActor.windows.
+ // We need to ignore them unless they are the top level page.
+ // Otherwise about:blank loads with the same principal as their parent document
+ // and would expose the same storage values as its parent.
+ const windows = targetActor.windows.filter(win => {
+ const isTopPage = win.parent === win;
+ return isTopPage || win.location.href !== "about:blank";
+ });
+
+ return windows;
+ },
+ get window() {
+ return targetActor.window;
+ },
+ get document() {
+ return this.window.document;
+ },
+ get originAttributes() {
+ return this.document.effectiveStoragePrincipal.originAttributes;
+ },
+
+ update(action, storeType, data) {
+ if (!this.boundUpdate) {
+ this.boundUpdate = {};
+ }
+
+ if (action === "cleared") {
+ const response = {};
+ response[this.storageKey] = data;
+
+ onDestroyed([
+ {
+ // needs this so the resource gets passed as an actor
+ // ...storages[storageKey],
+ ...storage,
+ clearedHostsOrPaths: data,
+ },
+ ]);
+ }
+
+ if (this.batchTimer) {
+ clearTimeout(this.batchTimer);
+ }
+
+ if (!this.boundUpdate[action]) {
+ this.boundUpdate[action] = {};
+ }
+ if (!this.boundUpdate[action][storeType]) {
+ this.boundUpdate[action][storeType] = {};
+ }
+ for (const host in data) {
+ if (!this.boundUpdate[action][storeType][host]) {
+ this.boundUpdate[action][storeType][host] = [];
+ }
+ for (const name of data[host]) {
+ if (!this.boundUpdate[action][storeType][host].includes(name)) {
+ this.boundUpdate[action][storeType][host].push(name);
+ }
+ }
+ }
+
+ if (action === "added") {
+ // If the same store name was previously deleted or changed, but now
+ // is added somehow, don't send the deleted or changed update
+ this._removeNamesFromUpdateList("deleted", storeType, data);
+ this._removeNamesFromUpdateList("changed", storeType, data);
+ } else if (
+ action === "changed" &&
+ this.boundUpdate?.added?.[storeType]
+ ) {
+ // If something got added and changed at the same time, then remove
+ // those items from changed instead.
+ this._removeNamesFromUpdateList(
+ "changed",
+ storeType,
+ this.boundUpdate.added[storeType]
+ );
+ } else if (action === "deleted") {
+ // If any item got deleted, or a host got deleted, there's no point
+ // in sending added or changed upate, so we remove them.
+ this._removeNamesFromUpdateList("added", storeType, data);
+ this._removeNamesFromUpdateList("changed", storeType, data);
+
+ for (const host in data) {
+ if (
+ data[host].length === 0 &&
+ this.boundUpdate?.added?.[storeType]?.[host]
+ ) {
+ delete this.boundUpdate.added[storeType][host];
+ }
+
+ if (
+ data[host].length === 0 &&
+ this.boundUpdate?.changed?.[storeType]?.[host]
+ ) {
+ delete this.boundUpdate.changed[storeType][host];
+ }
+ }
+ }
+
+ this.batchTimer = setTimeout(() => {
+ clearTimeout(this.batchTimer);
+ onUpdated([
+ {
+ // needs this so the resource gets passed as an actor
+ // ...storages[storageKey],
+ ...storage,
+ added: this.boundUpdate.added,
+ changed: this.boundUpdate.changed,
+ deleted: this.boundUpdate.deleted,
+ },
+ ]);
+ this.boundUpdate = {};
+ }, BATCH_DELAY);
+
+ return null;
+ },
+ /**
+ * This method removes data from the this.boundUpdate object in the same
+ * manner like this.update() adds data to it.
+ *
+ * @param {string} action
+ * The type of change. One of "added", "changed" or "deleted"
+ * @param {string} storeType
+ * The storage actor for which you want to remove the updates data.
+ * @param {object} data
+ * The update object. This object is of the following format:
+ * - {
+ * <host1>: [<store_names1>, <store_name2>...],
+ * <host2>: [<store_names34>...],
+ * }
+ * Where host1, host2 are the hosts which you want to remove and
+ * [<store_namesX] is an array of the names of the store objects.
+ **/
+ _removeNamesFromUpdateList(action, storeType, data) {
+ for (const host in data) {
+ if (this.boundUpdate?.[action]?.[storeType]?.[host]) {
+ for (const name in data[host]) {
+ const index = this.boundUpdate[action][storeType][host].indexOf(
+ name
+ );
+ if (index > -1) {
+ this.boundUpdate[action][storeType][host].splice(index, 1);
+ }
+ }
+ if (!this.boundUpdate[action][storeType][host].length) {
+ delete this.boundUpdate[action][storeType][host];
+ }
+ }
+ }
+ return null;
+ },
+
+ on() {
+ targetActor.on.apply(this, arguments);
+ },
+ off() {
+ targetActor.off.apply(this, arguments);
+ },
+ once() {
+ targetActor.once.apply(this, arguments);
+ },
+ });
+
+ // We have to manage the actor manually, because ResourceWatcher doesn't
+ // use the protocol.js specification.
+ // resource-available-form is typed as "json"
+ // So that we have to manually handle stuff that would normally be
+ // automagically done by procotol.js
+ // 1) Manage the actor in order to have an actorID on it
+ targetActor.manage(this.actor);
+ // 2) Convert to JSON "form"
+ const form = this.actor.form();
+
+ // NOTE: this is hoisted, so the `update` method above may use it.
+ const storage = form;
+
+ // All resources should have a resourceType, resourceId and resourceKey
+ // attributes, so available/updated/destroyed callbacks work properly.
+ storage.resourceType = this.storageType;
+ storage.resourceId = this.storageType;
+ storage.resourceKey = this.storageKey;
+
+ onAvailable([storage]);
+ }
+
+ destroy() {
+ this.actor?.destroy();
+ this.actor = null;
+ }
+}
+
+module.exports = ContentProcessStorage;
diff --git a/devtools/server/actors/resources/utils/moz.build b/devtools/server/actors/resources/utils/moz.build
new file mode 100644
index 0000000000..b57360d218
--- /dev/null
+++ b/devtools/server/actors/resources/utils/moz.build
@@ -0,0 +1,13 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "content-process-storage.js",
+ "nsi-console-listener-watcher.js",
+)
+
+with Files("nsi-console-listener-watcher.js"):
+ BUG_COMPONENT = ("DevTools", "Console")
diff --git a/devtools/server/actors/resources/utils/nsi-console-listener-watcher.js b/devtools/server/actors/resources/utils/nsi-console-listener-watcher.js
new file mode 100644
index 0000000000..352d622c30
--- /dev/null
+++ b/devtools/server/actors/resources/utils/nsi-console-listener-watcher.js
@@ -0,0 +1,187 @@
+/* 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";
+
+const { Ci, Cu } = require("chrome");
+const Services = require("Services");
+const ChromeUtils = require("ChromeUtils");
+
+const { createStringGrip } = require("devtools/server/actors/object/utils");
+
+const {
+ getActorIdForInternalSourceId,
+} = require("devtools/server/actors/utils/dbg-source");
+
+class nsIConsoleListenerWatcher {
+ /**
+ * Start watching for all messages related to a given Target Actor.
+ * This will notify about existing messages, as well as those created in the future.
+ *
+ * @param TargetActor targetActor
+ * The target actor from which we should observe messages
+ * @param Object options
+ * Dictionary object with following attributes:
+ * - onAvailable: mandatory function
+ * This will be called for each resource.
+ */
+ async watch(targetActor, { onAvailable }) {
+ if (!this.shouldHandleTarget(targetActor)) {
+ return;
+ }
+
+ // The following code expects the ThreadActor to be instantiated (in prepareStackForRemote)
+ // The Thread Actor is instantiated via Target.attach, but we should probably review
+ // this and only instantiate the actor instead of attaching the target.
+ if (!targetActor.threadActor) {
+ targetActor.attach();
+ }
+
+ // Create the consoleListener.
+ const listener = {
+ QueryInterface: ChromeUtils.generateQI(["nsIConsoleListener"]),
+ observe: message => {
+ if (!this.shouldHandleMessage(targetActor, message)) {
+ return;
+ }
+
+ onAvailable([this.buildResource(targetActor, message)]);
+ },
+ };
+
+ // Retrieve the cached messages just before registering the listener, so we don't get
+ // duplicated messages.
+ const cachedMessages = Services.console.getMessageArray() || [];
+ Services.console.registerListener(listener);
+ this.listener = listener;
+
+ // Remove unwanted cache messages and send an array of resources.
+ const messages = [];
+ for (const message of cachedMessages) {
+ if (!this.shouldHandleMessage(targetActor, message)) {
+ continue;
+ }
+
+ messages.push(this.buildResource(targetActor, message));
+ }
+ onAvailable(messages);
+ }
+
+ /**
+ * Return false if the watcher shouldn't be created.
+ *
+ * @param {TargetActor} targetActor
+ * @return {Boolean}
+ */
+ shouldHandleTarget(targetActor) {
+ return true;
+ }
+
+ /**
+ * Return true if you want the passed message to be handled by the watcher. This should
+ * be implemented on the child class.
+ *
+ * @param {TargetActor} targetActor
+ * @param {nsIScriptError|nsIConsoleMessage} message
+ * @return {Boolean}
+ */
+ shouldHandleMessage(targetActor, message) {
+ throw new Error(
+ "'shouldHandleMessage' should be implemented in the class that extends nsIConsoleListenerWatcher"
+ );
+ }
+
+ /**
+ * Prepare the resource to be sent to the client. This should be implemented on the
+ * child class.
+ *
+ * @param targetActor
+ * @param nsIScriptError|nsIConsoleMessage message
+ * @return object
+ * The object you can send to the remote client.
+ */
+ buildResource(targetActor, message) {
+ throw new Error(
+ "'buildResource' should be implemented in the class that extends nsIConsoleListenerWatcher"
+ );
+ }
+
+ /**
+ * Prepare a SavedFrame stack to be sent to the client.
+ *
+ * @param {TargetActor} targetActor
+ * @param {SavedFrame} errorStack
+ * Stack for an error we need to send to the client.
+ * @return object
+ * The object you can send to the remote client.
+ */
+ prepareStackForRemote(targetActor, errorStack) {
+ // Convert stack objects to the JSON attributes expected by client code
+ // Bug 1348885: If the global from which this error came from has been
+ // nuked, stack is going to be a dead wrapper.
+ if (!errorStack || (Cu && Cu.isDeadWrapper(errorStack))) {
+ return null;
+ }
+ const stack = [];
+ let s = errorStack;
+ while (s) {
+ stack.push({
+ filename: s.source,
+ sourceId: getActorIdForInternalSourceId(targetActor, s.sourceId),
+ lineNumber: s.line,
+ columnNumber: s.column,
+ functionName: s.functionDisplayName,
+ asyncCause: s.asyncCause ? s.asyncCause : undefined,
+ });
+ s = s.parent || s.asyncParent;
+ }
+ return stack;
+ }
+
+ /**
+ * Prepare error notes to be sent to the client.
+ *
+ * @param {TargetActor} targetActor
+ * @param {nsIArray<nsIScriptErrorNote>} errorNotes
+ * @return object
+ * The object you can send to the remote client.
+ */
+ prepareNotesForRemote(targetActor, errorNotes) {
+ if (!errorNotes?.length) {
+ return null;
+ }
+
+ const notes = [];
+ for (let i = 0, len = errorNotes.length; i < len; i++) {
+ const note = errorNotes.queryElementAt(i, Ci.nsIScriptErrorNote);
+ notes.push({
+ messageBody: createStringGrip(targetActor, note.errorMessage),
+ frame: {
+ source: note.sourceName,
+ sourceId: getActorIdForInternalSourceId(targetActor, note.sourceId),
+ line: note.lineNumber,
+ column: note.columnNumber,
+ },
+ });
+ }
+ return notes;
+ }
+
+ isProcessTarget(targetActor) {
+ const { typeName } = targetActor;
+ return (
+ typeName === "parentProcessTarget" || typeName === "contentProcessTarget"
+ );
+ }
+
+ /**
+ * Stop watching for messages.
+ */
+ destroy() {
+ if (this.listener) {
+ Services.console.unregisterListener(this.listener);
+ }
+ }
+}
+module.exports = nsIConsoleListenerWatcher;
diff --git a/devtools/server/actors/root.js b/devtools/server/actors/root.js
new file mode 100644
index 0000000000..002ba16e9f
--- /dev/null
+++ b/devtools/server/actors/root.js
@@ -0,0 +1,608 @@
+/* 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";
+
+// protocol.js uses objects as exceptions in order to define
+// error packets.
+/* eslint-disable no-throw-literal */
+
+const { Cu } = require("chrome");
+const Services = require("Services");
+const { Pool } = require("devtools/shared/protocol");
+const {
+ LazyPool,
+ createExtraActors,
+} = require("devtools/shared/protocol/lazy-pool");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const protocol = require("devtools/shared/protocol");
+const { rootSpec } = require("devtools/shared/specs/root");
+
+loader.lazyRequireGetter(
+ this,
+ "ChromeWindowTargetActor",
+ "devtools/server/actors/targets/chrome-window",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "ProcessDescriptorActor",
+ "devtools/server/actors/descriptors/process",
+ true
+);
+
+/* Root actor for the remote debugging protocol. */
+
+/**
+ * Create a remote debugging protocol root actor.
+ *
+ * @param conn
+ * The DevToolsServerConnection whose root actor we are constructing.
+ *
+ * @param parameters
+ * The properties of |parameters| provide backing objects for the root
+ * actor's requests; if a given property is omitted from |parameters|, the
+ * root actor won't implement the corresponding requests or notifications.
+ * Supported properties:
+ *
+ * - tabList: a live list (see below) of target actors for tabs. If present,
+ * the new root actor supports the 'listTabs' request, providing the live
+ * list's elements as its target actors, and sending 'tabListChanged'
+ * notifications when the live list's contents change. One actor in
+ * this list must have a true '.selected' property.
+ *
+ * - addonList: a live list (see below) of addon actors. If present, the
+ * new root actor supports the 'listAddons' request, providing the live
+ * list's elements as its addon actors, and sending 'addonListchanged'
+ * notifications when the live list's contents change.
+ *
+ * - globalActorFactories: an object |A| describing further actors to
+ * attach to the 'listTabs' reply. This is the type accumulated by
+ * ActorRegistry.addGlobalActor. For each own property |P| of |A|,
+ * the root actor adds a property named |P| to the 'listTabs'
+ * reply whose value is the name of an actor constructed by
+ * |A[P]|.
+ *
+ * - onShutdown: a function to call when the root actor is destroyed.
+ *
+ * Instance properties:
+ *
+ * - applicationType: the string the root actor will include as the
+ * "applicationType" property in the greeting packet. By default, this
+ * is "browser".
+ *
+ * Live lists:
+ *
+ * A "live list", as used for the |tabList|, is an object that presents a
+ * list of actors, and also notifies its clients of changes to the list. A
+ * live list's interface is two properties:
+ *
+ * - getList: a method that returns a promise to the contents of the list.
+ *
+ * - onListChanged: a handler called, with no arguments, when the set of
+ * values the iterator would produce has changed since the last
+ * time 'iterator' was called. This may only be set to null or a
+ * callable value (one for which the typeof operator returns
+ * 'function'). (Note that the live list will not call the
+ * onListChanged handler until the list has been iterated over
+ * once; if nobody's seen the list in the first place, nobody
+ * should care if its contents have changed!)
+ *
+ * When the list changes, the list implementation should ensure that any
+ * actors yielded in previous iterations whose referents (tabs) still exist
+ * get yielded again in subsequent iterations. If the underlying referent
+ * is the same, the same actor should be presented for it.
+ *
+ * The root actor registers an 'onListChanged' handler on the appropriate
+ * list when it may need to send the client 'tabListChanged' notifications,
+ * and is careful to remove the handler whenever it does not need to send
+ * such notifications (including when it is destroyed). This means that
+ * live list implementations can use the state of the handler property (set
+ * or null) to install and remove observers and event listeners.
+ *
+ * Note that, as the only way for the root actor to see the members of the
+ * live list is to begin an iteration over the list, the live list need not
+ * actually produce any actors until they are reached in the course of
+ * iteration: alliterative lazy live lists.
+ */
+exports.RootActor = protocol.ActorClassWithSpec(rootSpec, {
+ initialize: function(conn, parameters) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+
+ this._parameters = parameters;
+ this._onTabListChanged = this.onTabListChanged.bind(this);
+ this._onAddonListChanged = this.onAddonListChanged.bind(this);
+ this._onWorkerListChanged = this.onWorkerListChanged.bind(this);
+ this._onServiceWorkerRegistrationListChanged = this.onServiceWorkerRegistrationListChanged.bind(
+ this
+ );
+ this._onProcessListChanged = this.onProcessListChanged.bind(this);
+ this._extraActors = {};
+
+ this._globalActorPool = new LazyPool(this.conn);
+
+ this.applicationType = "browser";
+
+ this.traits = {
+ networkMonitor: true,
+ // @backward-compat { version 84 } Expose the pref value to the client.
+ // Services.prefs is undefined in xpcshell tests.
+ workerConsoleApiMessagesDispatchedToMainThread: Services.prefs
+ ? Services.prefs.getBoolPref(
+ "dom.worker.console.dispatch_events_to_main_thread"
+ )
+ : true,
+ // @backward-compat { version 86 } ThreadActor.attach no longer pause the thread,
+ // so that we no longer have to resume.
+ noPauseOnThreadActorAttach: true,
+ };
+ },
+
+ /**
+ * Return a 'hello' packet as specified by the Remote Debugging Protocol.
+ */
+ sayHello: function() {
+ return {
+ from: this.actorID,
+ applicationType: this.applicationType,
+ /* This is not in the spec, but it's used by tests. */
+ testConnectionPrefix: this.conn.prefix,
+ traits: this.traits,
+ };
+ },
+
+ forwardingCancelled: function(prefix) {
+ return {
+ from: this.actorID,
+ type: "forwardingCancelled",
+ prefix,
+ };
+ },
+
+ /**
+ * Destroys the actor from the browser window.
+ */
+ destroy: function() {
+ protocol.Actor.prototype.destroy.call(this);
+
+ /* Tell the live lists we aren't watching any more. */
+ if (this._parameters.tabList) {
+ this._parameters.tabList.destroy();
+ }
+ if (this._parameters.addonList) {
+ this._parameters.addonList.onListChanged = null;
+ }
+ if (this._parameters.workerList) {
+ this._parameters.workerList.destroy();
+ }
+ if (this._parameters.serviceWorkerRegistrationList) {
+ this._parameters.serviceWorkerRegistrationList.onListChanged = null;
+ }
+ if (this._parameters.processList) {
+ this._parameters.processList.onListChanged = null;
+ }
+ if (typeof this._parameters.onShutdown === "function") {
+ this._parameters.onShutdown();
+ }
+ // Cleanup Actors on destroy
+ if (this._tabDescriptorActorPool) {
+ this._tabDescriptorActorPool.destroy();
+ }
+ if (this._processDescriptorActorPool) {
+ this._processDescriptorActorPool.destroy();
+ }
+ if (this._globalActorPool) {
+ this._globalActorPool.destroy();
+ }
+ if (this._chromeWindowActorPool) {
+ this._chromeWindowActorPool.destroy();
+ }
+ if (this._addonTargetActorPool) {
+ this._addonTargetActorPool.destroy();
+ }
+ if (this._workerDescriptorActorPool) {
+ this._workerDescriptorActorPool.destroy();
+ }
+ if (this._frameDescriptorActorPool) {
+ this._frameDescriptorActorPool.destroy();
+ }
+
+ if (this._serviceWorkerRegistrationActorPool) {
+ this._serviceWorkerRegistrationActorPool.destroy();
+ }
+ this._extraActors = null;
+ this.conn = null;
+ this._tabDescriptorActorPool = null;
+ this._globalActorPool = null;
+ this._chromeWindowActorPool = null;
+ this._parameters = null;
+ },
+
+ /**
+ * Gets the "root" form, which lists all the global actors that affect the entire
+ * browser.
+ */
+ getRoot: function() {
+ // Create global actors
+ if (!this._globalActorPool) {
+ this._globalActorPool = new LazyPool(this.conn);
+ }
+ const actors = createExtraActors(
+ this._parameters.globalActorFactories,
+ this._globalActorPool,
+ this
+ );
+
+ return actors;
+ },
+
+ /* The 'listTabs' request and the 'tabListChanged' notification. */
+
+ /**
+ * Handles the listTabs request. The actors will survive until at least
+ * the next listTabs request.
+ */
+ listTabs: async function() {
+ const tabList = this._parameters.tabList;
+ if (!tabList) {
+ throw {
+ error: "noTabs",
+ message: "This root actor has no browser tabs.",
+ };
+ }
+
+ // Now that a client has requested the list of tabs, we reattach the onListChanged
+ // listener in order to be notified if the list of tabs changes again in the future.
+ tabList.onListChanged = this._onTabListChanged;
+
+ // Walk the tab list, accumulating the array of target actors for the reply, and
+ // moving all the actors to a new Pool. We'll replace the old tab target actor
+ // pool with the one we build here, thus retiring any actors that didn't get listed
+ // again, and preparing any new actors to receive packets.
+ const newActorPool = new Pool(this.conn, "listTabs-tab-descriptors");
+
+ const tabDescriptorActors = await tabList.getList();
+ for (const tabDescriptorActor of tabDescriptorActors) {
+ newActorPool.manage(tabDescriptorActor);
+ }
+
+ // Drop the old actorID -> actor map. Actors that still mattered were added to the
+ // new map; others will go away.
+ if (this._tabDescriptorActorPool) {
+ this._tabDescriptorActorPool.destroy();
+ }
+ this._tabDescriptorActorPool = newActorPool;
+
+ return tabDescriptorActors;
+ },
+
+ getTab: async function({ outerWindowID, tabId }) {
+ const tabList = this._parameters.tabList;
+ if (!tabList) {
+ throw {
+ error: "noTabs",
+ message: "This root actor has no browser tabs.",
+ };
+ }
+ if (!this._tabDescriptorActorPool) {
+ this._tabDescriptorActorPool = new Pool(
+ this.conn,
+ "getTab-tab-descriptors"
+ );
+ }
+
+ let descriptorActor;
+ try {
+ descriptorActor = await tabList.getTab({ outerWindowID, tabId });
+ } catch (error) {
+ if (error.error) {
+ // Pipe expected errors as-is to the client
+ throw error;
+ }
+ throw {
+ error: "noTab",
+ message: "Unexpected error while calling getTab(): " + error,
+ };
+ }
+
+ descriptorActor.parentID = this.actorID;
+ this._tabDescriptorActorPool.manage(descriptorActor);
+
+ return descriptorActor;
+ },
+
+ getWindow: function({ outerWindowID }) {
+ if (!DevToolsServer.allowChromeProcess) {
+ throw {
+ error: "forbidden",
+ message: "You are not allowed to debug windows.",
+ };
+ }
+ const window = Services.wm.getOuterWindowWithId(outerWindowID);
+ if (!window) {
+ throw {
+ error: "notFound",
+ message: `No window found with outerWindowID ${outerWindowID}`,
+ };
+ }
+
+ if (!this._chromeWindowActorPool) {
+ this._chromeWindowActorPool = new Pool(this.conn, "chrome-window");
+ }
+
+ const actor = new ChromeWindowTargetActor(this.conn, window);
+ actor.parentID = this.actorID;
+ this._chromeWindowActorPool.manage(actor);
+
+ return actor;
+ },
+
+ onTabListChanged: function() {
+ this.conn.send({ from: this.actorID, type: "tabListChanged" });
+ /* It's a one-shot notification; no need to watch any more. */
+ this._parameters.tabList.onListChanged = null;
+ },
+
+ /**
+ * This function can receive the following option from devtools client.
+ *
+ * @param {Object} option
+ * - iconDataURL: {boolean}
+ * When true, make data url from the icon of addon, then make possible to
+ * access by iconDataURL in the actor. The iconDataURL is useful when
+ * retrieving addons from a remote device, because the raw iconURL might not
+ * be accessible on the client.
+ */
+ listAddons: async function(option) {
+ const addonList = this._parameters.addonList;
+ if (!addonList) {
+ throw {
+ error: "noAddons",
+ message: "This root actor has no browser addons.",
+ };
+ }
+
+ // Reattach the onListChanged listener now that a client requested the list.
+ addonList.onListChanged = this._onAddonListChanged;
+
+ const addonTargetActors = await addonList.getList();
+ const addonTargetActorPool = new Pool(this.conn, "addon-descriptors");
+ for (const addonTargetActor of addonTargetActors) {
+ if (option.iconDataURL) {
+ await addonTargetActor.loadIconDataURL();
+ }
+
+ addonTargetActorPool.manage(addonTargetActor);
+ }
+
+ if (this._addonTargetActorPool) {
+ this._addonTargetActorPool.destroy();
+ }
+ this._addonTargetActorPool = addonTargetActorPool;
+
+ return addonTargetActors;
+ },
+
+ onAddonListChanged: function() {
+ this.conn.send({ from: this.actorID, type: "addonListChanged" });
+ this._parameters.addonList.onListChanged = null;
+ },
+
+ listWorkers: function() {
+ const workerList = this._parameters.workerList;
+ if (!workerList) {
+ throw {
+ error: "noWorkers",
+ message: "This root actor has no workers.",
+ };
+ }
+
+ // Reattach the onListChanged listener now that a client requested the list.
+ workerList.onListChanged = this._onWorkerListChanged;
+
+ return workerList.getList().then(actors => {
+ const pool = new Pool(this.conn, "worker-targets");
+ for (const actor of actors) {
+ pool.manage(actor);
+ }
+
+ // Do not destroy the pool before transfering ownership to the newly created
+ // pool, so that we do not accidently destroy actors that are still in use.
+ if (this._workerDescriptorActorPool) {
+ this._workerDescriptorActorPool.destroy();
+ }
+
+ this._workerDescriptorActorPool = pool;
+
+ return {
+ workers: actors,
+ };
+ });
+ },
+
+ onWorkerListChanged: function() {
+ this.conn.send({ from: this.actorID, type: "workerListChanged" });
+ this._parameters.workerList.onListChanged = null;
+ },
+
+ listServiceWorkerRegistrations: function() {
+ const registrationList = this._parameters.serviceWorkerRegistrationList;
+ if (!registrationList) {
+ throw {
+ error: "noServiceWorkerRegistrations",
+ message: "This root actor has no service worker registrations.",
+ };
+ }
+
+ // Reattach the onListChanged listener now that a client requested the list.
+ registrationList.onListChanged = this._onServiceWorkerRegistrationListChanged;
+
+ return registrationList.getList().then(actors => {
+ const pool = new Pool(this.conn, "service-workers-registrations");
+ for (const actor of actors) {
+ pool.manage(actor);
+ }
+
+ if (this._serviceWorkerRegistrationActorPool) {
+ this._serviceWorkerRegistrationActorPool.destroy();
+ }
+ this._serviceWorkerRegistrationActorPool = pool;
+
+ return {
+ registrations: actors,
+ };
+ });
+ },
+
+ onServiceWorkerRegistrationListChanged: function() {
+ this.conn.send({
+ from: this.actorID,
+ type: "serviceWorkerRegistrationListChanged",
+ });
+ this._parameters.serviceWorkerRegistrationList.onListChanged = null;
+ },
+
+ listProcesses: function() {
+ const { processList } = this._parameters;
+ if (!processList) {
+ throw {
+ error: "noProcesses",
+ message: "This root actor has no processes.",
+ };
+ }
+ processList.onListChanged = this._onProcessListChanged;
+ const processes = processList.getList();
+ const pool = new Pool(this.conn, "process-descriptors");
+ for (const metadata of processes) {
+ let processDescriptor = this._getKnownDescriptor(
+ metadata.id,
+ this._processDescriptorActorPool
+ );
+ if (!processDescriptor) {
+ processDescriptor = new ProcessDescriptorActor(this.conn, metadata);
+ }
+ pool.manage(processDescriptor);
+ }
+ // Do not destroy the pool before transfering ownership to the newly created
+ // pool, so that we do not accidently destroy actors that are still in use.
+ if (this._processDescriptorActorPool) {
+ this._processDescriptorActorPool.destroy();
+ }
+ this._processDescriptorActorPool = pool;
+ return [...this._processDescriptorActorPool.poolChildren()];
+ },
+
+ onProcessListChanged: function() {
+ this.conn.send({ from: this.actorID, type: "processListChanged" });
+ this._parameters.processList.onListChanged = null;
+ },
+
+ async getProcess(id) {
+ if (!DevToolsServer.allowChromeProcess) {
+ throw {
+ error: "forbidden",
+ message: "You are not allowed to debug chrome.",
+ };
+ }
+ if (typeof id != "number") {
+ throw {
+ error: "wrongParameter",
+ message: "getProcess requires a valid `id` attribute.",
+ };
+ }
+ this._processDescriptorActorPool =
+ this._processDescriptorActorPool ||
+ new Pool(this.conn, "process-descriptors");
+
+ let processDescriptor = this._getKnownDescriptor(
+ id,
+ this._processDescriptorActorPool
+ );
+ if (!processDescriptor) {
+ // The parent process has id == 0, based on ProcessActorList::getList implementation
+ const options = { id, parent: id === 0 };
+ processDescriptor = new ProcessDescriptorActor(this.conn, options);
+ this._processDescriptorActorPool.manage(processDescriptor);
+ }
+ return processDescriptor;
+ },
+
+ _getKnownDescriptor(id, pool) {
+ // if there is no pool, then we do not have any descriptors
+ if (!pool) {
+ return null;
+ }
+ for (const descriptor of pool.poolChildren()) {
+ if (descriptor.id === id) {
+ return descriptor;
+ }
+ }
+ return null;
+ },
+
+ _getParentProcessDescriptor() {
+ if (!this._processDescriptorActorPool) {
+ this._processDescriptorActorPool = new Pool(
+ this.conn,
+ "process-descriptors"
+ );
+ const options = { id: 0, parent: true };
+ const descriptor = new ProcessDescriptorActor(this.conn, options);
+ this._processDescriptorActorPool.manage(descriptor);
+ return descriptor;
+ }
+ for (const descriptor of this._processDescriptorActorPool.poolChildren()) {
+ if (descriptor.isParent) {
+ return descriptor;
+ }
+ }
+ return null;
+ },
+
+ _isParentBrowsingContext(id) {
+ // TODO: We may stop making the parent process codepath so special
+ const window = Services.wm.getMostRecentWindow(
+ DevToolsServer.chromeWindowType
+ );
+ return id == window.docShell.browsingContext.id;
+ },
+
+ /**
+ * Remove the extra actor (added by ActorRegistry.addGlobalActor or
+ * ActorRegistry.addTargetScopedActor) name |name|.
+ */
+ removeActorByName: function(name) {
+ if (name in this._extraActors) {
+ const actor = this._extraActors[name];
+ if (this._globalActorPool.has(actor.actorID)) {
+ actor.destroy();
+ }
+ if (this._tabDescriptorActorPool) {
+ // Iterate over BrowsingContextTargetActor instances to also remove target-scoped
+ // actors created during listTabs for each document.
+ for (const tab in this._tabDescriptorActorPool.poolChildren()) {
+ tab.removeActorByName(name);
+ }
+ }
+ delete this._extraActors[name];
+ }
+ },
+});
+
+/**
+ * This `echo` request can't be easily specified via protocol.js types
+ * as it is a JSON value in the packet itself. Protocol.js only allows
+ * arbitrary json object in one property of the packet.
+ * In order to bypass protocol.js, declare the request method directly
+ * on the prototype/requestTypes, which is populated by ActorClassWithSpec.
+ *
+ * Note that this request is only used by tests.
+ */
+exports.RootActor.prototype.requestTypes.echo = function(request) {
+ /*
+ * Request packets are frozen. Copy request, so that
+ * DevToolsServerConnection.onPacket can attach a 'from' property.
+ */
+ return Cu.cloneInto(request, {});
+};
diff --git a/devtools/server/actors/screenshot.js b/devtools/server/actors/screenshot.js
new file mode 100644
index 0000000000..3bee860a78
--- /dev/null
+++ b/devtools/server/actors/screenshot.js
@@ -0,0 +1,44 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const {
+ captureScreenshot,
+} = require("devtools/server/actors/utils/capture-screenshot");
+const { screenshotSpec } = require("devtools/shared/specs/screenshot");
+
+exports.ScreenshotActor = protocol.ActorClassWithSpec(screenshotSpec, {
+ initialize: function(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.targetActor = targetActor;
+ this.document = targetActor.window.document;
+ this._onNavigate = this._onNavigate.bind(this);
+
+ this.targetActor.on("navigate", this._onNavigate);
+ },
+
+ destroy() {
+ this.targetActor.off("navigate", this._onNavigate);
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ _onNavigate() {
+ this.document = this.targetActor.window.document;
+ },
+
+ capture: function(args) {
+ if (args.nodeActorID) {
+ const nodeActor = this.conn.getActor(args.nodeActorID);
+ if (!nodeActor) {
+ throw new Error(
+ `Screenshot actor failed to find Node actor for '${args.nodeActorID}'`
+ );
+ }
+ args.rawNode = nodeActor.rawNode;
+ }
+ return captureScreenshot(args, this.document);
+ },
+});
diff --git a/devtools/server/actors/source.js b/devtools/server/actors/source.js
new file mode 100644
index 0000000000..601265cd05
--- /dev/null
+++ b/devtools/server/actors/source.js
@@ -0,0 +1,751 @@
+/* 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";
+
+const { Cu } = require("chrome");
+const {
+ setBreakpointAtEntryPoints,
+} = require("devtools/server/actors/breakpoint");
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const { assert } = DevToolsUtils;
+const { sourceSpec } = require("devtools/shared/specs/source");
+const {
+ resolveSourceURL,
+ getSourcemapBaseURL,
+} = require("devtools/server/actors/utils/source-map-utils");
+const {
+ getDebuggerSourceURL,
+} = require("devtools/server/actors/utils/source-url");
+
+loader.lazyRequireGetter(
+ this,
+ "ArrayBufferActor",
+ "devtools/server/actors/array-buffer",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "LongStringActor",
+ "devtools/server/actors/string",
+ true
+);
+
+loader.lazyRequireGetter(this, "Services");
+loader.lazyGetter(
+ this,
+ "WebExtensionPolicy",
+ () => Cu.getGlobalForObject(Cu).WebExtensionPolicy
+);
+
+const windowsDrive = /^([a-zA-Z]:)/;
+
+function getSourceURL(source, window) {
+ // Some eval sources have URLs, but we want to explcitly ignore those because
+ // they are generally useless strings like "eval" or "debugger eval code".
+ const resourceURL =
+ (getDebuggerSourceURL(source) || "").split(" -> ").pop() || null;
+
+ // A "//# sourceURL=" pragma should basically be treated as a source file's
+ // full URL, so that is what we want to use as the base if it is present.
+ // If this is not an absolute URL, this will mean the maps in the file
+ // will not have a valid base URL, but that is up to tooling that
+ let result = resolveSourceURL(source.displayURL, window);
+ if (!result) {
+ result = resolveSourceURL(resourceURL, window) || resourceURL;
+
+ // In XPCShell tests, the source URL isn't actually a URL, it's a file path.
+ // That causes issues because "C:/folder/file.js" is parsed as a URL with
+ // "c:" as the URL scheme, which causes the drive letter to be unexpectedly
+ // lower-cased when the parsed URL is re-serialized. To avoid that, we
+ // detect that case and re-uppercase it again. This is a bit gross and
+ // ideally it seems like XPCShell tests should use file:// URLs for files,
+ // but alas they do not.
+ if (
+ resourceURL &&
+ resourceURL.match(windowsDrive) &&
+ result.slice(0, 2) == resourceURL.slice(0, 2).toLowerCase()
+ ) {
+ result = resourceURL.slice(0, 2) + result.slice(2);
+ }
+ }
+
+ return result;
+}
+
+/**
+ * A SourceActor provides information about the source of a script. Source
+ * actors are 1:1 with Debugger.Source objects.
+ *
+ * @param Debugger.Source source
+ * The source object we are representing.
+ * @param ThreadActor thread
+ * The current thread actor.
+ */
+const SourceActor = ActorClassWithSpec(sourceSpec, {
+ initialize: function({ source, thread }) {
+ Actor.prototype.initialize.call(this, thread.conn);
+
+ this._threadActor = thread;
+ this._url = undefined;
+ this._source = source;
+ this.__isInlineSource = undefined;
+ this._startLineColumnDisplacement = null;
+ },
+
+ get _isInlineSource() {
+ const source = this._source;
+ if (this.__isInlineSource === undefined) {
+ // If the source has a usable displayURL, the source is treated as not
+ // inlined because it has its own URL.
+ this.__isInlineSource =
+ source.introductionType === "inlineScript" &&
+ !resolveSourceURL(source.displayURL, this.threadActor._parent.window);
+ }
+ return this.__isInlineSource;
+ },
+
+ get threadActor() {
+ return this._threadActor;
+ },
+ get sourcesManager() {
+ return this._threadActor.sourcesManager;
+ },
+ get dbg() {
+ return this.threadActor.dbg;
+ },
+ get breakpointActorMap() {
+ return this.threadActor.breakpointActorMap;
+ },
+ get url() {
+ if (this._url === undefined) {
+ this._url = getSourceURL(this._source, this.threadActor._parent.window);
+ }
+ return this._url;
+ },
+
+ get extensionName() {
+ if (this._extensionName === undefined) {
+ this._extensionName = null;
+
+ // Cu is not available for workers and so we are not able to get a
+ // WebExtensionPolicy object
+ if (!isWorker && this.url) {
+ try {
+ const extURI = Services.io.newURI(this.url);
+ if (extURI) {
+ const policy = WebExtensionPolicy.getByURI(extURI);
+ if (policy) {
+ this._extensionName = policy.name;
+ }
+ }
+ } catch (e) {
+ // Ignore
+ }
+ }
+ }
+
+ return this._extensionName;
+ },
+
+ get internalSourceId() {
+ return this._source.id;
+ },
+
+ form: function() {
+ const source = this._source;
+
+ let introductionType = source.introductionType;
+ if (
+ introductionType === "srcScript" ||
+ introductionType === "inlineScript" ||
+ introductionType === "injectedScript"
+ ) {
+ // These three used to be one single type, so here we combine them all
+ // so that clients don't see any change in behavior.
+ introductionType = "scriptElement";
+ }
+
+ return {
+ actor: this.actorID,
+ extensionName: this.extensionName,
+ url: this.url,
+ isBlackBoxed: this.sourcesManager.isBlackBoxed(this.url),
+ sourceMapBaseURL: getSourcemapBaseURL(
+ this.url,
+ this.threadActor._parent.window
+ ),
+ sourceMapURL: source.sourceMapURL,
+ introductionType,
+ };
+ },
+
+ destroy: function() {
+ const parent = this.getParent();
+ if (parent && parent.sourceActors) {
+ delete parent.sourceActors[this.actorID];
+ }
+ Actor.prototype.destroy.call(this);
+ },
+
+ get _isWasm() {
+ return this._source.introductionType === "wasm";
+ },
+
+ _getSourceText: async function() {
+ if (this._isWasm) {
+ const wasm = this._source.binary;
+ const buffer = wasm.buffer;
+ assert(
+ wasm.byteOffset === 0 && wasm.byteLength === buffer.byteLength,
+ "Typed array from wasm source binary must cover entire buffer"
+ );
+ return {
+ content: buffer,
+ contentType: "text/wasm",
+ };
+ }
+
+ // Use `source.text` if it exists, is not the "no source" string, and
+ // the source isn't one that is inlined into some larger file.
+ // It will be "no source" if the Debugger API wasn't able to load
+ // the source because sources were discarded
+ // (javascript.options.discardSystemSource == true).
+ if (this._source.text !== "[no source]" && !this._isInlineSource) {
+ return {
+ content: this.actualText(),
+ contentType: "text/javascript",
+ };
+ }
+
+ return this.sourcesManager.urlContents(
+ this.url,
+ /* partial */ false,
+ /* canUseCache */ this._isInlineSource
+ );
+ },
+
+ // Get the actual text of this source, padded so that line numbers will match
+ // up with the source itself.
+ actualText() {
+ // If the source doesn't start at line 1, line numbers in the client will
+ // not match up with those in the source. Pad the text with blank lines to
+ // fix this. This can show up for sources associated with inline scripts
+ // in HTML created via document.write() calls: the script's source line
+ // number is relative to the start of the written HTML, but we show the
+ // source's content by itself.
+ const padding = this._source.startLine
+ ? "\n".repeat(this._source.startLine - 1)
+ : "";
+ return padding + this._source.text;
+ },
+
+ // Return whether the specified fetched contents includes the actual text of
+ // this source in the expected position.
+ contentMatches(fileContents) {
+ const lineBreak = /\r\n?|\n|\u2028|\u2029/;
+ const contentLines = fileContents.content.split(lineBreak);
+ const sourceLines = this._source.text.split(lineBreak);
+ let line = this._source.startLine - 1;
+ for (const sourceLine of sourceLines) {
+ const contentLine = contentLines[line++] || "";
+ if (!contentLine.includes(sourceLine)) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ getBreakableLines: async function() {
+ const positions = await this.getBreakpointPositions();
+ const lines = new Set();
+ for (const position of positions) {
+ if (!lines.has(position.line)) {
+ lines.add(position.line);
+ }
+ }
+
+ return Array.from(lines);
+ },
+
+ // For inline <script> tags in HTML pages, the column numbers of the start
+ // line are relative to the column immediately after the opening <script> tag,
+ // rather than the start of the line itself. Calculate the start line and any
+ // column displacement from the start of that line in the HTML file.
+ _getStartLineColumnDisplacement() {
+ if (this._startLineColumnDisplacement) {
+ return this._startLineColumnDisplacement;
+ }
+
+ // Allow fetching the partial contents of the HTML file. When getting the
+ // displacement to install breakpoints on an inline source that just
+ // appeared, we don't expect the HTML file to be completely loaded, and if
+ // we wait for it to load then the script will have already started running.
+ // Fetching the partial contents will only return a promise if we haven't
+ // seen any data for the file, which will only be the case when the debugger
+ // attaches to an existing page. In this case we don't need to get the
+ // displacement synchronously, so it's OK if we yield to the event loop
+ // while the promise resolves.
+ const fileContents = this.sourcesManager.urlContents(
+ this.url,
+ /* partial */ true,
+ /* canUseCache */ this._isInlineSource
+ );
+ if (fileContents.then) {
+ return fileContents.then(contents =>
+ this._setStartLineColumnDisplacement(contents)
+ );
+ }
+ return this._setStartLineColumnDisplacement(fileContents);
+ },
+
+ _setStartLineColumnDisplacement(fileContents) {
+ const d = this._calculateStartLineColumnDisplacement(fileContents);
+ this._startLineColumnDisplacement = d;
+ return d;
+ },
+
+ _calculateStartLineColumnDisplacement(fileContents) {
+ const startLine = this._source.startLine;
+
+ const lineBreak = /\r\n?|\n|\u2028|\u2029/;
+ const fileStartLine =
+ fileContents.content.split(lineBreak)[startLine - 1] || "";
+
+ const sourceContents = this._source.text;
+
+ if (lineBreak.test(sourceContents)) {
+ // The inline script must end the HTML file's line.
+ const firstLine = sourceContents.split(lineBreak)[0];
+ if (firstLine.length && fileStartLine.endsWith(firstLine)) {
+ const column = fileStartLine.length - firstLine.length;
+ return { startLine, column };
+ }
+ return {};
+ }
+
+ // The inline script could be anywhere on the line. Search for its
+ // contents in the line's text. This is a best-guess method and may return
+ // the wrong result if the text appears multiple times on the line, but
+ // the result should make some sense to the user in any case.
+ const column = fileStartLine.indexOf(sourceContents);
+ if (column != -1) {
+ return { startLine, column };
+ }
+ return {};
+ },
+
+ // If a { line, column } location is on the starting line of an inline source,
+ // adjust it upwards or downwards (per |upward|) according to the starting
+ // column displacement.
+ _adjustInlineScriptLocation(location, upward) {
+ if (!this._isInlineSource) {
+ return location;
+ }
+
+ const info = this._getStartLineColumnDisplacement();
+ if (info.then) {
+ return info.then(i =>
+ this._adjustInlineScriptLocationFromDisplacement(i, location, upward)
+ );
+ }
+ return this._adjustInlineScriptLocationFromDisplacement(
+ info,
+ location,
+ upward
+ );
+ },
+
+ _adjustInlineScriptLocationFromDisplacement(info, location, upward) {
+ const { line, column } = location;
+ if (this._startLineColumnDisplacement.startLine == line) {
+ let displacement = this._startLineColumnDisplacement.column;
+ if (!upward) {
+ displacement = -displacement;
+ }
+ return { line, column: column + displacement };
+ }
+ return location;
+ },
+
+ // Get all toplevel scripts in the source. Transitive child scripts must be
+ // found by traversing the child script tree.
+ _getTopLevelDebuggeeScripts() {
+ if (this._scripts) {
+ return this._scripts;
+ }
+
+ let scripts = this.dbg.findScripts({ source: this._source });
+
+ if (!this._isWasm) {
+ // There is no easier way to get the top-level scripts right now, so
+ // we have to build that up the list manually.
+ // Note: It is not valid to simply look for scripts where
+ // `.isFunction == false` because a source may have executed multiple
+ // where some have been GCed and some have not (bug 1627712).
+ const allScripts = new Set(scripts);
+ for (const script of allScripts) {
+ for (const child of script.getChildScripts()) {
+ allScripts.delete(child);
+ }
+ }
+ scripts = [...allScripts];
+ }
+
+ this._scripts = scripts;
+ return scripts;
+ },
+
+ resetDebuggeeScripts() {
+ this._scripts = null;
+ },
+
+ // Get toplevel scripts which contain all breakpoint positions for the source.
+ // This is different from _scripts if we detected that some scripts have been
+ // GC'ed and reparsed the source contents.
+ _getTopLevelBreakpointPositionScripts() {
+ if (this._breakpointPositionScripts) {
+ return this._breakpointPositionScripts;
+ }
+
+ let scripts = this._getTopLevelDebuggeeScripts();
+
+ // We need to find all breakpoint positions, even if scripts associated with
+ // this source have been GC'ed. We detect this by looking for a script which
+ // does not have a function: a source will typically have a top level
+ // non-function script. If this top level script still exists, then it keeps
+ // all its child scripts alive and we will find all breakpoint positions by
+ // scanning the existing scripts. If the top level script has been GC'ed
+ // then we won't find its breakpoint positions, and inner functions may have
+ // been GC'ed as well. In this case we reparse the source and generate a new
+ // and complete set of scripts to look for the breakpoint positions.
+ // Note that in some cases like "new Function(stuff)" there might not be a
+ // top level non-function script, but if there is a non-function script then
+ // it must be at the top level and will keep all other scripts in the source
+ // alive.
+ if (!this._isWasm && !scripts.some(script => !script.isFunction)) {
+ let newScript;
+ try {
+ newScript = this._source.reparse();
+ } catch (e) {
+ // reparse() will throw if the source is not valid JS. This can happen
+ // if this source is the resurrection of a GC'ed source and there are
+ // parse errors in the refetched contents.
+ }
+ if (newScript) {
+ scripts = [newScript];
+ }
+ }
+
+ this._breakpointPositionScripts = scripts;
+ return scripts;
+ },
+
+ // Get all scripts in this source that might include content in the range
+ // specified by the given query.
+ _findDebuggeeScripts(query, forBreakpointPositions) {
+ const scripts = forBreakpointPositions
+ ? this._getTopLevelBreakpointPositionScripts()
+ : this._getTopLevelDebuggeeScripts();
+
+ const {
+ start: { line: startLine = 0, column: startColumn = 0 } = {},
+ end: { line: endLine = Infinity, column: endColumn = Infinity } = {},
+ } = query || {};
+
+ const rv = [];
+ addMatchingScripts(scripts);
+ return rv;
+
+ function scriptMatches(script) {
+ // These tests are approximate, as we can't easily get the script's end
+ // column.
+ let lineCount;
+ try {
+ lineCount = script.lineCount;
+ } catch (err) {
+ // Accessing scripts which were optimized out during parsing can throw
+ // an exception. Tolerate these so that we can still get positions for
+ // other scripts in the source.
+ return false;
+ }
+
+ if (
+ script.startLine > endLine ||
+ script.startLine + lineCount <= startLine ||
+ (script.startLine == endLine && script.startColumn > endColumn)
+ ) {
+ return false;
+ }
+
+ if (
+ lineCount == 1 &&
+ script.startLine == startLine &&
+ script.startColumn + script.sourceLength <= startColumn
+ ) {
+ return false;
+ }
+
+ return true;
+ }
+
+ function addMatchingScripts(childScripts) {
+ for (const script of childScripts) {
+ if (scriptMatches(script)) {
+ rv.push(script);
+ if (script.format === "js") {
+ addMatchingScripts(script.getChildScripts());
+ }
+ }
+ }
+ }
+ },
+
+ getBreakpointPositions: async function(query) {
+ const scripts = this._findDebuggeeScripts(
+ query,
+ /* forBreakpointPositions */ true
+ );
+
+ const positions = [];
+ for (const script of scripts) {
+ await this._addScriptBreakpointPositions(query, script, positions);
+ }
+
+ return (
+ positions
+ // Sort the items by location.
+ .sort((a, b) => {
+ const lineDiff = a.line - b.line;
+ return lineDiff === 0 ? a.column - b.column : lineDiff;
+ })
+ );
+ },
+
+ async _addScriptBreakpointPositions(query, script, positions) {
+ const {
+ start: { line: startLine = 0, column: startColumn = 0 } = {},
+ end: { line: endLine = Infinity, column: endColumn = Infinity } = {},
+ } = query || {};
+
+ const offsets = script.getPossibleBreakpoints();
+ for (const { lineNumber, columnNumber } of offsets) {
+ if (
+ lineNumber < startLine ||
+ (lineNumber === startLine && columnNumber < startColumn) ||
+ lineNumber > endLine ||
+ (lineNumber === endLine && columnNumber >= endColumn)
+ ) {
+ continue;
+ }
+
+ // Adjust columns according to any inline script start column, so that
+ // column breakpoints show up correctly in the UI.
+ const position = await this._adjustInlineScriptLocation(
+ {
+ line: lineNumber,
+ column: columnNumber,
+ },
+ /* upward */ true
+ );
+
+ positions.push(position);
+ }
+ },
+
+ getBreakpointPositionsCompressed: async function(query) {
+ const items = await this.getBreakpointPositions(query);
+ const compressed = {};
+ for (const { line, column } of items) {
+ if (!compressed[line]) {
+ compressed[line] = [];
+ }
+ compressed[line].push(column);
+ }
+ return compressed;
+ },
+
+ /**
+ * Handler for the "onSource" packet.
+ * @return Object
+ * The return of this function contains a field `contentType`, and
+ * a field `source`. `source` can either be an ArrayBuffer or
+ * a LongString.
+ */
+ source: async function() {
+ try {
+ const { content, contentType } = await this._getSourceText();
+ if (
+ typeof content === "object" &&
+ content &&
+ content.constructor &&
+ content.constructor.name === "ArrayBuffer"
+ ) {
+ return {
+ source: new ArrayBufferActor(this.threadActor.conn, content),
+ contentType,
+ };
+ }
+
+ return {
+ source: new LongStringActor(this.threadActor.conn, content),
+ contentType,
+ };
+ } catch (error) {
+ reportError(error, "Got an exception during SA_onSource: ");
+ throw new Error(
+ "Could not load the source for " +
+ this.url +
+ ".\n" +
+ DevToolsUtils.safeErrorString(error)
+ );
+ }
+ },
+
+ /**
+ * Handler for the "blackbox" packet.
+ */
+ blackbox: function(range) {
+ this.sourcesManager.blackBox(this.url, range);
+ if (
+ this.threadActor.state == "paused" &&
+ this.threadActor.youngestFrame &&
+ this.threadActor.youngestFrame.script.url == this.url
+ ) {
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Handler for the "unblackbox" packet.
+ */
+ unblackbox: function(range) {
+ this.sourcesManager.unblackBox(this.url, range);
+ },
+
+ /**
+ * Handler for the "setPausePoints" packet.
+ *
+ * @param Array pausePoints
+ * A dictionary of pausePoint objects
+ *
+ * type PausePoints = {
+ * line: {
+ * column: { break?: boolean, step?: boolean }
+ * }
+ * }
+ */
+ setPausePoints: function(pausePoints) {
+ const uncompressed = {};
+ const points = {
+ 0: {},
+ 1: { break: true },
+ 2: { step: true },
+ 3: { break: true, step: true },
+ };
+
+ for (const line in pausePoints) {
+ uncompressed[line] = {};
+ for (const col in pausePoints[line]) {
+ uncompressed[line][col] = points[pausePoints[line][col]];
+ }
+ }
+
+ this.pausePoints = uncompressed;
+ },
+
+ /*
+ * Ensure the given BreakpointActor is set as a breakpoint handler on all
+ * scripts that match its location in the generated source.
+ *
+ * @param BreakpointActor actor
+ * The BreakpointActor to be set as a breakpoint handler.
+ *
+ * @returns A Promise that resolves to the given BreakpointActor.
+ */
+ applyBreakpoint: async function(actor) {
+ let { line, column } = actor.location;
+
+ // Find all entry points that correspond to the given location.
+ const entryPoints = [];
+ if (column === undefined) {
+ // Find all scripts that match the given source actor and line
+ // number.
+ const query = { start: { line }, end: { line } };
+ const scripts = this._findDebuggeeScripts(query).filter(
+ script => !actor.hasScript(script)
+ );
+
+ // This is a line breakpoint, so we add a breakpoint on the first
+ // breakpoint on the line.
+ const lineMatches = [];
+ for (const script of scripts) {
+ const possibleBreakpoints = script.getPossibleBreakpoints({ line });
+ for (const possibleBreakpoint of possibleBreakpoints) {
+ lineMatches.push({ ...possibleBreakpoint, script });
+ }
+ }
+ lineMatches.sort((a, b) => a.columnNumber - b.columnNumber);
+
+ if (lineMatches.length > 0) {
+ // A single Debugger.Source may have _multiple_ Debugger.Scripts
+ // at the same position from multiple evaluations of the source,
+ // so we explicitly want to take all of the matches for the matched
+ // column number.
+ const firstColumn = lineMatches[0].columnNumber;
+ const firstColumnMatches = lineMatches.filter(
+ m => m.columnNumber === firstColumn
+ );
+
+ for (const { script, offset } of firstColumnMatches) {
+ entryPoints.push({ script, offsets: [offset] });
+ }
+ }
+ } else {
+ // Adjust columns according to any inline script start column, to undo
+ // the adjustment performed when sending the breakpoint to the client and
+ // allow the breakpoint to be set correctly in the source (which treats
+ // the location after the <script> tag as column 0).
+ let adjusted = this._adjustInlineScriptLocation(
+ { line, column },
+ /* upward */ false
+ );
+ if (adjusted.then) {
+ adjusted = await adjusted;
+ }
+ line = adjusted.line;
+ column = adjusted.column;
+
+ // Find all scripts that match the given source actor, line,
+ // and column number.
+ const query = { start: { line, column }, end: { line, column } };
+ const scripts = this._findDebuggeeScripts(query).filter(
+ script => !actor.hasScript(script)
+ );
+
+ for (const script of scripts) {
+ // Check to see if the script contains a breakpoint position at
+ // this line and column.
+ const possibleBreakpoint = script
+ .getPossibleBreakpoints({
+ line,
+ minColumn: column,
+ maxColumn: column + 1,
+ })
+ .pop();
+
+ if (possibleBreakpoint) {
+ const { offset } = possibleBreakpoint;
+ entryPoints.push({ script, offsets: [offset] });
+ }
+ }
+ }
+
+ setBreakpointAtEntryPoints(actor, entryPoints);
+ },
+});
+
+exports.SourceActor = SourceActor;
diff --git a/devtools/server/actors/storage.js b/devtools/server/actors/storage.js
new file mode 100644
index 0000000000..11455499b8
--- /dev/null
+++ b/devtools/server/actors/storage.js
@@ -0,0 +1,3768 @@
+/* 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";
+
+const { Cc, Ci, Cu, CC } = require("chrome");
+const protocol = require("devtools/shared/protocol");
+const { LongStringActor } = require("devtools/server/actors/string");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const Services = require("Services");
+const { isWindowIncluded } = require("devtools/shared/layout/utils");
+const specs = require("devtools/shared/specs/storage");
+const { parseItemValue } = require("devtools/shared/storage/utils");
+loader.lazyGetter(this, "ExtensionProcessScript", () => {
+ return require("resource://gre/modules/ExtensionProcessScript.jsm")
+ .ExtensionProcessScript;
+});
+loader.lazyGetter(this, "ExtensionStorageIDB", () => {
+ return require("resource://gre/modules/ExtensionStorageIDB.jsm")
+ .ExtensionStorageIDB;
+});
+loader.lazyGetter(
+ this,
+ "WebExtensionPolicy",
+ () => Cu.getGlobalForObject(ExtensionProcessScript).WebExtensionPolicy
+);
+
+const EXTENSION_STORAGE_ENABLED_PREF =
+ "devtools.storage.extensionStorage.enabled";
+
+const DEFAULT_VALUE = "value";
+
+loader.lazyRequireGetter(
+ this,
+ "naturalSortCaseInsensitive",
+ "devtools/shared/natural-sort",
+ true
+);
+
+// "Lax", "Strict" and "None" are special values of the SameSite property
+// that should not be translated.
+const COOKIE_SAMESITE = {
+ LAX: "Lax",
+ STRICT: "Strict",
+ NONE: "None",
+};
+
+const SAFE_HOSTS_PREFIXES_REGEX = /^(about\+|https?\+|file\+|moz-extension\+)/;
+
+// GUID to be used as a separator in compound keys. This must match the same
+// constant in devtools/client/storage/ui.js,
+// devtools/client/storage/test/head.js and
+// devtools/server/tests/browser/head.js
+const SEPARATOR_GUID = "{9d414cc5-8319-0a04-0586-c0a6ae01670a}";
+
+loader.lazyImporter(this, "OS", "resource://gre/modules/osfile.jsm");
+loader.lazyImporter(this, "Sqlite", "resource://gre/modules/Sqlite.jsm");
+
+// We give this a funny name to avoid confusion with the global
+// indexedDB.
+loader.lazyGetter(this, "indexedDBForStorage", () => {
+ // On xpcshell, we can't instantiate indexedDB without crashing
+ try {
+ const sandbox = Cu.Sandbox(
+ CC("@mozilla.org/systemprincipal;1", "nsIPrincipal")(),
+ { wantGlobalProperties: ["indexedDB"] }
+ );
+ return sandbox.indexedDB;
+ } catch (e) {
+ return {};
+ }
+});
+
+// Maximum number of cookies/local storage key-value-pairs that can be sent
+// over the wire to the client in one request.
+const MAX_STORE_OBJECT_COUNT = 50;
+// Delay for the batch job that sends the accumulated update packets to the
+// client (ms).
+const BATCH_DELAY = 200;
+
+// MAX_COOKIE_EXPIRY should be 2^63-1, but JavaScript can't handle that
+// precision.
+const MAX_COOKIE_EXPIRY = Math.pow(2, 62);
+
+// A RegExp for characters that cannot appear in a file/directory name. This is
+// used to sanitize the host name for indexed db to lookup whether the file is
+// present in <profileDir>/storage/default/ location
+var illegalFileNameCharacters = [
+ "[",
+ // Control characters \001 to \036
+ "\\x00-\\x24",
+ // Special characters
+ '/:*?\\"<>|\\\\',
+ "]",
+].join("");
+var ILLEGAL_CHAR_REGEX = new RegExp(illegalFileNameCharacters, "g");
+
+// Holder for all the registered storage actors.
+var storageTypePool = new Map();
+exports.storageTypePool = storageTypePool;
+
+/**
+ * An async method equivalent to setTimeout but using Promises
+ *
+ * @param {number} time
+ * The wait time in milliseconds.
+ */
+function sleep(time) {
+ return new Promise(resolve => {
+ setTimeout(() => {
+ resolve(null);
+ }, time);
+ });
+}
+
+// Helper methods to create a storage actor.
+var StorageActors = {};
+
+/**
+ * Creates a default object with the common methods required by all storage
+ * actors.
+ *
+ * This default object is missing a couple of required methods that should be
+ * implemented seperately for each actor. They are namely:
+ * - observe : Method which gets triggered on the notificaiton of the watched
+ * topic.
+ * - getNamesForHost : Given a host, get list of all known store names.
+ * - getValuesForHost : Given a host (and optionally a name) get all known
+ * store objects.
+ * - toStoreObject : Given a store object, convert it to the required format
+ * so that it can be transferred over wire.
+ * - populateStoresForHost : Given a host, populate the map of all store
+ * objects for it
+ * - getFields: Given a subType(optional), get an array of objects containing
+ * column field info. The info includes,
+ * "name" is name of colume key.
+ * "editable" is 1 means editable field; 0 means uneditable.
+ *
+ * @param {string} typeName
+ * The typeName of the actor.
+ * @param {array} observationTopics
+ * An array of topics which this actor listens to via Notification Observers.
+ */
+StorageActors.defaults = function(typeName, observationTopics) {
+ return {
+ typeName: typeName,
+
+ get conn() {
+ return this.storageActor.conn;
+ },
+
+ /**
+ * Returns a list of currently known hosts for the target window. This list
+ * contains unique hosts from the window + all inner windows. If
+ * this._internalHosts is defined then these will also be added to the list.
+ */
+ get hosts() {
+ const hosts = new Set();
+ for (const { location } of this.storageActor.windows) {
+ const host = this.getHostName(location);
+
+ if (host) {
+ hosts.add(host);
+ }
+ }
+ if (this._internalHosts) {
+ for (const host of this._internalHosts) {
+ hosts.add(host);
+ }
+ }
+ return hosts;
+ },
+
+ /**
+ * Returns all the windows present on the page. Includes main window + inner
+ * iframe windows.
+ */
+ get windows() {
+ return this.storageActor.windows;
+ },
+
+ /**
+ * Converts the window.location object into a URL (e.g. http://domain.com).
+ */
+ getHostName(location) {
+ if (!location) {
+ // Debugging a legacy Firefox extension... no hostname available and no
+ // storage possible.
+ return null;
+ }
+
+ switch (location.protocol) {
+ case "about:":
+ return `${location.protocol}${location.pathname}`;
+ case "chrome:":
+ // chrome: URLs do not support storage of any type.
+ return null;
+ case "data:":
+ // data: URLs do not support storage of any type.
+ return null;
+ case "file:":
+ return `${location.protocol}//${location.pathname}`;
+ case "javascript:":
+ return location.href;
+ case "moz-extension:":
+ return location.origin;
+ case "resource:":
+ return `${location.origin}${location.pathname}`;
+ default:
+ // http: or unknown protocol.
+ return `${location.protocol}//${location.host}`;
+ }
+ },
+
+ initialize(storageActor) {
+ protocol.Actor.prototype.initialize.call(this, null);
+
+ this.storageActor = storageActor;
+
+ this.populateStoresForHosts();
+ if (observationTopics) {
+ observationTopics.forEach(observationTopic => {
+ Services.obs.addObserver(this, observationTopic);
+ });
+ }
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.onWindowDestroyed = this.onWindowDestroyed.bind(this);
+ this.storageActor.on("window-ready", this.onWindowReady);
+ this.storageActor.on("window-destroyed", this.onWindowDestroyed);
+ },
+
+ destroy() {
+ if (!this.storageActor) {
+ return;
+ }
+
+ if (observationTopics) {
+ observationTopics.forEach(observationTopic => {
+ Services.obs.removeObserver(this, observationTopic);
+ });
+ }
+ this.storageActor.off("window-ready", this.onWindowReady);
+ this.storageActor.off("window-destroyed", this.onWindowDestroyed);
+
+ this.hostVsStores.clear();
+
+ protocol.Actor.prototype.destroy.call(this);
+
+ this.storageActor = null;
+ },
+
+ getNamesForHost(host) {
+ return [...this.hostVsStores.get(host).keys()];
+ },
+
+ getValuesForHost(host, name) {
+ if (name) {
+ return [this.hostVsStores.get(host).get(name)];
+ }
+ return [...this.hostVsStores.get(host).values()];
+ },
+
+ getObjectsSize(host, names) {
+ return names.length;
+ },
+
+ /**
+ * When a new window is added to the page. This generally means that a new
+ * iframe is created, or the current window is completely reloaded.
+ *
+ * @param {window} window
+ * The window which was added.
+ */
+ async onWindowReady(window) {
+ const host = this.getHostName(window.location);
+ if (host && !this.hostVsStores.has(host)) {
+ await this.populateStoresForHost(host, window);
+ if (!this.storageActor) {
+ // The actor might be destroyed during populateStoresForHost.
+ return;
+ }
+
+ const data = {};
+ data[host] = this.getNamesForHost(host);
+ this.storageActor.update("added", typeName, data);
+ }
+ },
+
+ /**
+ * When a window is removed from the page. This generally means that an
+ * iframe was removed, or the current window reload is triggered.
+ *
+ * @param {window} window
+ * The window which was removed.
+ */
+ onWindowDestroyed(window) {
+ if (!window.location) {
+ // Nothing can be done if location object is null
+ return;
+ }
+ const host = this.getHostName(window.location);
+ if (host && !this.hosts.has(host)) {
+ this.hostVsStores.delete(host);
+ const data = {};
+ data[host] = [];
+ this.storageActor.update("deleted", typeName, data);
+ }
+ },
+
+ form() {
+ const hosts = {};
+ for (const host of this.hosts) {
+ hosts[host] = [];
+ }
+
+ return {
+ actor: this.actorID,
+ hosts: hosts,
+ traits: this._getTraits(),
+ };
+ },
+
+ // Share getTraits for child classes overriding form()
+ _getTraits() {
+ return {
+ // The supportsXXX traits are not related to backward compatibility
+ // Different storage actor types implement different APIs, the traits
+ // help the client to know what is supported or not.
+ supportsAddItem: typeof this.addItem === "function",
+ // Note: supportsRemoveItem and supportsRemoveAll are always defined
+ // for all actors. See Bug 1655001.
+ supportsRemoveItem: typeof this.removeItem === "function",
+ supportsRemoveAll: typeof this.removeAll === "function",
+ supportsRemoveAllSessionCookies:
+ typeof this.removeAllSessionCookies === "function",
+ };
+ },
+
+ /**
+ * Populates a map of known hosts vs a map of stores vs value.
+ */
+ populateStoresForHosts() {
+ this.hostVsStores = new Map();
+ for (const host of this.hosts) {
+ this.populateStoresForHost(host);
+ }
+ },
+
+ /**
+ * Returns a list of requested store objects. Maximum values returned are
+ * MAX_STORE_OBJECT_COUNT. This method returns paginated values whose
+ * starting index and total size can be controlled via the options object
+ *
+ * @param {string} host
+ * The host name for which the store values are required.
+ * @param {array:string} names
+ * Array containing the names of required store objects. Empty if all
+ * items are required.
+ * @param {object} options
+ * Additional options for the request containing following
+ * properties:
+ * - offset {number} : The begin index of the returned array amongst
+ * the total values
+ * - size {number} : The number of values required.
+ * - sortOn {string} : The values should be sorted on this property.
+ * - index {string} : In case of indexed db, the IDBIndex to be used
+ * for fetching the values.
+ *
+ * @return {object} An object containing following properties:
+ * - offset - The actual offset of the returned array. This might
+ * be different from the requested offset if that was
+ * invalid
+ * - total - The total number of entries possible.
+ * - data - The requested values.
+ */
+ async getStoreObjects(host, names, options = {}) {
+ const offset = options.offset || 0;
+ let size = options.size || MAX_STORE_OBJECT_COUNT;
+ if (size > MAX_STORE_OBJECT_COUNT) {
+ size = MAX_STORE_OBJECT_COUNT;
+ }
+ const sortOn = options.sortOn || "name";
+
+ const toReturn = {
+ offset: offset,
+ total: 0,
+ data: [],
+ };
+
+ let principal = null;
+ if (this.typeName === "indexedDB") {
+ // We only acquire principal when the type of the storage is indexedDB
+ // because the principal only matters the indexedDB.
+ const win = this.storageActor.getWindowFromHost(host);
+ principal = this.getPrincipal(win);
+ }
+
+ if (names) {
+ for (const name of names) {
+ const values = await this.getValuesForHost(
+ host,
+ name,
+ options,
+ this.hostVsStores,
+ principal
+ );
+
+ const { result, objectStores } = values;
+
+ if (result && typeof result.objectsSize !== "undefined") {
+ for (const { key, count } of result.objectsSize) {
+ this.objectsSize[key] = count;
+ }
+ }
+
+ if (result) {
+ toReturn.data.push(...result.data);
+ } else if (objectStores) {
+ toReturn.data.push(...objectStores);
+ } else {
+ toReturn.data.push(...values);
+ }
+ }
+
+ toReturn.total = this.getObjectsSize(host, names, options);
+ } else {
+ let obj = await this.getValuesForHost(
+ host,
+ undefined,
+ undefined,
+ this.hostVsStores,
+ principal
+ );
+ if (obj.dbs) {
+ obj = obj.dbs;
+ }
+
+ toReturn.total = obj.length;
+ toReturn.data = obj;
+ }
+
+ if (offset > toReturn.total) {
+ // In this case, toReturn.data is an empty array.
+ toReturn.offset = toReturn.total;
+ toReturn.data = [];
+ } else {
+ // We need to use natural sort before slicing.
+ const sorted = toReturn.data.sort((a, b) => {
+ return naturalSortCaseInsensitive(a[sortOn], b[sortOn]);
+ });
+ let sliced;
+ if (this.typeName === "indexedDB") {
+ // indexedDB's getValuesForHost never returns *all* values available but only
+ // a slice, starting at the expected offset. Therefore the result is already
+ // sliced as expected.
+ sliced = sorted;
+ } else {
+ sliced = sorted.slice(offset, offset + size);
+ }
+ toReturn.data = sliced.map(a => this.toStoreObject(a));
+ }
+
+ return toReturn;
+ },
+
+ getPrincipal(win) {
+ if (win) {
+ return win.document.effectiveStoragePrincipal;
+ }
+ // We are running in the browser toolbox and viewing system DBs so we
+ // need to use system principal.
+ return Cc["@mozilla.org/systemprincipal;1"].createInstance(
+ Ci.nsIPrincipal
+ );
+ },
+ };
+};
+
+/**
+ * Creates an actor and its corresponding front and registers it to the Storage
+ * Actor.
+ *
+ * @See StorageActors.defaults()
+ *
+ * @param {object} options
+ * Options required by StorageActors.defaults method which are :
+ * - typeName {string}
+ * The typeName of the actor.
+ * - observationTopics {array}
+ * The topics which this actor listens to via
+ * Notification Observers.
+ * @param {object} overrides
+ * All the methods which you want to be different from the ones in
+ * StorageActors.defaults method plus the required ones described there.
+ */
+StorageActors.createActor = function(options = {}, overrides = {}) {
+ const actorObject = StorageActors.defaults(
+ options.typeName,
+ options.observationTopics || null
+ );
+ for (const key in overrides) {
+ actorObject[key] = overrides[key];
+ }
+
+ const actorSpec = specs.childSpecs[options.typeName];
+ const actor = protocol.ActorClassWithSpec(actorSpec, actorObject);
+ storageTypePool.set(actorObject.typeName, actor);
+};
+
+/**
+ * The Cookies actor and front.
+ */
+StorageActors.createActor(
+ {
+ typeName: "cookies",
+ },
+ {
+ initialize(storageActor) {
+ protocol.Actor.prototype.initialize.call(this, null);
+
+ this.storageActor = storageActor;
+
+ this.maybeSetupChildProcess();
+ this.populateStoresForHosts();
+ this.addCookieObservers();
+
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.onWindowDestroyed = this.onWindowDestroyed.bind(this);
+ this.storageActor.on("window-ready", this.onWindowReady);
+ this.storageActor.on("window-destroyed", this.onWindowDestroyed);
+ },
+
+ destroy() {
+ this.hostVsStores.clear();
+
+ // We need to remove the cookie listeners early in E10S mode so we need to
+ // use a conditional here to ensure that we only attempt to remove them in
+ // single process mode.
+ if (!DevToolsServer.isInChildProcess) {
+ this.removeCookieObservers();
+ }
+
+ this.storageActor.off("window-ready", this.onWindowReady);
+ this.storageActor.off("window-destroyed", this.onWindowDestroyed);
+
+ this._pendingResponse = null;
+
+ protocol.Actor.prototype.destroy.call(this);
+
+ this.storageActor = null;
+ },
+
+ /**
+ * Given a cookie object, figure out all the matching hosts from the page that
+ * the cookie belong to.
+ */
+ getMatchingHosts(cookies) {
+ if (!cookies.length) {
+ cookies = [cookies];
+ }
+ const hosts = new Set();
+ for (const host of this.hosts) {
+ for (const cookie of cookies) {
+ if (this.isCookieAtHost(cookie, host)) {
+ hosts.add(host);
+ }
+ }
+ }
+ return [...hosts];
+ },
+
+ /**
+ * Given a cookie object and a host, figure out if the cookie is valid for
+ * that host.
+ */
+ isCookieAtHost(cookie, host) {
+ if (cookie.host == null) {
+ return host == null;
+ }
+
+ host = trimHttpHttpsPort(host);
+
+ if (cookie.host.startsWith(".")) {
+ return ("." + host).endsWith(cookie.host);
+ }
+ if (cookie.host === "") {
+ return host.startsWith("file://" + cookie.path);
+ }
+
+ return cookie.host == host;
+ },
+
+ toStoreObject(cookie) {
+ if (!cookie) {
+ return null;
+ }
+
+ return {
+ uniqueKey:
+ `${cookie.name}${SEPARATOR_GUID}${cookie.host}` +
+ `${SEPARATOR_GUID}${cookie.path}`,
+ name: cookie.name,
+ host: cookie.host || "",
+ path: cookie.path || "",
+
+ // because expires is in seconds
+ expires: (cookie.expires || 0) * 1000,
+
+ // because creationTime is in micro seconds
+ creationTime: cookie.creationTime / 1000,
+
+ size: cookie.name.length + (cookie.value || "").length,
+
+ // - do -
+ lastAccessed: cookie.lastAccessed / 1000,
+ value: new LongStringActor(this.conn, cookie.value || ""),
+ hostOnly: !cookie.isDomain,
+ isSecure: cookie.isSecure,
+ isHttpOnly: cookie.isHttpOnly,
+ sameSite: this.getSameSiteStringFromCookie(cookie),
+ };
+ },
+
+ getSameSiteStringFromCookie(cookie) {
+ switch (cookie.sameSite) {
+ case cookie.SAMESITE_LAX:
+ return COOKIE_SAMESITE.LAX;
+ case cookie.SAMESITE_STRICT:
+ return COOKIE_SAMESITE.STRICT;
+ }
+ // cookie.SAMESITE_NONE
+ return COOKIE_SAMESITE.NONE;
+ },
+
+ populateStoresForHost(host) {
+ this.hostVsStores.set(host, new Map());
+
+ const originAttributes = this.getOriginAttributesFromHost(host);
+ const cookies = this.getCookiesFromHost(host, originAttributes);
+
+ for (const cookie of cookies) {
+ if (this.isCookieAtHost(cookie, host)) {
+ const uniqueKey =
+ `${cookie.name}${SEPARATOR_GUID}${cookie.host}` +
+ `${SEPARATOR_GUID}${cookie.path}`;
+
+ this.hostVsStores.get(host).set(uniqueKey, cookie);
+ }
+ }
+ },
+
+ getOriginAttributesFromHost(host) {
+ const win = this.storageActor.getWindowFromHost(host);
+ let originAttributes;
+ if (win) {
+ originAttributes =
+ win.document.effectiveStoragePrincipal.originAttributes;
+ } else {
+ // If we can't find the window by host, fallback to the top window
+ // origin attributes.
+ originAttributes = this.storageActor.document.effectiveStoragePrincipal
+ .originAttributes;
+ }
+
+ return originAttributes;
+ },
+
+ /**
+ * Notification observer for "cookie-change".
+ *
+ * @param subject
+ * {Cookie|[Array]} A JSON parsed object containing either a single
+ * cookie representation or an array. Array is only in case of
+ * a "batch-deleted" action.
+ * @param {string} topic
+ * The topic of the notification.
+ * @param {string} action
+ * Additional data associated with the notification. Its the type of
+ * cookie change in the "cookie-change" topic.
+ */
+ onCookieChanged(subject, topic, action) {
+ if (
+ topic !== "cookie-changed" ||
+ !this.storageActor ||
+ !this.storageActor.windows
+ ) {
+ return null;
+ }
+
+ const hosts = this.getMatchingHosts(subject);
+ const data = {};
+
+ switch (action) {
+ case "added":
+ case "changed":
+ if (hosts.length) {
+ for (const host of hosts) {
+ const uniqueKey =
+ `${subject.name}${SEPARATOR_GUID}${subject.host}` +
+ `${SEPARATOR_GUID}${subject.path}`;
+
+ this.hostVsStores.get(host).set(uniqueKey, subject);
+ data[host] = [uniqueKey];
+ }
+ this.storageActor.update(action, "cookies", data);
+ }
+ break;
+
+ case "deleted":
+ if (hosts.length) {
+ for (const host of hosts) {
+ const uniqueKey =
+ `${subject.name}${SEPARATOR_GUID}${subject.host}` +
+ `${SEPARATOR_GUID}${subject.path}`;
+
+ this.hostVsStores.get(host).delete(uniqueKey);
+ data[host] = [uniqueKey];
+ }
+ this.storageActor.update("deleted", "cookies", data);
+ }
+ break;
+
+ case "batch-deleted":
+ if (hosts.length) {
+ for (const host of hosts) {
+ const stores = [];
+ for (const cookie of subject) {
+ const uniqueKey =
+ `${cookie.name}${SEPARATOR_GUID}${cookie.host}` +
+ `${SEPARATOR_GUID}${cookie.path}`;
+
+ this.hostVsStores.get(host).delete(uniqueKey);
+ stores.push(uniqueKey);
+ }
+ data[host] = stores;
+ }
+ this.storageActor.update("deleted", "cookies", data);
+ }
+ break;
+
+ case "cleared":
+ if (hosts.length) {
+ for (const host of hosts) {
+ data[host] = [];
+ }
+ this.storageActor.update("cleared", "cookies", data);
+ }
+ break;
+ }
+ return null;
+ },
+
+ async getFields() {
+ return [
+ { name: "uniqueKey", editable: false, private: true },
+ { name: "name", editable: true, hidden: false },
+ { name: "value", editable: true, hidden: false },
+ { name: "host", editable: true, hidden: false },
+ { name: "path", editable: true, hidden: false },
+ { name: "expires", editable: true, hidden: false },
+ { name: "size", editable: false, hidden: false },
+ { name: "isHttpOnly", editable: true, hidden: false },
+ { name: "isSecure", editable: true, hidden: false },
+ { name: "sameSite", editable: false, hidden: false },
+ { name: "lastAccessed", editable: false, hidden: false },
+ { name: "creationTime", editable: false, hidden: true },
+ { name: "hostOnly", editable: false, hidden: true },
+ ];
+ },
+
+ /**
+ * Pass the editItem command from the content to the chrome process.
+ *
+ * @param {Object} data
+ * See editCookie() for format details.
+ */
+ async editItem(data) {
+ data.originAttributes = this.getOriginAttributesFromHost(data.host);
+ this.editCookie(data);
+ },
+
+ async addItem(guid) {
+ const doc = this.storageActor.document;
+ const time = new Date().getTime();
+ const expiry = new Date(time + 3600 * 24 * 1000).toGMTString();
+
+ doc.cookie = `${guid}=${DEFAULT_VALUE};expires=${expiry}`;
+ },
+
+ async removeItem(host, name) {
+ const originAttributes = this.getOriginAttributesFromHost(host);
+ this.removeCookie(host, name, originAttributes);
+ },
+
+ async removeAll(host, domain) {
+ const originAttributes = this.getOriginAttributesFromHost(host);
+ this.removeAllCookies(host, domain, originAttributes);
+ },
+
+ async removeAllSessionCookies(host, domain) {
+ const originAttributes = this.getOriginAttributesFromHost(host);
+ this.removeAllSessionCookies(host, domain, originAttributes);
+ },
+
+ maybeSetupChildProcess() {
+ cookieHelpers.onCookieChanged = this.onCookieChanged.bind(this);
+
+ if (!DevToolsServer.isInChildProcess) {
+ this.getCookiesFromHost = cookieHelpers.getCookiesFromHost.bind(
+ cookieHelpers
+ );
+ this.addCookieObservers = cookieHelpers.addCookieObservers.bind(
+ cookieHelpers
+ );
+ this.removeCookieObservers = cookieHelpers.removeCookieObservers.bind(
+ cookieHelpers
+ );
+ this.editCookie = cookieHelpers.editCookie.bind(cookieHelpers);
+ this.removeCookie = cookieHelpers.removeCookie.bind(cookieHelpers);
+ this.removeAllCookies = cookieHelpers.removeAllCookies.bind(
+ cookieHelpers
+ );
+ this.removeAllSessionCookies = cookieHelpers.removeAllSessionCookies.bind(
+ cookieHelpers
+ );
+ return;
+ }
+
+ const mm = this.conn.parentMessageManager;
+
+ // eslint-disable-next-line no-restricted-properties
+ this.conn.setupInParent({
+ module: "devtools/server/actors/storage",
+ setupParent: "setupParentProcessForCookies",
+ });
+
+ this.getCookiesFromHost = callParentProcess.bind(
+ null,
+ "getCookiesFromHost"
+ );
+ this.addCookieObservers = callParentProcess.bind(
+ null,
+ "addCookieObservers"
+ );
+ this.removeCookieObservers = callParentProcess.bind(
+ null,
+ "removeCookieObservers"
+ );
+ this.editCookie = callParentProcess.bind(null, "editCookie");
+ this.removeCookie = callParentProcess.bind(null, "removeCookie");
+ this.removeAllCookies = callParentProcess.bind(null, "removeAllCookies");
+ this.removeAllSessionCookies = callParentProcess.bind(
+ null,
+ "removeAllSessionCookies"
+ );
+
+ mm.addMessageListener(
+ "debug:storage-cookie-request-child",
+ cookieHelpers.handleParentRequest
+ );
+
+ function callParentProcess(methodName, ...args) {
+ const reply = mm.sendSyncMessage(
+ "debug:storage-cookie-request-parent",
+ {
+ method: methodName,
+ args: args,
+ }
+ );
+
+ if (reply.length === 0) {
+ console.error("ERR_DIRECTOR_CHILD_NO_REPLY from " + methodName);
+ } else if (reply.length > 1) {
+ console.error(
+ "ERR_DIRECTOR_CHILD_MULTIPLE_REPLIES from " + methodName
+ );
+ }
+
+ const result = reply[0];
+
+ if (methodName === "getCookiesFromHost") {
+ return JSON.parse(result);
+ }
+
+ return result;
+ }
+ },
+ }
+);
+
+var cookieHelpers = {
+ getCookiesFromHost(host, originAttributes) {
+ // Local files have no host.
+ if (host.startsWith("file:///")) {
+ host = "";
+ }
+
+ host = trimHttpHttpsPort(host);
+
+ return Services.cookies.getCookiesFromHost(host, originAttributes);
+ },
+
+ /**
+ * Apply the results of a cookie edit.
+ *
+ * @param {Object} data
+ * An object in the following format:
+ * {
+ * host: "http://www.mozilla.org",
+ * field: "value",
+ * editCookie: "name",
+ * oldValue: "%7BHello%7D",
+ * newValue: "%7BHelloo%7D",
+ * items: {
+ * name: "optimizelyBuckets",
+ * path: "/",
+ * host: ".mozilla.org",
+ * expires: "Mon, 02 Jun 2025 12:37:37 GMT",
+ * creationTime: "Tue, 18 Nov 2014 16:21:18 GMT",
+ * lastAccessed: "Wed, 17 Feb 2016 10:06:23 GMT",
+ * value: "%7BHelloo%7D",
+ * isDomain: "true",
+ * isSecure: "false",
+ * isHttpOnly: "false"
+ * }
+ * }
+ */
+ // eslint-disable-next-line complexity
+ editCookie(data) {
+ let { field, oldValue, newValue } = data;
+ const origName = field === "name" ? oldValue : data.items.name;
+ const origHost = field === "host" ? oldValue : data.items.host;
+ const origPath = field === "path" ? oldValue : data.items.path;
+ let cookie = null;
+
+ const cookies = Services.cookies.getCookiesFromHost(
+ origHost,
+ data.originAttributes || {}
+ );
+ for (const nsiCookie of cookies) {
+ if (
+ nsiCookie.name === origName &&
+ nsiCookie.host === origHost &&
+ nsiCookie.path === origPath
+ ) {
+ cookie = {
+ host: nsiCookie.host,
+ path: nsiCookie.path,
+ name: nsiCookie.name,
+ value: nsiCookie.value,
+ isSecure: nsiCookie.isSecure,
+ isHttpOnly: nsiCookie.isHttpOnly,
+ isSession: nsiCookie.isSession,
+ expires: nsiCookie.expires,
+ originAttributes: nsiCookie.originAttributes,
+ schemeMap: nsiCookie.schemeMap,
+ };
+ break;
+ }
+ }
+
+ if (!cookie) {
+ return;
+ }
+
+ // If the date is expired set it for 10 seconds in the future.
+ const now = new Date();
+ if (!cookie.isSession && cookie.expires * 1000 <= now) {
+ const tenSecondsFromNow = (now.getTime() + 10 * 1000) / 1000;
+
+ cookie.expires = tenSecondsFromNow;
+ }
+
+ switch (field) {
+ case "isSecure":
+ case "isHttpOnly":
+ case "isSession":
+ newValue = newValue === "true";
+ break;
+
+ case "expires":
+ newValue = Date.parse(newValue) / 1000;
+
+ if (isNaN(newValue)) {
+ newValue = MAX_COOKIE_EXPIRY;
+ }
+ break;
+
+ case "host":
+ case "name":
+ case "path":
+ // Remove the edited cookie.
+ Services.cookies.remove(
+ origHost,
+ origName,
+ origPath,
+ cookie.originAttributes
+ );
+ break;
+ }
+
+ // Apply changes.
+ cookie[field] = newValue;
+
+ // cookie.isSession is not always set correctly on session cookies so we
+ // need to trust cookie.expires instead.
+ cookie.isSession = !cookie.expires;
+
+ // Add the edited cookie.
+ Services.cookies.add(
+ cookie.host,
+ cookie.path,
+ cookie.name,
+ cookie.value,
+ cookie.isSecure,
+ cookie.isHttpOnly,
+ cookie.isSession,
+ cookie.isSession ? MAX_COOKIE_EXPIRY : cookie.expires,
+ cookie.originAttributes,
+ cookie.sameSite,
+ cookie.schemeMap
+ );
+ },
+
+ _removeCookies(host, opts = {}) {
+ // We use a uniqueId to emulate compound keys for cookies. We need to
+ // extract the cookie name to remove the correct cookie.
+ if (opts.name) {
+ const split = opts.name.split(SEPARATOR_GUID);
+
+ opts.name = split[0];
+ opts.path = split[2];
+ }
+
+ host = trimHttpHttpsPort(host);
+
+ function hostMatches(cookieHost, matchHost) {
+ if (cookieHost == null) {
+ return matchHost == null;
+ }
+ if (cookieHost.startsWith(".")) {
+ return ("." + matchHost).endsWith(cookieHost);
+ }
+ return cookieHost == host;
+ }
+
+ const cookies = Services.cookies.getCookiesFromHost(
+ host,
+ opts.originAttributes || {}
+ );
+ for (const cookie of cookies) {
+ if (
+ hostMatches(cookie.host, host) &&
+ (!opts.name || cookie.name === opts.name) &&
+ (!opts.domain || cookie.host === opts.domain) &&
+ (!opts.path || cookie.path === opts.path) &&
+ (!opts.session || (!cookie.expires && !cookie.maxAge))
+ ) {
+ Services.cookies.remove(
+ cookie.host,
+ cookie.name,
+ cookie.path,
+ cookie.originAttributes
+ );
+ }
+ }
+ },
+
+ removeCookie(host, name, originAttributes) {
+ if (name !== undefined) {
+ this._removeCookies(host, { name, originAttributes });
+ }
+ },
+
+ removeAllCookies(host, domain, originAttributes) {
+ this._removeCookies(host, { domain, originAttributes });
+ },
+
+ removeAllSessionCookies(host, domain, originAttributes) {
+ this._removeCookies(host, { domain, originAttributes, session: true });
+ },
+
+ addCookieObservers() {
+ Services.obs.addObserver(cookieHelpers, "cookie-changed");
+ return null;
+ },
+
+ removeCookieObservers() {
+ Services.obs.removeObserver(cookieHelpers, "cookie-changed");
+ return null;
+ },
+
+ observe(subject, topic, data) {
+ if (!subject) {
+ return;
+ }
+
+ switch (topic) {
+ case "cookie-changed":
+ if (data === "batch-deleted") {
+ const cookiesNoInterface = subject.QueryInterface(Ci.nsIArray);
+ const cookies = [];
+
+ for (let i = 0; i < cookiesNoInterface.length; i++) {
+ const cookie = cookiesNoInterface.queryElementAt(i, Ci.nsICookie);
+ cookies.push(cookie);
+ }
+ cookieHelpers.onCookieChanged(cookies, topic, data);
+
+ return;
+ }
+
+ const cookie = subject.QueryInterface(Ci.nsICookie);
+ cookieHelpers.onCookieChanged(cookie, topic, data);
+ break;
+ }
+ },
+
+ handleParentRequest(msg) {
+ switch (msg.json.method) {
+ case "onCookieChanged":
+ let [cookie, topic, data] = msg.data.args;
+ cookie = JSON.parse(cookie);
+ cookieHelpers.onCookieChanged(cookie, topic, data);
+ break;
+ }
+ },
+
+ handleChildRequest(msg) {
+ switch (msg.json.method) {
+ case "getCookiesFromHost": {
+ const host = msg.data.args[0];
+ const originAttributes = msg.data.args[1];
+ const cookies = cookieHelpers.getCookiesFromHost(
+ host,
+ originAttributes
+ );
+ return JSON.stringify(cookies);
+ }
+ case "addCookieObservers": {
+ return cookieHelpers.addCookieObservers();
+ }
+ case "removeCookieObservers": {
+ return cookieHelpers.removeCookieObservers();
+ }
+ case "editCookie": {
+ const rowdata = msg.data.args[0];
+ return cookieHelpers.editCookie(rowdata);
+ }
+ case "createNewCookie": {
+ const host = msg.data.args[0];
+ const guid = msg.data.args[1];
+ const originAttributes = msg.data.args[2];
+ return cookieHelpers.createNewCookie(host, guid, originAttributes);
+ }
+ case "removeCookie": {
+ const host = msg.data.args[0];
+ const name = msg.data.args[1];
+ const originAttributes = msg.data.args[2];
+ return cookieHelpers.removeCookie(host, name, originAttributes);
+ }
+ case "removeAllCookies": {
+ const host = msg.data.args[0];
+ const domain = msg.data.args[1];
+ const originAttributes = msg.data.args[2];
+ return cookieHelpers.removeAllCookies(host, domain, originAttributes);
+ }
+ case "removeAllSessionCookies": {
+ const host = msg.data.args[0];
+ const domain = msg.data.args[1];
+ const originAttributes = msg.data.args[2];
+ return cookieHelpers.removeAllSessionCookies(
+ host,
+ domain,
+ originAttributes
+ );
+ }
+ default:
+ console.error("ERR_DIRECTOR_PARENT_UNKNOWN_METHOD", msg.json.method);
+ throw new Error("ERR_DIRECTOR_PARENT_UNKNOWN_METHOD");
+ }
+ },
+};
+
+/**
+ * E10S parent/child setup helpers
+ */
+
+exports.setupParentProcessForCookies = function({ mm, prefix }) {
+ cookieHelpers.onCookieChanged = callChildProcess.bind(
+ null,
+ "onCookieChanged"
+ );
+
+ // listen for director-script requests from the child process
+ mm.addMessageListener(
+ "debug:storage-cookie-request-parent",
+ cookieHelpers.handleChildRequest
+ );
+
+ function callChildProcess(methodName, ...args) {
+ if (methodName === "onCookieChanged") {
+ args[0] = JSON.stringify(args[0]);
+ }
+
+ try {
+ mm.sendAsyncMessage("debug:storage-cookie-request-child", {
+ method: methodName,
+ args: args,
+ });
+ } catch (e) {
+ // We may receive a NS_ERROR_NOT_INITIALIZED if the target window has
+ // been closed. This can legitimately happen in between test runs.
+ }
+ }
+
+ return {
+ onDisconnected: () => {
+ // Although "disconnected-from-child" implies that the child is already
+ // disconnected this is not the case. The disconnection takes place after
+ // this method has finished. This gives us chance to clean up items within
+ // the parent process e.g. observers.
+ cookieHelpers.removeCookieObservers();
+ mm.removeMessageListener(
+ "debug:storage-cookie-request-parent",
+ cookieHelpers.handleChildRequest
+ );
+ },
+ };
+};
+
+/**
+ * Helper method to create the overriden object required in
+ * StorageActors.createActor for Local Storage and Session Storage.
+ * This method exists as both Local Storage and Session Storage have almost
+ * identical actors.
+ */
+function getObjectForLocalOrSessionStorage(type) {
+ return {
+ getNamesForHost(host) {
+ const storage = this.hostVsStores.get(host);
+ return storage ? Object.keys(storage) : [];
+ },
+
+ getValuesForHost(host, name) {
+ const storage = this.hostVsStores.get(host);
+ if (!storage) {
+ return [];
+ }
+ if (name) {
+ const value = storage ? storage.getItem(name) : null;
+ return [{ name, value }];
+ }
+ if (!storage) {
+ return [];
+ }
+
+ // local and session storage cannot be iterated over using Object.keys()
+ // because it skips keys that are duplicated on the prototype
+ // e.g. "key", "getKeys" so we need to gather the real keys using the
+ // storage.key() function.
+ const storageArray = [];
+ for (let i = 0; i < storage.length; i++) {
+ const key = storage.key(i);
+ storageArray.push({
+ name: key,
+ value: storage.getItem(key),
+ });
+ }
+ return storageArray;
+ },
+
+ populateStoresForHost(host, window) {
+ try {
+ this.hostVsStores.set(host, window[type]);
+ } catch (ex) {
+ console.warn(`Failed to enumerate ${type} for host ${host}: ${ex}`);
+ }
+ },
+
+ populateStoresForHosts() {
+ this.hostVsStores = new Map();
+ for (const window of this.windows) {
+ const host = this.getHostName(window.location);
+ if (host) {
+ this.populateStoresForHost(host, window);
+ }
+ }
+ },
+
+ async getFields() {
+ return [
+ { name: "name", editable: true },
+ { name: "value", editable: true },
+ ];
+ },
+
+ async addItem(guid, host) {
+ const storage = this.hostVsStores.get(host);
+ if (!storage) {
+ return;
+ }
+ storage.setItem(guid, DEFAULT_VALUE);
+ },
+
+ /**
+ * Edit localStorage or sessionStorage fields.
+ *
+ * @param {Object} data
+ * See editCookie() for format details.
+ */
+ async editItem({ host, field, oldValue, items }) {
+ const storage = this.hostVsStores.get(host);
+ if (!storage) {
+ return;
+ }
+
+ if (field === "name") {
+ storage.removeItem(oldValue);
+ }
+
+ storage.setItem(items.name, items.value);
+ },
+
+ async removeItem(host, name) {
+ const storage = this.hostVsStores.get(host);
+ if (!storage) {
+ return;
+ }
+ storage.removeItem(name);
+ },
+
+ async removeAll(host) {
+ const storage = this.hostVsStores.get(host);
+ if (!storage) {
+ return;
+ }
+ storage.clear();
+ },
+
+ observe(subject, topic, data) {
+ if (
+ (topic != "dom-storage2-changed" &&
+ topic != "dom-private-storage2-changed") ||
+ data != type
+ ) {
+ return null;
+ }
+
+ const host = this.getSchemaAndHost(subject.url);
+
+ if (!this.hostVsStores.has(host)) {
+ return null;
+ }
+
+ let action = "changed";
+ if (subject.key == null) {
+ return this.storageActor.update("cleared", type, [host]);
+ } else if (subject.oldValue == null) {
+ action = "added";
+ } else if (subject.newValue == null) {
+ action = "deleted";
+ }
+ const updateData = {};
+ updateData[host] = [subject.key];
+ return this.storageActor.update(action, type, updateData);
+ },
+
+ /**
+ * Given a url, correctly determine its protocol + hostname part.
+ */
+ getSchemaAndHost(url) {
+ const uri = Services.io.newURI(url);
+ if (!uri.host) {
+ return uri.spec;
+ }
+ return uri.scheme + "://" + uri.hostPort;
+ },
+
+ toStoreObject(item) {
+ if (!item) {
+ return null;
+ }
+
+ return {
+ name: item.name,
+ value: new LongStringActor(this.conn, item.value || ""),
+ };
+ },
+ };
+}
+
+/**
+ * The Local Storage actor and front.
+ */
+StorageActors.createActor(
+ {
+ typeName: "localStorage",
+ observationTopics: ["dom-storage2-changed", "dom-private-storage2-changed"],
+ },
+ getObjectForLocalOrSessionStorage("localStorage")
+);
+
+/**
+ * The Session Storage actor and front.
+ */
+StorageActors.createActor(
+ {
+ typeName: "sessionStorage",
+ observationTopics: ["dom-storage2-changed", "dom-private-storage2-changed"],
+ },
+ getObjectForLocalOrSessionStorage("sessionStorage")
+);
+
+const extensionStorageHelpers = {
+ unresolvedPromises: new Map(),
+ // Map of addonId => onStorageChange listeners in the parent process. Each addon toolbox targets
+ // a single addon, and multiple addon toolboxes could be open at the same time.
+ onChangedParentListeners: new Map(),
+ // Set of onStorageChange listeners in the extension child process. Each addon toolbox will create
+ // a separate extensionStorage actor targeting that addon. The addonId is passed into the listener,
+ // so that changes propagate only if the storage actor has a matching addonId.
+ onChangedChildListeners: new Set(),
+ /**
+ * Editing is supported only for serializable types. Examples of unserializable
+ * types include Map, Set and ArrayBuffer.
+ */
+ isEditable(value) {
+ // Bug 1542038: the managed storage area is never editable
+ for (const { test } of Object.values(this.supportedTypes)) {
+ if (test(value)) {
+ return true;
+ }
+ }
+ return false;
+ },
+ isPrimitive(value) {
+ const primitiveValueTypes = ["string", "number", "boolean"];
+ return primitiveValueTypes.includes(typeof value) || value === null;
+ },
+ isObjectLiteral(value) {
+ return (
+ value &&
+ typeof value === "object" &&
+ Cu.getClassName(value, true) === "Object"
+ );
+ },
+ // Nested arrays or object literals are only editable 2 levels deep
+ isArrayOrObjectLiteralEditable(obj) {
+ const topLevelValuesArr = Array.isArray(obj) ? obj : Object.values(obj);
+ if (
+ topLevelValuesArr.some(
+ value =>
+ !this.isPrimitive(value) &&
+ !Array.isArray(value) &&
+ !this.isObjectLiteral(value)
+ )
+ ) {
+ // At least one value is too complex to parse
+ return false;
+ }
+ const arrayOrObjects = topLevelValuesArr.filter(
+ value => Array.isArray(value) || this.isObjectLiteral(value)
+ );
+ if (arrayOrObjects.length === 0) {
+ // All top level values are primitives
+ return true;
+ }
+
+ // One or more top level values was an array or object literal.
+ // All of these top level values must themselves have only primitive values
+ // for the object to be editable
+ for (const nestedObj of arrayOrObjects) {
+ const secondLevelValuesArr = Array.isArray(nestedObj)
+ ? nestedObj
+ : Object.values(nestedObj);
+ if (secondLevelValuesArr.some(value => !this.isPrimitive(value))) {
+ return false;
+ }
+ }
+ return true;
+ },
+ typesFromString: {
+ // Helper methods to parse string values in editItem
+ jsonifiable: {
+ test(str) {
+ try {
+ JSON.parse(str);
+ } catch (e) {
+ return false;
+ }
+ return true;
+ },
+ parse(str) {
+ return JSON.parse(str);
+ },
+ },
+ },
+ supportedTypes: {
+ // Helper methods to determine the value type of an item in isEditable
+ array: {
+ test(value) {
+ if (Array.isArray(value)) {
+ return extensionStorageHelpers.isArrayOrObjectLiteralEditable(value);
+ }
+ return false;
+ },
+ },
+ boolean: {
+ test(value) {
+ return typeof value === "boolean";
+ },
+ },
+ null: {
+ test(value) {
+ return value === null;
+ },
+ },
+ number: {
+ test(value) {
+ return typeof value === "number";
+ },
+ },
+ object: {
+ test(value) {
+ if (extensionStorageHelpers.isObjectLiteral(value)) {
+ return extensionStorageHelpers.isArrayOrObjectLiteralEditable(value);
+ }
+ return false;
+ },
+ },
+ string: {
+ test(value) {
+ return typeof value === "string";
+ },
+ },
+ },
+
+ // Sets the parent process message manager
+ setPpmm(ppmm) {
+ this.ppmm = ppmm;
+ },
+
+ // A promise in the main process has resolved, and we need to pass the return value(s)
+ // back to the child process
+ backToChild(...args) {
+ Services.mm.broadcastAsyncMessage(
+ "debug:storage-extensionStorage-request-child",
+ {
+ method: "backToChild",
+ args: args,
+ }
+ );
+ },
+
+ // Send a message from the main process to a listener in the child process that the
+ // extension has modified storage local data
+ fireStorageOnChanged({ addonId, changes }) {
+ Services.mm.broadcastAsyncMessage(
+ "debug:storage-extensionStorage-request-child",
+ {
+ addonId,
+ changes,
+ method: "storageOnChanged",
+ }
+ );
+ },
+
+ // Subscribe a listener for event notifications from the WE storage API when
+ // storage local data has been changed by the extension, and keep track of the
+ // listener to remove it when the debugger is being disconnected.
+ subscribeOnChangedListenerInParent(addonId) {
+ if (!this.onChangedParentListeners.has(addonId)) {
+ const onChangedListener = changes => {
+ this.fireStorageOnChanged({ addonId, changes });
+ };
+ ExtensionStorageIDB.addOnChangedListener(addonId, onChangedListener);
+ this.onChangedParentListeners.set(addonId, onChangedListener);
+ }
+ },
+
+ // The main process does not require an extension context to select the backend
+ // Bug 1542038, 1542039: Each storage area will need its own implementation, as
+ // they use different storage backends.
+ async setupStorageInParent(addonId) {
+ const { extension } = WebExtensionPolicy.getByID(addonId);
+ const parentResult = await ExtensionStorageIDB.selectBackend({ extension });
+ const result = {
+ ...parentResult,
+ // Received as a StructuredCloneHolder, so we need to deserialize
+ storagePrincipal: parentResult.storagePrincipal.deserialize(this, true),
+ };
+
+ this.subscribeOnChangedListenerInParent(addonId);
+ return this.backToChild("setupStorageInParent", result);
+ },
+
+ onDisconnected() {
+ for (const [addonId, listener] of this.onChangedParentListeners) {
+ ExtensionStorageIDB.removeOnChangedListener(addonId, listener);
+ }
+ this.onChangedParentListeners.clear();
+ },
+
+ // Runs in the main process. This determines what code to execute based on the message
+ // received from the child process.
+ async handleChildRequest(msg) {
+ switch (msg.json.method) {
+ case "setupStorageInParent":
+ const addonId = msg.data.args[0];
+ const result = await extensionStorageHelpers.setupStorageInParent(
+ addonId
+ );
+ return result;
+ default:
+ console.error("ERR_DIRECTOR_PARENT_UNKNOWN_METHOD", msg.json.method);
+ throw new Error("ERR_DIRECTOR_PARENT_UNKNOWN_METHOD");
+ }
+ },
+
+ // Runs in the child process. This determines what code to execute based on the message
+ // received from the parent process.
+ handleParentRequest(msg) {
+ switch (msg.json.method) {
+ case "backToChild": {
+ const [func, rv] = msg.json.args;
+ const resolve = this.unresolvedPromises.get(func);
+ if (resolve) {
+ this.unresolvedPromises.delete(func);
+ resolve(rv);
+ }
+ break;
+ }
+ case "storageOnChanged": {
+ const { addonId, changes } = msg.data;
+ for (const listener of this.onChangedChildListeners) {
+ try {
+ listener({ addonId, changes });
+ } catch (err) {
+ console.error(err);
+ // Ignore errors raised from listeners.
+ }
+ }
+ break;
+ }
+ default:
+ console.error("ERR_DIRECTOR_CLIENT_UNKNOWN_METHOD", msg.json.method);
+ throw new Error("ERR_DIRECTOR_CLIENT_UNKNOWN_METHOD");
+ }
+ },
+
+ callParentProcessAsync(methodName, ...args) {
+ const promise = new Promise(resolve => {
+ this.unresolvedPromises.set(methodName, resolve);
+ });
+
+ this.ppmm.sendAsyncMessage(
+ "debug:storage-extensionStorage-request-parent",
+ {
+ method: methodName,
+ args: args,
+ }
+ );
+
+ return promise;
+ },
+};
+
+/**
+ * E10S parent/child setup helpers
+ * Add a message listener in the parent process to receive messages from the child
+ * process.
+ */
+exports.setupParentProcessForExtensionStorage = function({ mm, prefix }) {
+ // listen for director-script requests from the child process
+ mm.addMessageListener(
+ "debug:storage-extensionStorage-request-parent",
+ extensionStorageHelpers.handleChildRequest
+ );
+
+ return {
+ onDisconnected: () => {
+ // Although "disconnected-from-child" implies that the child is already
+ // disconnected this is not the case. The disconnection takes place after
+ // this method has finished. This gives us chance to clean up items within
+ // the parent process e.g. observers.
+ mm.removeMessageListener(
+ "debug:storage-extensionStorage-request-parent",
+ extensionStorageHelpers.handleChildRequest
+ );
+ extensionStorageHelpers.onDisconnected();
+ },
+ };
+};
+
+/**
+ * The Extension Storage actor.
+ */
+if (Services.prefs.getBoolPref(EXTENSION_STORAGE_ENABLED_PREF, false)) {
+ StorageActors.createActor(
+ {
+ typeName: "extensionStorage",
+ },
+ {
+ initialize(storageActor) {
+ protocol.Actor.prototype.initialize.call(this, null);
+
+ this.storageActor = storageActor;
+
+ this.addonId = this.storageActor.parentActor.addonId;
+
+ // Retrieve the base moz-extension url for the extension
+ // (and also remove the final '/' from it).
+ this.extensionHostURL = this.getExtensionPolicy()
+ .getURL()
+ .slice(0, -1);
+
+ // Map<host, ExtensionStorageIDB db connection>
+ // Bug 1542038, 1542039: Each storage area will need its own
+ // dbConnectionForHost, as they each have different storage backends.
+ // Anywhere dbConnectionForHost is used, we need to know the storage
+ // area to access the correct database.
+ this.dbConnectionForHost = new Map();
+
+ // Bug 1542038, 1542039: Each storage area will need its own
+ // this.hostVsStores or this actor will need to deviate from how
+ // this.hostVsStores is defined in the framework to associate each
+ // storage item with a storage area. Any methods that use it will also
+ // need to be updated (e.g. getNamesForHost).
+ this.hostVsStores = new Map();
+
+ this.onStorageChange = this.onStorageChange.bind(this);
+
+ this.setupChildProcess();
+
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.onWindowDestroyed = this.onWindowDestroyed.bind(this);
+ this.storageActor.on("window-ready", this.onWindowReady);
+ this.storageActor.on("window-destroyed", this.onWindowDestroyed);
+ },
+
+ getExtensionPolicy() {
+ return WebExtensionPolicy.getByID(this.addonId);
+ },
+
+ destroy() {
+ extensionStorageHelpers.onChangedChildListeners.delete(
+ this.onStorageChange
+ );
+
+ this.storageActor.off("window-ready", this.onWindowReady);
+ this.storageActor.off("window-destroyed", this.onWindowDestroyed);
+
+ this.hostVsStores.clear();
+ protocol.Actor.prototype.destroy.call(this);
+
+ this.storageActor = null;
+ },
+
+ setupChildProcess() {
+ const ppmm = this.conn.parentMessageManager;
+ extensionStorageHelpers.setPpmm(ppmm);
+
+ // eslint-disable-next-line no-restricted-properties
+ this.conn.setupInParent({
+ module: "devtools/server/actors/storage",
+ setupParent: "setupParentProcessForExtensionStorage",
+ });
+
+ extensionStorageHelpers.onChangedChildListeners.add(
+ this.onStorageChange
+ );
+ this.setupStorageInParent = extensionStorageHelpers.callParentProcessAsync.bind(
+ extensionStorageHelpers,
+ "setupStorageInParent"
+ );
+
+ // Add a message listener in the child process to receive messages from the parent
+ // process
+ ppmm.addMessageListener(
+ "debug:storage-extensionStorage-request-child",
+ extensionStorageHelpers.handleParentRequest.bind(
+ extensionStorageHelpers
+ )
+ );
+ },
+
+ /**
+ * This fires when the extension changes storage data while the storage
+ * inspector is open. Ensures this.hostVsStores stays up-to-date and
+ * passes the changes on to update the client.
+ */
+ onStorageChange({ addonId, changes }) {
+ if (addonId !== this.addonId) {
+ return;
+ }
+
+ const host = this.extensionHostURL;
+ const storeMap = this.hostVsStores.get(host);
+
+ function isStructuredCloneHolder(value) {
+ return (
+ value &&
+ typeof value === "object" &&
+ Cu.getClassName(value, true) === "StructuredCloneHolder"
+ );
+ }
+
+ for (const key in changes) {
+ const storageChange = changes[key];
+ let { newValue, oldValue } = storageChange;
+ if (isStructuredCloneHolder(newValue)) {
+ newValue = newValue.deserialize(this);
+ }
+ if (isStructuredCloneHolder(oldValue)) {
+ oldValue = oldValue.deserialize(this);
+ }
+
+ let action;
+ if (typeof newValue === "undefined") {
+ action = "deleted";
+ storeMap.delete(key);
+ } else if (typeof oldValue === "undefined") {
+ action = "added";
+ storeMap.set(key, newValue);
+ } else {
+ action = "changed";
+ storeMap.set(key, newValue);
+ }
+
+ this.storageActor.update(action, this.typeName, { [host]: [key] });
+ }
+ },
+
+ /**
+ * Purpose of this method is same as populateStoresForHosts but this is async.
+ * This exact same operation cannot be performed in populateStoresForHosts
+ * method, as that method is called in initialize method of the actor, which
+ * cannot be asynchronous.
+ */
+ async preListStores() {
+ // Ensure the actor's target is an extension and it is enabled
+ if (!this.addonId || !WebExtensionPolicy.getByID(this.addonId)) {
+ return;
+ }
+
+ await this.populateStoresForHost(this.extensionHostURL);
+ },
+
+ /**
+ * This method is overriden and left blank as for extensionStorage, this operation
+ * cannot be performed synchronously. Thus, the preListStores method exists to
+ * do the same task asynchronously.
+ */
+ populateStoresForHosts() {},
+
+ /**
+ * This method asynchronously reads the storage data for the target extension
+ * and caches this data into this.hostVsStores.
+ * @param {String} host - the hostname for the extension
+ */
+ async populateStoresForHost(host) {
+ if (host !== this.extensionHostURL) {
+ return;
+ }
+
+ const extension = ExtensionProcessScript.getExtensionChild(
+ this.addonId
+ );
+ if (!extension || !extension.hasPermission("storage")) {
+ return;
+ }
+
+ // Make sure storeMap is defined and set in this.hostVsStores before subscribing
+ // a storage onChanged listener in the parent process
+ const storeMap = new Map();
+ this.hostVsStores.set(host, storeMap);
+
+ const storagePrincipal = await this.getStoragePrincipal(extension.id);
+
+ if (!storagePrincipal) {
+ // This could happen if the extension fails to be migrated to the
+ // IndexedDB backend
+ return;
+ }
+
+ const db = await ExtensionStorageIDB.open(storagePrincipal);
+ this.dbConnectionForHost.set(host, db);
+ const data = await db.get();
+
+ for (const [key, value] of Object.entries(data)) {
+ storeMap.set(key, value);
+ }
+
+ if (this.storageActor.parentActor.fallbackWindow) {
+ // Show the storage actor in the add-on storage inspector even when there
+ // is no extension page currently open
+ // This strategy may need to change depending on the outcome of Bug 1597900
+ const storageData = {};
+ storageData[host] = this.getNamesForHost(host);
+ this.storageActor.update("added", this.typeName, storageData);
+ }
+ },
+
+ async getStoragePrincipal(addonId) {
+ const {
+ backendEnabled,
+ storagePrincipal,
+ } = await this.setupStorageInParent(addonId);
+
+ if (!backendEnabled) {
+ // IDB backend disabled; give up.
+ return null;
+ }
+ return storagePrincipal;
+ },
+
+ getValuesForHost(host, name) {
+ const result = [];
+
+ if (!this.hostVsStores.has(host)) {
+ return result;
+ }
+
+ if (name) {
+ return [{ name, value: this.hostVsStores.get(host).get(name) }];
+ }
+
+ for (const [key, value] of Array.from(
+ this.hostVsStores.get(host).entries()
+ )) {
+ result.push({ name: key, value });
+ }
+ return result;
+ },
+
+ /**
+ * Converts a storage item to an "extensionobject" as defined in
+ * devtools/shared/specs/storage.js. Behavior largely mirrors the "indexedDB" storage actor,
+ * except where it would throw an unhandled error (i.e. for a `BigInt` or `undefined`
+ * `item.value`).
+ * @param {Object} item - The storage item to convert
+ * @param {String} item.name - The storage item key
+ * @param {*} item.value - The storage item value
+ * @return {extensionobject}
+ */
+ toStoreObject(item) {
+ if (!item) {
+ return null;
+ }
+
+ let { name, value } = item;
+ let isValueEditable = extensionStorageHelpers.isEditable(value);
+
+ // `JSON.stringify()` throws for `BigInt`, adds extra quotes to strings and `Date` strings,
+ // and doesn't modify `undefined`.
+ switch (typeof value) {
+ case "bigint":
+ value = `${value.toString()}n`;
+ break;
+ case "string":
+ break;
+ case "undefined":
+ value = "undefined";
+ break;
+ default:
+ value = JSON.stringify(value);
+ if (
+ // can't use `instanceof` across frame boundaries
+ Object.prototype.toString.call(item.value) === "[object Date]"
+ ) {
+ value = JSON.parse(value);
+ }
+ }
+
+ // FIXME: Bug 1318029 - Due to a bug that is thrown whenever a
+ // LongStringActor string reaches DevToolsServer.LONG_STRING_LENGTH we need
+ // to trim the value. When the bug is fixed we should stop trimming the
+ // string here.
+ const maxLength = DevToolsServer.LONG_STRING_LENGTH - 1;
+ if (value.length > maxLength) {
+ value = value.substr(0, maxLength);
+ isValueEditable = false;
+ }
+
+ return {
+ name,
+ value: new LongStringActor(this.conn, value),
+ area: "local", // Bug 1542038, 1542039: set the correct storage area
+ isValueEditable,
+ };
+ },
+
+ getFields() {
+ return [
+ { name: "name", editable: false },
+ { name: "value", editable: true },
+ { name: "area", editable: false },
+ { name: "isValueEditable", editable: false, private: true },
+ ];
+ },
+
+ onItemUpdated(action, host, names) {
+ this.storageActor.update(action, this.typeName, {
+ [host]: names,
+ });
+ },
+
+ async editItem({ host, field, items, oldValue }) {
+ const db = this.dbConnectionForHost.get(host);
+ if (!db) {
+ return;
+ }
+
+ const { name, value } = items;
+
+ let parsedValue = parseItemValue(value);
+ if (parsedValue === value) {
+ const { typesFromString } = extensionStorageHelpers;
+ for (const { test, parse } of Object.values(typesFromString)) {
+ if (test(value)) {
+ parsedValue = parse(value);
+ break;
+ }
+ }
+ }
+ const changes = await db.set({ [name]: parsedValue });
+ this.fireOnChangedExtensionEvent(host, changes);
+
+ this.onItemUpdated("changed", host, [name]);
+ },
+
+ async removeItem(host, name) {
+ const db = this.dbConnectionForHost.get(host);
+ if (!db) {
+ return;
+ }
+
+ const changes = await db.remove(name);
+ this.fireOnChangedExtensionEvent(host, changes);
+
+ this.onItemUpdated("deleted", host, [name]);
+ },
+
+ async removeAll(host) {
+ const db = this.dbConnectionForHost.get(host);
+ if (!db) {
+ return;
+ }
+
+ const changes = await db.clear();
+ this.fireOnChangedExtensionEvent(host, changes);
+
+ this.onItemUpdated("cleared", host, []);
+ },
+
+ /**
+ * Let the extension know that storage data has been changed by the user from
+ * the storage inspector.
+ */
+ fireOnChangedExtensionEvent(host, changes) {
+ // Bug 1542038, 1542039: Which message to send depends on the storage area
+ const uuid = new URL(host).host;
+ Services.cpmm.sendAsyncMessage(
+ `Extension:StorageLocalOnChanged:${uuid}`,
+ changes
+ );
+ },
+ }
+ );
+}
+
+StorageActors.createActor(
+ {
+ typeName: "Cache",
+ },
+ {
+ async getCachesForHost(host) {
+ const win = this.storageActor.getWindowFromHost(host);
+ if (!win) {
+ return null;
+ }
+
+ const principal = win.document.effectiveStoragePrincipal;
+
+ // The first argument tells if you want to get |content| cache or |chrome|
+ // cache.
+ // The |content| cache is the cache explicitely named by the web content
+ // (service worker or web page).
+ // The |chrome| cache is the cache implicitely cached by the platform,
+ // hosting the source file of the service worker.
+ const { CacheStorage } = win;
+
+ if (!CacheStorage) {
+ return null;
+ }
+
+ const cache = new CacheStorage("content", principal);
+ return cache;
+ },
+
+ async preListStores() {
+ for (const host of this.hosts) {
+ await this.populateStoresForHost(host);
+ }
+ },
+
+ form() {
+ const hosts = {};
+ for (const host of this.hosts) {
+ hosts[host] = this.getNamesForHost(host);
+ }
+
+ return {
+ actor: this.actorID,
+ hosts: hosts,
+ traits: this._getTraits(),
+ };
+ },
+
+ getNamesForHost(host) {
+ // UI code expect each name to be a JSON string of an array :/
+ return [...this.hostVsStores.get(host).keys()].map(a => {
+ return JSON.stringify([a]);
+ });
+ },
+
+ async getValuesForHost(host, name) {
+ if (!name) {
+ return [];
+ }
+ // UI is weird and expect a JSON stringified array... and pass it back :/
+ name = JSON.parse(name)[0];
+
+ const cache = this.hostVsStores.get(host).get(name);
+ const requests = await cache.keys();
+ const results = [];
+ for (const request of requests) {
+ let response = await cache.match(request);
+ // Unwrap the response to get access to all its properties if the
+ // response happen to be 'opaque', when it is a Cross Origin Request.
+ response = response.cloneUnfiltered();
+ results.push(await this.processEntry(request, response));
+ }
+ return results;
+ },
+
+ async processEntry(request, response) {
+ return {
+ url: String(request.url),
+ status: String(response.statusText),
+ };
+ },
+
+ async getFields() {
+ return [
+ { name: "url", editable: false },
+ { name: "status", editable: false },
+ ];
+ },
+
+ async populateStoresForHost(host) {
+ const storeMap = new Map();
+ const caches = await this.getCachesForHost(host);
+ try {
+ for (const name of await caches.keys()) {
+ storeMap.set(name, await caches.open(name));
+ }
+ } catch (ex) {
+ console.warn(
+ `Failed to enumerate CacheStorage for host ${host}: ${ex}`
+ );
+ }
+ this.hostVsStores.set(host, storeMap);
+ },
+
+ /**
+ * This method is overriden and left blank as for Cache Storage, this
+ * operation cannot be performed synchronously. Thus, the preListStores
+ * method exists to do the same task asynchronously.
+ */
+ populateStoresForHosts() {
+ this.hostVsStores = new Map();
+ },
+
+ /**
+ * Given a url, correctly determine its protocol + hostname part.
+ */
+ getSchemaAndHost(url) {
+ const uri = Services.io.newURI(url);
+ return uri.scheme + "://" + uri.hostPort;
+ },
+
+ toStoreObject(item) {
+ return item;
+ },
+
+ async removeItem(host, name) {
+ const cacheMap = this.hostVsStores.get(host);
+ if (!cacheMap) {
+ return;
+ }
+
+ const parsedName = JSON.parse(name);
+
+ if (parsedName.length == 1) {
+ // Delete the whole Cache object
+ const [cacheName] = parsedName;
+ cacheMap.delete(cacheName);
+ const cacheStorage = await this.getCachesForHost(host);
+ await cacheStorage.delete(cacheName);
+ this.onItemUpdated("deleted", host, [cacheName]);
+ } else if (parsedName.length == 2) {
+ // Delete one cached request
+ const [cacheName, url] = parsedName;
+ const cache = cacheMap.get(cacheName);
+ if (cache) {
+ await cache.delete(url);
+ this.onItemUpdated("deleted", host, [cacheName, url]);
+ }
+ }
+ },
+
+ async removeAll(host, name) {
+ const cacheMap = this.hostVsStores.get(host);
+ if (!cacheMap) {
+ return;
+ }
+
+ const parsedName = JSON.parse(name);
+
+ // Only a Cache object is a valid object to clear
+ if (parsedName.length == 1) {
+ const [cacheName] = parsedName;
+ const cache = cacheMap.get(cacheName);
+ if (cache) {
+ const keys = await cache.keys();
+ await Promise.all(keys.map(key => cache.delete(key)));
+ this.onItemUpdated("cleared", host, [cacheName]);
+ }
+ }
+ },
+
+ /**
+ * CacheStorage API doesn't support any notifications, we must fake them
+ */
+ onItemUpdated(action, host, path) {
+ this.storageActor.update(action, "Cache", {
+ [host]: [JSON.stringify(path)],
+ });
+ },
+ }
+);
+
+/**
+ * Code related to the Indexed DB actor and front
+ */
+
+// Metadata holder objects for various components of Indexed DB
+
+/**
+ * Meta data object for a particular index in an object store
+ *
+ * @param {IDBIndex} index
+ * The particular index from the object store.
+ */
+function IndexMetadata(index) {
+ this._name = index.name;
+ this._keyPath = index.keyPath;
+ this._unique = index.unique;
+ this._multiEntry = index.multiEntry;
+}
+IndexMetadata.prototype = {
+ toObject() {
+ return {
+ name: this._name,
+ keyPath: this._keyPath,
+ unique: this._unique,
+ multiEntry: this._multiEntry,
+ };
+ },
+};
+
+/**
+ * Meta data object for a particular object store in a db
+ *
+ * @param {IDBObjectStore} objectStore
+ * The particular object store from the db.
+ */
+function ObjectStoreMetadata(objectStore) {
+ this._name = objectStore.name;
+ this._keyPath = objectStore.keyPath;
+ this._autoIncrement = objectStore.autoIncrement;
+ this._indexes = [];
+
+ for (let i = 0; i < objectStore.indexNames.length; i++) {
+ const index = objectStore.index(objectStore.indexNames[i]);
+
+ const newIndex = {
+ keypath: index.keyPath,
+ multiEntry: index.multiEntry,
+ name: index.name,
+ objectStore: {
+ autoIncrement: index.objectStore.autoIncrement,
+ indexNames: [...index.objectStore.indexNames],
+ keyPath: index.objectStore.keyPath,
+ name: index.objectStore.name,
+ },
+ };
+
+ this._indexes.push([newIndex, new IndexMetadata(index)]);
+ }
+}
+ObjectStoreMetadata.prototype = {
+ toObject() {
+ return {
+ name: this._name,
+ keyPath: this._keyPath,
+ autoIncrement: this._autoIncrement,
+ indexes: JSON.stringify(
+ [...this._indexes.values()].map(index => index.toObject())
+ ),
+ };
+ },
+};
+
+/**
+ * Meta data object for a particular indexed db in a host.
+ *
+ * @param {string} origin
+ * The host associated with this indexed db.
+ * @param {IDBDatabase} db
+ * The particular indexed db.
+ * @param {String} storage
+ * Storage type, either "temporary", "default" or "persistent".
+ */
+function DatabaseMetadata(origin, db, storage) {
+ this._origin = origin;
+ this._name = db.name;
+ this._version = db.version;
+ this._objectStores = [];
+ this.storage = storage;
+
+ if (db.objectStoreNames.length) {
+ const transaction = db.transaction(db.objectStoreNames, "readonly");
+
+ for (let i = 0; i < transaction.objectStoreNames.length; i++) {
+ const objectStore = transaction.objectStore(
+ transaction.objectStoreNames[i]
+ );
+ this._objectStores.push([
+ transaction.objectStoreNames[i],
+ new ObjectStoreMetadata(objectStore),
+ ]);
+ }
+ }
+}
+DatabaseMetadata.prototype = {
+ get objectStores() {
+ return this._objectStores;
+ },
+
+ toObject() {
+ return {
+ uniqueKey: `${this._name}${SEPARATOR_GUID}${this.storage}`,
+ name: this._name,
+ storage: this.storage,
+ origin: this._origin,
+ version: this._version,
+ objectStores: this._objectStores.size,
+ };
+ },
+};
+
+StorageActors.createActor(
+ {
+ typeName: "indexedDB",
+ },
+ {
+ initialize(storageActor) {
+ protocol.Actor.prototype.initialize.call(this, null);
+
+ this.storageActor = storageActor;
+
+ this.maybeSetupChildProcess();
+
+ this.objectsSize = {};
+ this.storageActor = storageActor;
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.onWindowDestroyed = this.onWindowDestroyed.bind(this);
+
+ this.storageActor.on("window-ready", this.onWindowReady);
+ this.storageActor.on("window-destroyed", this.onWindowDestroyed);
+ },
+
+ destroy() {
+ this.hostVsStores.clear();
+ this.objectsSize = null;
+
+ this.storageActor.off("window-ready", this.onWindowReady);
+ this.storageActor.off("window-destroyed", this.onWindowDestroyed);
+
+ protocol.Actor.prototype.destroy.call(this);
+
+ this.storageActor = null;
+ },
+
+ /**
+ * Returns a list of currently known hosts for the target window. This list
+ * contains unique hosts from the window, all inner windows and all permanent
+ * indexedDB hosts defined inside the browser.
+ */
+ async getHosts() {
+ // Add internal hosts to this._internalHosts, which will be picked up by
+ // the this.hosts getter. Because this.hosts is a property on the default
+ // storage actor and inherited by all storage actors we have to do it this
+ // way.
+ // Only look up internal hosts if we are in the browser toolbox
+ const isBrowserToolbox = this.storageActor.parentActor.isRootActor;
+
+ this._internalHosts = isBrowserToolbox
+ ? await this.getInternalHosts()
+ : [];
+
+ return this.hosts;
+ },
+
+ /**
+ * Remove an indexedDB database from given host with a given name.
+ */
+ async removeDatabase(host, name) {
+ const win = this.storageActor.getWindowFromHost(host);
+ if (!win) {
+ return { error: `Window for host ${host} not found` };
+ }
+
+ const principal = win.document.effectiveStoragePrincipal;
+ return this.removeDB(host, principal, name);
+ },
+
+ async removeAll(host, name) {
+ const [db, store] = JSON.parse(name);
+
+ const win = this.storageActor.getWindowFromHost(host);
+ if (!win) {
+ return;
+ }
+
+ const principal = win.document.effectiveStoragePrincipal;
+ this.clearDBStore(host, principal, db, store);
+ },
+
+ async removeItem(host, name) {
+ const [db, store, id] = JSON.parse(name);
+
+ const win = this.storageActor.getWindowFromHost(host);
+ if (!win) {
+ return;
+ }
+
+ const principal = win.document.effectiveStoragePrincipal;
+ this.removeDBRecord(host, principal, db, store, id);
+ },
+
+ /**
+ * This method is overriden and left blank as for indexedDB, this operation
+ * cannot be performed synchronously. Thus, the preListStores method exists to
+ * do the same task asynchronously.
+ */
+ populateStoresForHosts() {},
+
+ getNamesForHost(host) {
+ const names = [];
+
+ for (const [dbName, { objectStores }] of this.hostVsStores.get(host)) {
+ if (objectStores.size) {
+ for (const objectStore of objectStores.keys()) {
+ names.push(JSON.stringify([dbName, objectStore]));
+ }
+ } else {
+ names.push(JSON.stringify([dbName]));
+ }
+ }
+ return names;
+ },
+
+ /**
+ * Returns the total number of entries for various types of requests to
+ * getStoreObjects for Indexed DB actor.
+ *
+ * @param {string} host
+ * The host for the request.
+ * @param {array:string} names
+ * Array of stringified name objects for indexed db actor.
+ * The request type depends on the length of any parsed entry from this
+ * array. 0 length refers to request for the whole host. 1 length
+ * refers to request for a particular db in the host. 2 length refers
+ * to a particular object store in a db in a host. 3 length refers to
+ * particular items of an object store in a db in a host.
+ * @param {object} options
+ * An options object containing following properties:
+ * - index {string} The IDBIndex for the object store in the db.
+ */
+ getObjectsSize(host, names, options) {
+ // In Indexed DB, we are interested in only the first name, as the pattern
+ // should follow in all entries.
+ const name = names[0];
+ const parsedName = JSON.parse(name);
+
+ if (parsedName.length == 3) {
+ // This is the case where specific entries from an object store were
+ // requested
+ return names.length;
+ } else if (parsedName.length == 2) {
+ // This is the case where all entries from an object store are requested.
+ const index = options.index;
+ const [db, objectStore] = parsedName;
+ if (this.objectsSize[host + db + objectStore + index]) {
+ return this.objectsSize[host + db + objectStore + index];
+ }
+ } else if (parsedName.length == 1) {
+ // This is the case where details of all object stores in a db are
+ // requested.
+ if (
+ this.hostVsStores.has(host) &&
+ this.hostVsStores.get(host).has(parsedName[0])
+ ) {
+ return this.hostVsStores.get(host).get(parsedName[0]).objectStores
+ .size;
+ }
+ } else if (!parsedName || !parsedName.length) {
+ // This is the case were details of all dbs in a host are requested.
+ if (this.hostVsStores.has(host)) {
+ return this.hostVsStores.get(host).size;
+ }
+ }
+ return 0;
+ },
+
+ /**
+ * Purpose of this method is same as populateStoresForHosts but this is async.
+ * This exact same operation cannot be performed in populateStoresForHosts
+ * method, as that method is called in initialize method of the actor, which
+ * cannot be asynchronous.
+ */
+ async preListStores() {
+ this.hostVsStores = new Map();
+
+ for (const host of await this.getHosts()) {
+ await this.populateStoresForHost(host);
+ }
+ },
+
+ async populateStoresForHost(host) {
+ const storeMap = new Map();
+
+ const win = this.storageActor.getWindowFromHost(host);
+ const principal = this.getPrincipal(win);
+
+ const { names } = await this.getDBNamesForHost(host, principal);
+
+ for (const { name, storage } of names) {
+ let metadata = await this.getDBMetaData(host, principal, name, storage);
+
+ metadata = indexedDBHelpers.patchMetadataMapsAndProtos(metadata);
+
+ storeMap.set(`${name} (${storage})`, metadata);
+ }
+
+ this.hostVsStores.set(host, storeMap);
+ },
+
+ /**
+ * Returns the over-the-wire implementation of the indexed db entity.
+ */
+ toStoreObject(item) {
+ if (!item) {
+ return null;
+ }
+
+ if ("indexes" in item) {
+ // Object store meta data
+ return {
+ objectStore: item.name,
+ keyPath: item.keyPath,
+ autoIncrement: item.autoIncrement,
+ indexes: item.indexes,
+ };
+ }
+ if ("objectStores" in item) {
+ // DB meta data
+ return {
+ uniqueKey: `${item.name} (${item.storage})`,
+ db: item.name,
+ storage: item.storage,
+ origin: item.origin,
+ version: item.version,
+ objectStores: item.objectStores,
+ };
+ }
+
+ let value = JSON.stringify(item.value);
+
+ // FIXME: Bug 1318029 - Due to a bug that is thrown whenever a
+ // LongStringActor string reaches DevToolsServer.LONG_STRING_LENGTH we need
+ // to trim the value. When the bug is fixed we should stop trimming the
+ // string here.
+ const maxLength = DevToolsServer.LONG_STRING_LENGTH - 1;
+ if (value.length > maxLength) {
+ value = value.substr(0, maxLength);
+ }
+
+ // Indexed db entry
+ return {
+ name: item.name,
+ value: new LongStringActor(this.conn, value),
+ };
+ },
+
+ form() {
+ const hosts = {};
+ for (const host of this.hosts) {
+ hosts[host] = this.getNamesForHost(host);
+ }
+
+ return {
+ actor: this.actorID,
+ hosts: hosts,
+ traits: this._getTraits(),
+ };
+ },
+
+ onItemUpdated(action, host, path) {
+ // Database was removed, remove it from stores map
+ if (action === "deleted" && path.length === 1) {
+ if (this.hostVsStores.has(host)) {
+ this.hostVsStores.get(host).delete(path[0]);
+ }
+ }
+
+ this.storageActor.update(action, "indexedDB", {
+ [host]: [JSON.stringify(path)],
+ });
+ },
+
+ maybeSetupChildProcess() {
+ if (!DevToolsServer.isInChildProcess) {
+ this.backToChild = (func, rv) => rv;
+ this.clearDBStore = indexedDBHelpers.clearDBStore;
+ this.findIDBPathsForHost = indexedDBHelpers.findIDBPathsForHost;
+ this.findSqlitePathsForHost = indexedDBHelpers.findSqlitePathsForHost;
+ this.findStorageTypePaths = indexedDBHelpers.findStorageTypePaths;
+ this.getDBMetaData = indexedDBHelpers.getDBMetaData;
+ this.getDBNamesForHost = indexedDBHelpers.getDBNamesForHost;
+ this.getNameFromDatabaseFile = indexedDBHelpers.getNameFromDatabaseFile;
+ this.getObjectStoreData = indexedDBHelpers.getObjectStoreData;
+ this.getSanitizedHost = indexedDBHelpers.getSanitizedHost;
+ this.getValuesForHost = indexedDBHelpers.getValuesForHost;
+ this.openWithPrincipal = indexedDBHelpers.openWithPrincipal;
+ this.removeDB = indexedDBHelpers.removeDB;
+ this.removeDBRecord = indexedDBHelpers.removeDBRecord;
+ this.splitNameAndStorage = indexedDBHelpers.splitNameAndStorage;
+ this.getInternalHosts = indexedDBHelpers.getInternalHosts;
+ return;
+ }
+
+ const mm = this.conn.parentMessageManager;
+
+ // eslint-disable-next-line no-restricted-properties
+ this.conn.setupInParent({
+ module: "devtools/server/actors/storage",
+ setupParent: "setupParentProcessForIndexedDB",
+ });
+
+ this.getDBMetaData = callParentProcessAsync.bind(null, "getDBMetaData");
+ this.splitNameAndStorage = callParentProcessAsync.bind(
+ null,
+ "splitNameAndStorage"
+ );
+ this.getInternalHosts = callParentProcessAsync.bind(
+ null,
+ "getInternalHosts"
+ );
+ this.getDBNamesForHost = callParentProcessAsync.bind(
+ null,
+ "getDBNamesForHost"
+ );
+ this.getValuesForHost = callParentProcessAsync.bind(
+ null,
+ "getValuesForHost"
+ );
+ this.removeDB = callParentProcessAsync.bind(null, "removeDB");
+ this.removeDBRecord = callParentProcessAsync.bind(null, "removeDBRecord");
+ this.clearDBStore = callParentProcessAsync.bind(null, "clearDBStore");
+
+ mm.addMessageListener("debug:storage-indexedDB-request-child", msg => {
+ switch (msg.json.method) {
+ case "backToChild": {
+ const [func, rv] = msg.json.args;
+ const resolve = unresolvedPromises.get(func);
+ if (resolve) {
+ unresolvedPromises.delete(func);
+ resolve(rv);
+ }
+ break;
+ }
+ case "onItemUpdated": {
+ const [action, host, path] = msg.json.args;
+ this.onItemUpdated(action, host, path);
+ }
+ }
+ });
+
+ const unresolvedPromises = new Map();
+ function callParentProcessAsync(methodName, ...args) {
+ const promise = new Promise(resolve => {
+ unresolvedPromises.set(methodName, resolve);
+ });
+
+ mm.sendAsyncMessage("debug:storage-indexedDB-request-parent", {
+ method: methodName,
+ args: args,
+ });
+
+ return promise;
+ }
+ },
+
+ async getFields(subType) {
+ switch (subType) {
+ // Detail of database
+ case "database":
+ return [
+ { name: "objectStore", editable: false },
+ { name: "keyPath", editable: false },
+ { name: "autoIncrement", editable: false },
+ { name: "indexes", editable: false },
+ ];
+
+ // Detail of object store
+ case "object store":
+ return [
+ { name: "name", editable: false },
+ { name: "value", editable: false },
+ ];
+
+ // Detail of indexedDB for one origin
+ default:
+ return [
+ { name: "uniqueKey", editable: false, private: true },
+ { name: "db", editable: false },
+ { name: "storage", editable: false },
+ { name: "origin", editable: false },
+ { name: "version", editable: false },
+ { name: "objectStores", editable: false },
+ ];
+ }
+ },
+ }
+);
+
+var indexedDBHelpers = {
+ backToChild(...args) {
+ Services.mm.broadcastAsyncMessage("debug:storage-indexedDB-request-child", {
+ method: "backToChild",
+ args: args,
+ });
+ },
+
+ onItemUpdated(action, host, path) {
+ Services.mm.broadcastAsyncMessage("debug:storage-indexedDB-request-child", {
+ method: "onItemUpdated",
+ args: [action, host, path],
+ });
+ },
+
+ /**
+ * Fetches and stores all the metadata information for the given database
+ * `name` for the given `host` with its `principal`. The stored metadata
+ * information is of `DatabaseMetadata` type.
+ */
+ async getDBMetaData(host, principal, name, storage) {
+ const request = this.openWithPrincipal(principal, name, storage);
+ return new Promise(resolve => {
+ request.onsuccess = event => {
+ const db = event.target.result;
+ const dbData = new DatabaseMetadata(host, db, storage);
+ db.close();
+
+ resolve(this.backToChild("getDBMetaData", dbData));
+ };
+ request.onerror = ({ target }) => {
+ console.error(
+ `Error opening indexeddb database ${name} for host ${host}`,
+ target.error
+ );
+ resolve(this.backToChild("getDBMetaData", null));
+ };
+ });
+ },
+
+ splitNameAndStorage: function(name) {
+ const lastOpenBracketIndex = name.lastIndexOf("(");
+ const lastCloseBracketIndex = name.lastIndexOf(")");
+ const delta = lastCloseBracketIndex - lastOpenBracketIndex - 1;
+
+ const storage = name.substr(lastOpenBracketIndex + 1, delta);
+
+ name = name.substr(0, lastOpenBracketIndex - 1);
+
+ return { storage, name };
+ },
+
+ /**
+ * Get all "internal" hosts. Internal hosts are database namespaces used by
+ * the browser.
+ */
+ async getInternalHosts() {
+ const profileDir = OS.Constants.Path.profileDir;
+ const storagePath = OS.Path.join(profileDir, "storage", "permanent");
+ const iterator = new OS.File.DirectoryIterator(storagePath);
+ const hosts = [];
+
+ await iterator.forEach(entry => {
+ if (entry.isDir && !SAFE_HOSTS_PREFIXES_REGEX.test(entry.name)) {
+ hosts.push(entry.name);
+ }
+ });
+ iterator.close();
+
+ return this.backToChild("getInternalHosts", hosts);
+ },
+
+ /**
+ * Opens an indexed db connection for the given `principal` and
+ * database `name`.
+ */
+ openWithPrincipal: function(principal, name, storage) {
+ return indexedDBForStorage.openForPrincipal(principal, name, {
+ storage: storage,
+ });
+ },
+
+ async removeDB(host, principal, dbName) {
+ const result = new Promise(resolve => {
+ const { name, storage } = this.splitNameAndStorage(dbName);
+ const request = indexedDBForStorage.deleteForPrincipal(principal, name, {
+ storage: storage,
+ });
+
+ request.onsuccess = () => {
+ resolve({});
+ this.onItemUpdated("deleted", host, [dbName]);
+ };
+
+ request.onblocked = () => {
+ console.warn(
+ `Deleting indexedDB database ${name} for host ${host} is blocked`
+ );
+ resolve({ blocked: true });
+ };
+
+ request.onerror = () => {
+ const { error } = request;
+ console.warn(
+ `Error deleting indexedDB database ${name} for host ${host}: ${error}`
+ );
+ resolve({ error: error.message });
+ };
+
+ // If the database is blocked repeatedly, the onblocked event will not
+ // be fired again. To avoid waiting forever, report as blocked if nothing
+ // else happens after 3 seconds.
+ setTimeout(() => resolve({ blocked: true }), 3000);
+ });
+
+ return this.backToChild("removeDB", await result);
+ },
+
+ async removeDBRecord(host, principal, dbName, storeName, id) {
+ let db;
+ const { name, storage } = this.splitNameAndStorage(dbName);
+
+ try {
+ db = await new Promise((resolve, reject) => {
+ const request = this.openWithPrincipal(principal, name, storage);
+ request.onsuccess = ev => resolve(ev.target.result);
+ request.onerror = ev => reject(ev.target.error);
+ });
+
+ const transaction = db.transaction(storeName, "readwrite");
+ const store = transaction.objectStore(storeName);
+
+ await new Promise((resolve, reject) => {
+ const request = store.delete(id);
+ request.onsuccess = () => resolve();
+ request.onerror = ev => reject(ev.target.error);
+ });
+
+ this.onItemUpdated("deleted", host, [dbName, storeName, id]);
+ } catch (error) {
+ const recordPath = [dbName, storeName, id].join("/");
+ console.error(
+ `Failed to delete indexedDB record: ${recordPath}: ${error}`
+ );
+ }
+
+ if (db) {
+ db.close();
+ }
+
+ return this.backToChild("removeDBRecord", null);
+ },
+
+ async clearDBStore(host, principal, dbName, storeName) {
+ let db;
+ const { name, storage } = this.splitNameAndStorage(dbName);
+
+ try {
+ db = await new Promise((resolve, reject) => {
+ const request = this.openWithPrincipal(principal, name, storage);
+ request.onsuccess = ev => resolve(ev.target.result);
+ request.onerror = ev => reject(ev.target.error);
+ });
+
+ const transaction = db.transaction(storeName, "readwrite");
+ const store = transaction.objectStore(storeName);
+
+ await new Promise((resolve, reject) => {
+ const request = store.clear();
+ request.onsuccess = () => resolve();
+ request.onerror = ev => reject(ev.target.error);
+ });
+
+ this.onItemUpdated("cleared", host, [dbName, storeName]);
+ } catch (error) {
+ const storePath = [dbName, storeName].join("/");
+ console.error(`Failed to clear indexedDB store: ${storePath}: ${error}`);
+ }
+
+ if (db) {
+ db.close();
+ }
+
+ return this.backToChild("clearDBStore", null);
+ },
+
+ /**
+ * Fetches all the databases and their metadata for the given `host`.
+ */
+ async getDBNamesForHost(host, principal) {
+ const sanitizedHost = this.getSanitizedHost(host) + principal.originSuffix;
+ const profileDir = OS.Constants.Path.profileDir;
+ const files = [];
+ const names = [];
+ const storagePath = OS.Path.join(profileDir, "storage");
+
+ // We expect sqlite DB paths to look something like this:
+ // - PathToProfileDir/storage/default/http+++www.example.com/
+ // idb/1556056096MeysDaabta.sqlite
+ // - PathToProfileDir/storage/permanent/http+++www.example.com/
+ // idb/1556056096MeysDaabta.sqlite
+ // - PathToProfileDir/storage/temporary/http+++www.example.com/
+ // idb/1556056096MeysDaabta.sqlite
+ // The subdirectory inside the storage folder is determined by the storage
+ // type:
+ // - default: { storage: "default" } or not specified.
+ // - permanent: { storage: "persistent" }.
+ // - temporary: { storage: "temporary" }.
+ const sqliteFiles = await this.findSqlitePathsForHost(
+ storagePath,
+ sanitizedHost
+ );
+
+ for (const file of sqliteFiles) {
+ const splitPath = OS.Path.split(file).components;
+ const idbIndex = splitPath.indexOf("idb");
+ const storage = splitPath[idbIndex - 2];
+ const relative = file.substr(profileDir.length + 1);
+
+ files.push({
+ file: relative,
+ storage: storage === "permanent" ? "persistent" : storage,
+ });
+ }
+
+ if (files.length > 0) {
+ for (const { file, storage } of files) {
+ const name = await this.getNameFromDatabaseFile(file);
+ if (name) {
+ names.push({
+ name,
+ storage,
+ });
+ }
+ }
+ }
+
+ return this.backToChild("getDBNamesForHost", { names });
+ },
+
+ /**
+ * Find all SQLite files that hold IndexedDB data for a host, such as:
+ * storage/temporary/http+++www.example.com/idb/1556056096MeysDaabta.sqlite
+ */
+ async findSqlitePathsForHost(storagePath, sanitizedHost) {
+ const sqlitePaths = [];
+ const idbPaths = await this.findIDBPathsForHost(storagePath, sanitizedHost);
+ for (const idbPath of idbPaths) {
+ const iterator = new OS.File.DirectoryIterator(idbPath);
+ await iterator.forEach(entry => {
+ if (!entry.isDir && entry.path.endsWith(".sqlite")) {
+ sqlitePaths.push(entry.path);
+ }
+ });
+ iterator.close();
+ }
+ return sqlitePaths;
+ },
+
+ /**
+ * Find all paths that hold IndexedDB data for a host, such as:
+ * storage/temporary/http+++www.example.com/idb
+ */
+ async findIDBPathsForHost(storagePath, sanitizedHost) {
+ const idbPaths = [];
+ const typePaths = await this.findStorageTypePaths(storagePath);
+ for (const typePath of typePaths) {
+ const idbPath = OS.Path.join(typePath, sanitizedHost, "idb");
+ if (await OS.File.exists(idbPath)) {
+ idbPaths.push(idbPath);
+ }
+ }
+ return idbPaths;
+ },
+
+ /**
+ * Find all the storage types, such as "default", "permanent", or "temporary".
+ * These names have changed over time, so it seems simpler to look through all
+ * types that currently exist in the profile.
+ */
+ async findStorageTypePaths(storagePath) {
+ const iterator = new OS.File.DirectoryIterator(storagePath);
+ const typePaths = [];
+ await iterator.forEach(entry => {
+ if (entry.isDir) {
+ typePaths.push(entry.path);
+ }
+ });
+ iterator.close();
+ return typePaths;
+ },
+
+ /**
+ * Removes any illegal characters from the host name to make it a valid file
+ * name.
+ */
+ getSanitizedHost(host) {
+ if (host.startsWith("about:")) {
+ host = "moz-safe-" + host;
+ }
+ return host.replace(ILLEGAL_CHAR_REGEX, "+");
+ },
+
+ /**
+ * Retrieves the proper indexed db database name from the provided .sqlite
+ * file location.
+ */
+ async getNameFromDatabaseFile(path) {
+ let connection = null;
+ let retryCount = 0;
+
+ // Content pages might be having an open transaction for the same indexed db
+ // which this sqlite file belongs to. In that case, sqlite.openConnection
+ // will throw. Thus we retry for some time to see if lock is removed.
+ while (!connection && retryCount++ < 25) {
+ try {
+ connection = await Sqlite.openConnection({ path: path });
+ } catch (ex) {
+ // Continuously retrying is overkill. Waiting for 100ms before next try
+ await sleep(100);
+ }
+ }
+
+ if (!connection) {
+ return null;
+ }
+
+ const rows = await connection.execute("SELECT name FROM database");
+ if (rows.length != 1) {
+ return null;
+ }
+
+ const name = rows[0].getResultByName("name");
+
+ await connection.close();
+
+ return name;
+ },
+
+ async getValuesForHost(
+ host,
+ name = "null",
+ options,
+ hostVsStores,
+ principal
+ ) {
+ name = JSON.parse(name);
+ if (!name || !name.length) {
+ // This means that details about the db in this particular host are
+ // requested.
+ const dbs = [];
+ if (hostVsStores.has(host)) {
+ for (let [, db] of hostVsStores.get(host)) {
+ db = indexedDBHelpers.patchMetadataMapsAndProtos(db);
+ dbs.push(db.toObject());
+ }
+ }
+ return this.backToChild("getValuesForHost", { dbs: dbs });
+ }
+
+ const [db2, objectStore, id] = name;
+ if (!objectStore) {
+ // This means that details about all the object stores in this db are
+ // requested.
+ const objectStores = [];
+ if (hostVsStores.has(host) && hostVsStores.get(host).has(db2)) {
+ let db = hostVsStores.get(host).get(db2);
+
+ db = indexedDBHelpers.patchMetadataMapsAndProtos(db);
+
+ const objectStores2 = db.objectStores;
+
+ for (const objectStore2 of objectStores2) {
+ objectStores.push(objectStore2[1].toObject());
+ }
+ }
+ return this.backToChild("getValuesForHost", {
+ objectStores: objectStores,
+ });
+ }
+ // Get either all entries from the object store, or a particular id
+ const storage = hostVsStores.get(host).get(db2).storage;
+ const result = await this.getObjectStoreData(
+ host,
+ principal,
+ db2,
+ storage,
+ {
+ objectStore: objectStore,
+ id: id,
+ index: options.index,
+ offset: options.offset,
+ size: options.size,
+ }
+ );
+ return this.backToChild("getValuesForHost", { result: result });
+ },
+
+ /**
+ * Returns requested entries (or at most MAX_STORE_OBJECT_COUNT) from a particular
+ * objectStore from the db in the given host.
+ *
+ * @param {string} host
+ * The given host.
+ * @param {nsIPrincipal} principal
+ * The principal of the given document.
+ * @param {string} dbName
+ * The name of the indexed db from the above host.
+ * @param {String} storage
+ * Storage type, either "temporary", "default" or "persistent".
+ * @param {Object} requestOptions
+ * An object in the following format:
+ * {
+ * objectStore: The name of the object store from the above db,
+ * id: Id of the requested entry from the above object
+ * store. null if all entries from the above object
+ * store are requested,
+ * index: Name of the IDBIndex to be iterated on while fetching
+ * entries. null or "name" if no index is to be
+ * iterated,
+ * offset: offset of the entries to be fetched,
+ * size: The intended size of the entries to be fetched
+ * }
+ */
+ getObjectStoreData(host, principal, dbName, storage, requestOptions) {
+ const { name } = this.splitNameAndStorage(dbName);
+ const request = this.openWithPrincipal(principal, name, storage);
+
+ return new Promise((resolve, reject) => {
+ let { objectStore, id, index, offset, size } = requestOptions;
+ const data = [];
+ let db;
+
+ if (!size || size > MAX_STORE_OBJECT_COUNT) {
+ size = MAX_STORE_OBJECT_COUNT;
+ }
+
+ request.onsuccess = event => {
+ db = event.target.result;
+
+ const transaction = db.transaction(objectStore, "readonly");
+ let source = transaction.objectStore(objectStore);
+ if (index && index != "name") {
+ source = source.index(index);
+ }
+
+ source.count().onsuccess = event2 => {
+ const objectsSize = [];
+ const count = event2.target.result;
+ objectsSize.push({
+ key: host + dbName + objectStore + index,
+ count: count,
+ });
+
+ if (!offset) {
+ offset = 0;
+ } else if (offset > count) {
+ db.close();
+ resolve([]);
+ return;
+ }
+
+ if (id) {
+ source.get(id).onsuccess = event3 => {
+ db.close();
+ resolve([{ name: id, value: event3.target.result }]);
+ };
+ } else {
+ source.openCursor().onsuccess = event4 => {
+ const cursor = event4.target.result;
+
+ if (!cursor || data.length >= size) {
+ db.close();
+ resolve({
+ data: data,
+ objectsSize: objectsSize,
+ });
+ return;
+ }
+ if (offset-- <= 0) {
+ data.push({ name: cursor.key, value: cursor.value });
+ }
+ cursor.continue();
+ };
+ }
+ };
+ };
+
+ request.onerror = () => {
+ db.close();
+ resolve([]);
+ };
+ });
+ },
+
+ /**
+ * When indexedDB metadata is parsed to and from JSON then the object's
+ * prototype is dropped and any Maps are changed to arrays of arrays. This
+ * method is used to repair the prototypes and fix any broken Maps.
+ */
+ patchMetadataMapsAndProtos(metadata) {
+ const md = Object.create(DatabaseMetadata.prototype);
+ Object.assign(md, metadata);
+
+ md._objectStores = new Map(metadata._objectStores);
+
+ for (const [name, store] of md._objectStores) {
+ const obj = Object.create(ObjectStoreMetadata.prototype);
+ Object.assign(obj, store);
+
+ md._objectStores.set(name, obj);
+
+ if (typeof store._indexes.length !== "undefined") {
+ obj._indexes = new Map(store._indexes);
+ }
+
+ for (const [name2, value] of obj._indexes) {
+ const obj2 = Object.create(IndexMetadata.prototype);
+ Object.assign(obj2, value);
+
+ obj._indexes.set(name2, obj2);
+ }
+ }
+
+ return md;
+ },
+
+ handleChildRequest(msg) {
+ const args = msg.data.args;
+
+ switch (msg.json.method) {
+ case "getDBMetaData": {
+ const [host, principal, name, storage] = args;
+ return indexedDBHelpers.getDBMetaData(host, principal, name, storage);
+ }
+ case "getInternalHosts": {
+ return indexedDBHelpers.getInternalHosts();
+ }
+ case "splitNameAndStorage": {
+ const [name] = args;
+ return indexedDBHelpers.splitNameAndStorage(name);
+ }
+ case "getDBNamesForHost": {
+ const [host, principal] = args;
+ return indexedDBHelpers.getDBNamesForHost(host, principal);
+ }
+ case "getValuesForHost": {
+ const [host, name, options, hostVsStores, principal] = args;
+ return indexedDBHelpers.getValuesForHost(
+ host,
+ name,
+ options,
+ hostVsStores,
+ principal
+ );
+ }
+ case "removeDB": {
+ const [host, principal, dbName] = args;
+ return indexedDBHelpers.removeDB(host, principal, dbName);
+ }
+ case "removeDBRecord": {
+ const [host, principal, db, store, id] = args;
+ return indexedDBHelpers.removeDBRecord(host, principal, db, store, id);
+ }
+ case "clearDBStore": {
+ const [host, principal, db, store] = args;
+ return indexedDBHelpers.clearDBStore(host, principal, db, store);
+ }
+ default:
+ console.error("ERR_DIRECTOR_PARENT_UNKNOWN_METHOD", msg.json.method);
+ throw new Error("ERR_DIRECTOR_PARENT_UNKNOWN_METHOD");
+ }
+ },
+};
+
+/**
+ * E10S parent/child setup helpers
+ */
+
+exports.setupParentProcessForIndexedDB = function({ mm, prefix }) {
+ mm.addMessageListener(
+ "debug:storage-indexedDB-request-parent",
+ indexedDBHelpers.handleChildRequest
+ );
+
+ return {
+ onDisconnected: () => {
+ mm.removeMessageListener(
+ "debug:storage-indexedDB-request-parent",
+ indexedDBHelpers.handleChildRequest
+ );
+ },
+ };
+};
+
+/**
+ * General helpers
+ */
+function trimHttpHttpsPort(url) {
+ const match = url.match(/(.+):\d+$/);
+
+ if (match) {
+ url = match[1];
+ }
+ if (url.startsWith("http://")) {
+ return url.substr(7);
+ }
+ if (url.startsWith("https://")) {
+ return url.substr(8);
+ }
+ return url;
+}
+
+/**
+ * The main Storage Actor.
+ */
+const StorageActor = protocol.ActorClassWithSpec(specs.storageSpec, {
+ typeName: "storage",
+
+ get window() {
+ return this.parentActor.window;
+ },
+
+ get document() {
+ return this.parentActor.window.document;
+ },
+
+ get windows() {
+ return this.childWindowPool;
+ },
+
+ initialize(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+
+ this.parentActor = targetActor;
+
+ this.childActorPool = new Map();
+ this.childWindowPool = new Set();
+
+ // Fetch all the inner iframe windows in this tab.
+ this.fetchChildWindows(this.parentActor.docShell);
+
+ // Skip initializing storage actors already instanced as Resources
+ // by the watcher. This happens when the target is a tab.
+ const isAddonTarget = !!this.parentActor.addonId;
+ const isWatcherEnabled = !isAddonTarget && !this.parentActor.isRootActor;
+ const shallUseLegacyActors = Services.prefs.getBoolPref(
+ "devtools.storage.test.forceLegacyActors",
+ false
+ );
+ const resourcesInWatcher = {
+ localStorage: isWatcherEnabled,
+ sessionStorage: isWatcherEnabled,
+ };
+
+ // Initialize the registered store types
+ for (const [store, ActorConstructor] of storageTypePool) {
+ // Only create the extensionStorage actor when the debugging target
+ // is an extension.
+ if (store === "extensionStorage" && !isAddonTarget) {
+ continue;
+ }
+ // Skip resource actors
+ if (resourcesInWatcher[store] && !shallUseLegacyActors) {
+ continue;
+ }
+
+ this.childActorPool.set(store, new ActorConstructor(this));
+ }
+
+ // Notifications that help us keep track of newly added windows and windows
+ // that got removed
+ Services.obs.addObserver(this, "content-document-global-created");
+ Services.obs.addObserver(this, "inner-window-destroyed");
+ this.onPageChange = this.onPageChange.bind(this);
+
+ const handler = targetActor.chromeEventHandler;
+ handler.addEventListener("pageshow", this.onPageChange, true);
+ handler.addEventListener("pagehide", this.onPageChange, true);
+
+ this.destroyed = false;
+ this.boundUpdate = {};
+ },
+
+ destroy() {
+ clearTimeout(this.batchTimer);
+ this.batchTimer = null;
+ // Remove observers
+ Services.obs.removeObserver(this, "content-document-global-created");
+ Services.obs.removeObserver(this, "inner-window-destroyed");
+ this.destroyed = true;
+ if (this.parentActor.browser) {
+ this.parentActor.browser.removeEventListener(
+ "pageshow",
+ this.onPageChange,
+ true
+ );
+ this.parentActor.browser.removeEventListener(
+ "pagehide",
+ this.onPageChange,
+ true
+ );
+ }
+ // Destroy the registered store types
+ for (const actor of this.childActorPool.values()) {
+ actor.destroy();
+ }
+ this.childActorPool.clear();
+ this.childWindowPool.clear();
+
+ this.childActorPool = null;
+ this.childWindowPool = null;
+ this.parentActor = null;
+ this.boundUpdate = null;
+ this._pendingResponse = null;
+
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Given a docshell, recursively find out all the child windows from it.
+ *
+ * @param {nsIDocShell} item
+ * The docshell from which all inner windows need to be extracted.
+ */
+ fetchChildWindows(item) {
+ const docShell = item
+ .QueryInterface(Ci.nsIDocShell)
+ .QueryInterface(Ci.nsIDocShellTreeItem);
+ if (!docShell.contentViewer) {
+ return null;
+ }
+ const window = docShell.contentViewer.DOMDocument.defaultView;
+ if (window.location.href == "about:blank") {
+ // Skip out about:blank windows as Gecko creates them multiple times while
+ // creating any global.
+ return null;
+ }
+ this.childWindowPool.add(window);
+ for (let i = 0; i < docShell.childCount; i++) {
+ const child = docShell.getChildAt(i);
+ this.fetchChildWindows(child);
+ }
+ return null;
+ },
+
+ isIncludedInTargetExtension(subject) {
+ const { document } = subject;
+ return (
+ document.nodePrincipal.addonId &&
+ document.nodePrincipal.addonId === this.parentActor.addonId
+ );
+ },
+
+ isIncludedInTopLevelWindow(window) {
+ return isWindowIncluded(this.window, window);
+ },
+
+ getWindowFromInnerWindowID(innerID) {
+ innerID = innerID.QueryInterface(Ci.nsISupportsPRUint64).data;
+ for (const win of this.childWindowPool.values()) {
+ const id = win.windowGlobalChild.innerWindowId;
+ if (id == innerID) {
+ return win;
+ }
+ }
+ return null;
+ },
+
+ getWindowFromHost(host) {
+ for (const win of this.childWindowPool.values()) {
+ const origin = win.document.nodePrincipal.originNoSuffix;
+ const url = win.document.URL;
+ if (origin === host || url === host) {
+ return win;
+ }
+ }
+ return null;
+ },
+
+ /**
+ * Event handler for any docshell update. This lets us figure out whenever
+ * any new window is added, or an existing window is removed.
+ */
+ observe(subject, topic) {
+ if (
+ subject.location &&
+ (!subject.location.href || subject.location.href == "about:blank")
+ ) {
+ return null;
+ }
+
+ // We don't want to try to find a top level window for an extension page, as
+ // in many cases (e.g. background page), it is not loaded in a tab, and
+ // 'isIncludedInTopLevelWindow' throws an error
+ if (
+ topic == "content-document-global-created" &&
+ (this.isIncludedInTargetExtension(subject) ||
+ this.isIncludedInTopLevelWindow(subject))
+ ) {
+ this.childWindowPool.add(subject);
+ this.emit("window-ready", subject);
+ } else if (topic == "inner-window-destroyed") {
+ const window = this.getWindowFromInnerWindowID(subject);
+ if (window) {
+ this.childWindowPool.delete(window);
+ this.emit("window-destroyed", window);
+ }
+ }
+ return null;
+ },
+
+ /**
+ * Called on "pageshow" or "pagehide" event on the chromeEventHandler of
+ * current tab.
+ *
+ * @param {event} The event object passed to the handler. We are using these
+ * three properties from the event:
+ * - target {document} The document corresponding to the event.
+ * - type {string} Name of the event - "pageshow" or "pagehide".
+ * - persisted {boolean} true if there was no
+ * "content-document-global-created" notification along
+ * this event.
+ */
+ onPageChange({ target, type, persisted }) {
+ if (this.destroyed) {
+ return;
+ }
+
+ const window = target.defaultView;
+
+ if (type == "pagehide" && this.childWindowPool.delete(window)) {
+ this.emit("window-destroyed", window);
+ } else if (
+ type == "pageshow" &&
+ persisted &&
+ window.location.href &&
+ window.location.href != "about:blank" &&
+ this.isIncludedInTopLevelWindow(window)
+ ) {
+ this.childWindowPool.add(window);
+ this.emit("window-ready", window);
+ }
+ },
+
+ /**
+ * Lists the available hosts for all the registered storage types.
+ *
+ * @returns {object} An object containing with the following structure:
+ * - <storageType> : [{
+ * actor: <actorId>,
+ * host: <hostname>
+ * }]
+ */
+ async listStores() {
+ const toReturn = {};
+
+ for (const [name, value] of this.childActorPool) {
+ if (value.preListStores) {
+ await value.preListStores();
+ }
+ toReturn[name] = value;
+ }
+
+ return toReturn;
+ },
+
+ /**
+ * This method is called by the registered storage types so as to tell the
+ * Storage Actor that there are some changes in the stores. Storage Actor then
+ * notifies the client front about these changes at regular (BATCH_DELAY)
+ * interval.
+ *
+ * @param {string} action
+ * The type of change. One of "added", "changed" or "deleted"
+ * @param {string} storeType
+ * The storage actor in which this change has occurred.
+ * @param {object} data
+ * The update object. This object is of the following format:
+ * - {
+ * <host1>: [<store_names1>, <store_name2>...],
+ * <host2>: [<store_names34>...],
+ * }
+ * Where host1, host2 are the host in which this change happened and
+ * [<store_namesX] is an array of the names of the changed store objects.
+ * Pass an empty array if the host itself was affected: either completely
+ * removed or cleared.
+ */
+ // eslint-disable-next-line complexity
+ update(action, storeType, data) {
+ if (action == "cleared") {
+ this.emit("stores-cleared", { [storeType]: data });
+ return null;
+ }
+
+ if (this.batchTimer) {
+ clearTimeout(this.batchTimer);
+ }
+ if (!this.boundUpdate[action]) {
+ this.boundUpdate[action] = {};
+ }
+ if (!this.boundUpdate[action][storeType]) {
+ this.boundUpdate[action][storeType] = {};
+ }
+ for (const host in data) {
+ if (!this.boundUpdate[action][storeType][host]) {
+ this.boundUpdate[action][storeType][host] = [];
+ }
+ for (const name of data[host]) {
+ if (!this.boundUpdate[action][storeType][host].includes(name)) {
+ this.boundUpdate[action][storeType][host].push(name);
+ }
+ }
+ }
+ if (action == "added") {
+ // If the same store name was previously deleted or changed, but now is
+ // added somehow, dont send the deleted or changed update.
+ this.removeNamesFromUpdateList("deleted", storeType, data);
+ this.removeNamesFromUpdateList("changed", storeType, data);
+ } else if (
+ action == "changed" &&
+ this.boundUpdate.added &&
+ this.boundUpdate.added[storeType]
+ ) {
+ // If something got added and changed at the same time, then remove those
+ // items from changed instead.
+ this.removeNamesFromUpdateList(
+ "changed",
+ storeType,
+ this.boundUpdate.added[storeType]
+ );
+ } else if (action == "deleted") {
+ // If any item got delete, or a host got delete, no point in sending
+ // added or changed update
+ this.removeNamesFromUpdateList("added", storeType, data);
+ this.removeNamesFromUpdateList("changed", storeType, data);
+
+ for (const host in data) {
+ if (
+ data[host].length == 0 &&
+ this.boundUpdate.added &&
+ this.boundUpdate.added[storeType] &&
+ this.boundUpdate.added[storeType][host]
+ ) {
+ delete this.boundUpdate.added[storeType][host];
+ }
+ if (
+ data[host].length == 0 &&
+ this.boundUpdate.changed &&
+ this.boundUpdate.changed[storeType] &&
+ this.boundUpdate.changed[storeType][host]
+ ) {
+ delete this.boundUpdate.changed[storeType][host];
+ }
+ }
+ }
+
+ this.batchTimer = setTimeout(() => {
+ clearTimeout(this.batchTimer);
+ this.emit("stores-update", this.boundUpdate);
+ this.boundUpdate = {};
+ }, BATCH_DELAY);
+
+ return null;
+ },
+
+ /**
+ * This method removes data from the this.boundUpdate object in the same
+ * manner like this.update() adds data to it.
+ *
+ * @param {string} action
+ * The type of change. One of "added", "changed" or "deleted"
+ * @param {string} storeType
+ * The storage actor for which you want to remove the updates data.
+ * @param {object} data
+ * The update object. This object is of the following format:
+ * - {
+ * <host1>: [<store_names1>, <store_name2>...],
+ * <host2>: [<store_names34>...],
+ * }
+ * Where host1, host2 are the hosts which you want to remove and
+ * [<store_namesX] is an array of the names of the store objects.
+ */
+ removeNamesFromUpdateList(action, storeType, data) {
+ for (const host in data) {
+ if (
+ this.boundUpdate[action] &&
+ this.boundUpdate[action][storeType] &&
+ this.boundUpdate[action][storeType][host]
+ ) {
+ for (const name in data[host]) {
+ const index = this.boundUpdate[action][storeType][host].indexOf(name);
+ if (index > -1) {
+ this.boundUpdate[action][storeType][host].splice(index, 1);
+ }
+ }
+ if (!this.boundUpdate[action][storeType][host].length) {
+ delete this.boundUpdate[action][storeType][host];
+ }
+ }
+ }
+ return null;
+ },
+});
+
+exports.StorageActor = StorageActor;
diff --git a/devtools/server/actors/string.js b/devtools/server/actors/string.js
new file mode 100644
index 0000000000..5db53753f3
--- /dev/null
+++ b/devtools/server/actors/string.js
@@ -0,0 +1,41 @@
+/* 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 { DevToolsServer } = require("devtools/server/devtools-server");
+
+var protocol = require("devtools/shared/protocol");
+const { longStringSpec } = require("devtools/shared/specs/string");
+
+exports.LongStringActor = protocol.ActorClassWithSpec(longStringSpec, {
+ initialize: function(conn, str) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this.str = str;
+ this.short = this.str.length < DevToolsServer.LONG_STRING_LENGTH;
+ },
+
+ destroy: function() {
+ this.str = null;
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ form: function() {
+ if (this.short) {
+ return this.str;
+ }
+ return {
+ type: "longString",
+ actor: this.actorID,
+ length: this.str.length,
+ initial: this.str.substring(0, DevToolsServer.LONG_STRING_INITIAL_LENGTH),
+ };
+ },
+
+ substring: function(start, end) {
+ return this.str.substring(start, end);
+ },
+
+ release: function() {},
+});
diff --git a/devtools/server/actors/style-rule.js b/devtools/server/actors/style-rule.js
new file mode 100644
index 0000000000..6d1989fc74
--- /dev/null
+++ b/devtools/server/actors/style-rule.js
@@ -0,0 +1,1168 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { getCSSLexer } = require("devtools/shared/css/lexer");
+const InspectorUtils = require("InspectorUtils");
+const TrackChangeEmitter = require("devtools/server/actors/utils/track-change-emitter");
+
+const {
+ getRuleText,
+ getTextAtLineColumn,
+} = require("devtools/server/actors/utils/style-utils");
+
+const { styleRuleSpec } = require("devtools/shared/specs/style-rule");
+const {
+ style: { ELEMENT_STYLE },
+} = require("devtools/shared/constants");
+
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "SharedCssLogic",
+ "devtools/shared/inspector/css-logic"
+);
+loader.lazyRequireGetter(
+ this,
+ ["CSSRuleTypeName", "findCssSelector", "prettifyCSS"],
+ "devtools/shared/inspector/css-logic",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isCssPropertyKnown",
+ "devtools/server/actors/css-properties",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "inactivePropertyHelper",
+ "devtools/server/actors/utils/inactive-property-helper",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "parseNamedDeclarations",
+ "devtools/shared/css/parsing-utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["UPDATE_PRESERVING_RULES", "UPDATE_GENERAL"],
+ "devtools/server/actors/style-sheet",
+ true
+);
+
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+
+const SUPPORTED_RULE_TYPES = [
+ CSSRule.STYLE_RULE,
+ CSSRule.SUPPORTS_RULE,
+ CSSRule.KEYFRAME_RULE,
+ CSSRule.KEYFRAMES_RULE,
+ CSSRule.MEDIA_RULE,
+];
+
+/**
+ * An actor that represents a CSS style object on the protocol.
+ *
+ * We slightly flatten the CSSOM for this actor, it represents
+ * both the CSSRule and CSSStyle objects in one actor. For nodes
+ * (which have a CSSStyle but no CSSRule) we create a StyleRuleActor
+ * with a special rule type (100).
+ */
+const StyleRuleActor = protocol.ActorClassWithSpec(styleRuleSpec, {
+ initialize: function(pageStyle, item) {
+ protocol.Actor.prototype.initialize.call(this, null);
+ this.pageStyle = pageStyle;
+ this.rawStyle = item.style;
+ this._parentSheet = null;
+ this._onStyleApplied = this._onStyleApplied.bind(this);
+ // Parsed CSS declarations from this.form().declarations used to check CSS property
+ // names and values before tracking changes. Using cached values instead of accessing
+ // this.form().declarations on demand because that would cause needless re-parsing.
+ this._declarations = [];
+
+ if (CSSRule.isInstance(item)) {
+ this.type = item.type;
+ this.rawRule = item;
+ this._computeRuleIndex();
+ if (
+ SUPPORTED_RULE_TYPES.includes(this.type) &&
+ this.rawRule.parentStyleSheet
+ ) {
+ this.line = InspectorUtils.getRelativeRuleLine(this.rawRule);
+ this.column = InspectorUtils.getRuleColumn(this.rawRule);
+ this._parentSheet = this.rawRule.parentStyleSheet;
+ if (!this.pageStyle.styleSheetWatcher) {
+ this.sheetActor = this.pageStyle._sheetRef(this._parentSheet);
+ this.sheetActor.on("style-applied", this._onStyleApplied);
+ }
+ }
+ } else {
+ // Fake a rule
+ this.type = ELEMENT_STYLE;
+ this.rawNode = item;
+ this.rawRule = {
+ style: item.style,
+ toString: function() {
+ return "[element rule " + this.style + "]";
+ },
+ };
+ }
+ },
+
+ get conn() {
+ return this.pageStyle.conn;
+ },
+
+ destroy: function() {
+ if (!this.rawStyle) {
+ return;
+ }
+ protocol.Actor.prototype.destroy.call(this);
+ this.rawStyle = null;
+ this.pageStyle = null;
+ this.rawNode = null;
+ this.rawRule = null;
+ this._declarations = null;
+ if (this.sheetActor) {
+ this.sheetActor.off("style-applied", this._onStyleApplied);
+ }
+ },
+
+ // Objects returned by this actor are owned by the PageStyleActor
+ // to which this rule belongs.
+ get marshallPool() {
+ return this.pageStyle;
+ },
+
+ // True if this rule supports as-authored styles, meaning that the
+ // rule text can be rewritten using setRuleText.
+ get canSetRuleText() {
+ return (
+ this.type === ELEMENT_STYLE ||
+ (this._parentSheet &&
+ // If a rule has been modified via CSSOM, then we should fall
+ // back to non-authored editing.
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1224121
+ !InspectorUtils.hasRulesModifiedByCSSOM(this._parentSheet) &&
+ // Special case about:PreferenceStyleSheet, as it is generated on
+ // the fly and the URI is not registered with the about:handler
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=935803#c37
+ this._parentSheet.href !== "about:PreferenceStyleSheet")
+ );
+ },
+
+ /**
+ * Return an array with StyleRuleActor instances for each of this rule's ancestor rules
+ * (@media, @supports, @keyframes, etc) obtained by recursively reading rule.parentRule.
+ * If the rule has no ancestors, return an empty array.
+ *
+ * @return {Array}
+ */
+ get ancestorRules() {
+ const ancestors = [];
+ let rule = this.rawRule;
+
+ while (rule.parentRule) {
+ ancestors.unshift(this.pageStyle._styleRef(rule.parentRule));
+ rule = rule.parentRule;
+ }
+
+ return ancestors;
+ },
+
+ /**
+ * Return an object with information about this rule used for tracking changes.
+ * It will be decorated with information about a CSS change before being tracked.
+ *
+ * It contains:
+ * - the rule selector (or generated selectror for inline styles)
+ * - the rule's host stylesheet (or element for inline styles)
+ * - the rule's ancestor rules (@media, @supports, @keyframes), if any
+ * - the rule's position within its ancestor tree, if any
+ *
+ * @return {Object}
+ */
+ get metadata() {
+ const data = {};
+ data.id = this.actorID;
+ // Collect information about the rule's ancestors (@media, @supports, @keyframes).
+ // Used to show context for this change in the UI and to match the rule for undo/redo.
+ data.ancestors = this.ancestorRules.map(rule => {
+ return {
+ id: rule.actorID,
+ // Rule type as number defined by CSSRule.type (ex: 4, 7, 12)
+ // @see https://developer.mozilla.org/en-US/docs/Web/API/CSSRule
+ type: rule.rawRule.type,
+ // Rule type as human-readable string (ex: "@media", "@supports", "@keyframes")
+ typeName: CSSRuleTypeName[rule.rawRule.type],
+ // Conditions of @media and @supports rules (ex: "min-width: 1em")
+ conditionText: rule.rawRule.conditionText,
+ // Name of @keyframes rule; refrenced by the animation-name CSS property.
+ name: rule.rawRule.name,
+ // Selector of individual @keyframe rule within a @keyframes rule (ex: 0%, 100%).
+ keyText: rule.rawRule.keyText,
+ // Array with the indexes of this rule and its ancestors within the CSS rule tree.
+ ruleIndex: rule._ruleIndex,
+ };
+ });
+
+ // For changes in element style attributes, generate a unique selector.
+ if (this.type === ELEMENT_STYLE && this.rawNode) {
+ // findCssSelector() fails on XUL documents. Catch and silently ignore that error.
+ try {
+ data.selector = findCssSelector(this.rawNode);
+ } catch (err) {}
+
+ data.source = {
+ type: "element",
+ // Used to differentiate between elements which match the same generated selector
+ // but live in different documents (ex: host document and iframe).
+ href: this.rawNode.baseURI,
+ // Element style attributes don't have a rule index; use the generated selector.
+ index: data.selector,
+ // Whether the element lives in a different frame than the host document.
+ isFramed: this.rawNode.ownerGlobal !== this.pageStyle.ownerWindow,
+ };
+
+ const nodeActor = this.pageStyle.walker.getNode(this.rawNode);
+ if (nodeActor) {
+ data.source.id = nodeActor.actorID;
+ }
+
+ data.ruleIndex = 0;
+ } else {
+ data.selector =
+ this.type === CSSRule.KEYFRAME_RULE
+ ? this.rawRule.keyText
+ : this.rawRule.selectorText;
+ // Used to differentiate between changes to rules with identical selectors.
+ data.ruleIndex = this._ruleIndex;
+
+ if (this.pageStyle.styleSheetWatcher) {
+ const watcher = this.pageStyle.styleSheetWatcher;
+ const sheet = this._parentSheet;
+ const inspectorActor = this.pageStyle.inspector;
+ const resourceId = watcher.getResourceId(sheet);
+ const styleSheetIndex = watcher.getStyleSheetIndex(resourceId);
+ data.source = {
+ // Inline stylesheets have a null href; Use window URL instead.
+ type: sheet.href ? "stylesheet" : "inline",
+ href: sheet.href || inspectorActor.window.location.toString(),
+ id: resourceId,
+ index: styleSheetIndex,
+ // Whether the stylesheet lives in a different frame than the host document.
+ isFramed: inspectorActor.window !== inspectorActor.window.top,
+ };
+ } else {
+ data.source = {
+ // Inline stylesheets have a null href; Use window URL instead.
+ type: this.sheetActor.href ? "stylesheet" : "inline",
+ href:
+ this.sheetActor.href || this.sheetActor.window.location.toString(),
+ id: this.sheetActor.actorID,
+ index: this.sheetActor.styleSheetIndex,
+ // Whether the stylesheet lives in a different frame than the host document.
+ isFramed: this.sheetActor.ownerWindow !== this.sheetActor.window,
+ };
+ }
+ }
+
+ return data;
+ },
+
+ getDocument: function(sheet) {
+ if (sheet.ownerNode) {
+ return sheet.ownerNode.nodeType == sheet.ownerNode.DOCUMENT_NODE
+ ? sheet.ownerNode
+ : sheet.ownerNode.ownerDocument;
+ } else if (sheet.parentStyleSheet) {
+ return this.getDocument(sheet.parentStyleSheet);
+ }
+ throw new Error(
+ "Failed trying to get the document of an invalid stylesheet"
+ );
+ },
+
+ toString: function() {
+ return "[StyleRuleActor for " + this.rawRule + "]";
+ },
+
+ // eslint-disable-next-line complexity
+ form: function() {
+ const form = {
+ actor: this.actorID,
+ type: this.type,
+ line: this.line || undefined,
+ column: this.column,
+ traits: {
+ // Indicates whether StyleRuleActor implements and can use the setRuleText method.
+ // It cannot use it if the stylesheet was programmatically mutated via the CSSOM.
+ canSetRuleText: this.canSetRuleText,
+ },
+ };
+
+ if (this.rawRule.parentRule) {
+ form.parentRule = this.pageStyle._styleRef(
+ this.rawRule.parentRule
+ ).actorID;
+
+ // CSS rules that we call media rules are STYLE_RULES that are children
+ // of MEDIA_RULEs. We need to check the parentRule to check if a rule is
+ // a media rule so we do this here instead of in the switch statement
+ // below.
+ if (this.rawRule.parentRule.type === CSSRule.MEDIA_RULE) {
+ form.media = [];
+ for (let i = 0, n = this.rawRule.parentRule.media.length; i < n; i++) {
+ form.media.push(this.rawRule.parentRule.media.item(i));
+ }
+ }
+ }
+ if (this._parentSheet) {
+ if (this.pageStyle.styleSheetWatcher) {
+ form.parentStyleSheet = this.pageStyle.styleSheetWatcher.getResourceId(
+ this._parentSheet
+ );
+ } else {
+ form.parentStyleSheet = this.pageStyle._sheetRef(
+ this._parentSheet
+ ).actorID;
+ }
+ }
+
+ // One tricky thing here is that other methods in this actor must
+ // ensure that authoredText has been set before |form| is called.
+ // This has to be treated specially, for now, because we cannot
+ // synchronously compute the authored text, but |form| also cannot
+ // return a promise. See bug 1205868.
+ form.authoredText = this.authoredText;
+
+ switch (this.type) {
+ case CSSRule.STYLE_RULE:
+ form.selectors = CssLogic.getSelectors(this.rawRule);
+ form.cssText = this.rawStyle.cssText || "";
+ break;
+ case ELEMENT_STYLE:
+ // Elements don't have a parent stylesheet, and therefore
+ // don't have an associated URI. Provide a URI for
+ // those.
+ const doc = this.rawNode.ownerDocument;
+ form.href = doc.location ? doc.location.href : "";
+ form.cssText = this.rawStyle.cssText || "";
+ form.authoredText = this.rawNode.getAttribute("style");
+ break;
+ case CSSRule.CHARSET_RULE:
+ form.encoding = this.rawRule.encoding;
+ break;
+ case CSSRule.IMPORT_RULE:
+ form.href = this.rawRule.href;
+ break;
+ case CSSRule.KEYFRAMES_RULE:
+ form.cssText = this.rawRule.cssText;
+ form.name = this.rawRule.name;
+ break;
+ case CSSRule.KEYFRAME_RULE:
+ form.cssText = this.rawStyle.cssText || "";
+ form.keyText = this.rawRule.keyText || "";
+ break;
+ }
+
+ // Parse the text into a list of declarations so the client doesn't have to
+ // and so that we can safely determine if a declaration is valid rather than
+ // have the client guess it.
+ if (form.authoredText || form.cssText) {
+ // authoredText may be an empty string when deleting all properties; it's ok to use.
+ const cssText =
+ typeof form.authoredText === "string"
+ ? form.authoredText
+ : form.cssText;
+ const declarations = parseNamedDeclarations(
+ isCssPropertyKnown,
+ cssText,
+ true
+ );
+ const el = this.pageStyle.selectedElement;
+ const style = this.pageStyle.cssLogic.computedStyle;
+
+ // Whether the stylesheet is a user-agent stylesheet. This affects the
+ // validity of some properties and property values.
+ const userAgent =
+ this._parentSheet &&
+ SharedCssLogic.isAgentStylesheet(this._parentSheet);
+ // Whether the stylesheet is a chrome stylesheet. Ditto.
+ //
+ // Note that chrome rules are also enabled in user sheets, see
+ // ParserContext::chrome_rules_enabled().
+ //
+ // https://searchfox.org/mozilla-central/rev/919607a3610222099fbfb0113c98b77888ebcbfb/servo/components/style/parser.rs#164
+ const chrome = (() => {
+ if (!this._parentSheet) {
+ return false;
+ }
+ if (SharedCssLogic.isUserStylesheet(this._parentSheet)) {
+ return true;
+ }
+ if (this._parentSheet.href) {
+ return this._parentSheet.href.startsWith("chrome:");
+ }
+ return el && el.ownerDocument.documentURI.startsWith("chrome:");
+ })();
+ // Whether the document is in quirks mode. This affects whether stuff
+ // like `width: 10` is valid.
+ const quirks =
+ !userAgent && el && el.ownerDocument.compatMode == "BackCompat";
+ const supportsOptions = { userAgent, chrome, quirks };
+ form.declarations = declarations.map(decl => {
+ // InspectorUtils.supports only supports the 1-arg version, but that's
+ // what we want to do anyways so that we also accept !important in the
+ // value.
+ decl.isValid = InspectorUtils.supports(
+ `${decl.name}:${decl.value}`,
+ supportsOptions
+ );
+ // TODO: convert from Object to Boolean. See Bug 1574471
+ decl.isUsed = inactivePropertyHelper.isPropertyUsed(
+ el,
+ style,
+ this.rawRule,
+ decl.name
+ );
+ // Check property name. All valid CSS properties support "initial" as a value.
+ decl.isNameValid = InspectorUtils.supports(
+ `${decl.name}:initial`,
+ supportsOptions
+ );
+ return decl;
+ });
+
+ // Cache parsed declarations so we don't needlessly re-parse authoredText every time
+ // we need to check previous property names and values when tracking changes.
+ this._declarations = declarations;
+ }
+
+ return form;
+ },
+
+ /**
+ * Send an event notifying that the location of the rule has
+ * changed.
+ *
+ * @param {Number} line the new line number
+ * @param {Number} column the new column number
+ */
+ _notifyLocationChanged: function(line, column) {
+ this.emit("location-changed", line, column);
+ },
+
+ /**
+ * Compute the index of this actor's raw rule in its parent style
+ * sheet. The index is a vector where each element is the index of
+ * a given CSS rule in its parent. A vector is used to support
+ * nested rules.
+ */
+ _computeRuleIndex: function() {
+ let rule = this.rawRule;
+ const result = [];
+
+ while (rule) {
+ let cssRules = [];
+ if (rule.parentRule) {
+ cssRules = rule.parentRule.cssRules;
+ } else if (rule.parentStyleSheet) {
+ cssRules = rule.parentStyleSheet.cssRules;
+ }
+
+ let found = false;
+ for (let i = 0; i < cssRules.length; i++) {
+ if (rule === cssRules.item(i)) {
+ found = true;
+ result.unshift(i);
+ break;
+ }
+ }
+
+ if (!found) {
+ this._ruleIndex = null;
+ return;
+ }
+
+ rule = rule.parentRule;
+ }
+
+ this._ruleIndex = result;
+ },
+
+ /**
+ * Get the rule corresponding to |this._ruleIndex| from the given
+ * style sheet.
+ *
+ * @param {DOMStyleSheet} sheet
+ * The style sheet.
+ * @return {CSSStyleRule} the rule corresponding to
+ * |this._ruleIndex|
+ */
+ _getRuleFromIndex: function(parentSheet) {
+ let currentRule = null;
+ for (const i of this._ruleIndex) {
+ if (currentRule === null) {
+ currentRule = parentSheet.cssRules[i];
+ } else {
+ currentRule = currentRule.cssRules.item(i);
+ }
+ }
+ return currentRule;
+ },
+
+ /**
+ * This is attached to the parent style sheet actor's
+ * "style-applied" event.
+ */
+ _onStyleApplied: function(kind) {
+ if (kind === UPDATE_GENERAL) {
+ // A general change means that the rule actors are invalidated,
+ // so stop listening to events now.
+ if (this.sheetActor) {
+ this.sheetActor.off("style-applied", this._onStyleApplied);
+ }
+ } else if (this._ruleIndex) {
+ // The sheet was updated by this actor, in a way that preserves
+ // the rules. Now, recompute our new rule from the style sheet,
+ // so that we aren't left with a reference to a dangling rule.
+ const oldRule = this.rawRule;
+ const oldActor = this.pageStyle.refMap.get(oldRule);
+ this.rawRule = this._getRuleFromIndex(this._parentSheet);
+ if (oldActor) {
+ // Also tell the page style so that future calls to _styleRef
+ // return the same StyleRuleActor.
+ this.pageStyle.updateStyleRef(oldRule, this.rawRule, this);
+ }
+ const line = InspectorUtils.getRelativeRuleLine(this.rawRule);
+ const column = InspectorUtils.getRuleColumn(this.rawRule);
+ if (line !== this.line || column !== this.column) {
+ this._notifyLocationChanged(line, column);
+ }
+ this.line = line;
+ this.column = column;
+ }
+ },
+
+ /**
+ * Return a promise that resolves to the authored form of a rule's
+ * text, if available. If the authored form is not available, the
+ * returned promise simply resolves to the empty string. If the
+ * authored form is available, this also sets |this.authoredText|.
+ * The authored text will include invalid and otherwise ignored
+ * properties.
+ *
+ * @param {Boolean} skipCache
+ * If a value for authoredText was previously found and cached,
+ * ignore it and parse the stylehseet again. The authoredText
+ * may be outdated if a descendant of this rule has changed.
+ */
+ getAuthoredCssText: async function(skipCache = false) {
+ if (!this.canSetRuleText || !SUPPORTED_RULE_TYPES.includes(this.type)) {
+ return Promise.resolve("");
+ }
+
+ if (typeof this.authoredText === "string" && !skipCache) {
+ return Promise.resolve(this.authoredText);
+ }
+
+ if (this.pageStyle.styleSheetWatcher) {
+ await this.pageStyle.styleSheetWatcher.ensureResourceAvailable(
+ this._parentSheet
+ );
+ const resourceId = this.pageStyle.styleSheetWatcher.getResourceId(
+ this._parentSheet
+ );
+ const cssText = await this.pageStyle.styleSheetWatcher.getText(
+ resourceId
+ );
+ const { text } = getRuleText(cssText, this.line, this.column);
+
+ // Cache the result on the rule actor to avoid parsing again next time
+ this.authoredText = text;
+ return this.authoredText;
+ }
+
+ return this.sheetActor.getText().then(longStr => {
+ const cssText = longStr.str;
+ const { text } = getRuleText(cssText, this.line, this.column);
+
+ // Cache the result on the rule actor to avoid parsing again next time
+ this.authoredText = text;
+ return this.authoredText;
+ });
+ },
+
+ /**
+ * Return a promise that resolves to the complete cssText of the rule as authored.
+ *
+ * Unlike |getAuthoredCssText()|, which only returns the contents of the rule, this
+ * method includes the CSS selectors and at-rules (@media, @supports, @keyframes, etc.)
+ *
+ * If the rule type is unrecongized, the promise resolves to an empty string.
+ * If the rule is an element inline style, the promise resolves with the generated
+ * selector that uniquely identifies the element and with the rule body consisting of
+ * the element's style attribute.
+ *
+ * @return {String}
+ */
+ getRuleText: async function() {
+ // Bail out if the rule is not supported or not an element inline style.
+ if (![...SUPPORTED_RULE_TYPES, ELEMENT_STYLE].includes(this.type)) {
+ return Promise.resolve("");
+ }
+
+ let ruleBodyText;
+ let selectorText;
+ let text;
+
+ // For element inline styles, use the style attribute and generated unique selector.
+ if (this.type === ELEMENT_STYLE) {
+ ruleBodyText = this.rawNode.getAttribute("style");
+ selectorText = this.metadata.selector;
+ } else {
+ // Get the rule's authored text and skip any cached value.
+ ruleBodyText = await this.getAuthoredCssText(true);
+
+ let stylesheetText = null;
+ if (this.pageStyle.styleSheetWatcher) {
+ await this.pageStyle.styleSheetWatcher.ensureResourceAvailable(
+ this._parentSheet
+ );
+ const resourceId = this.pageStyle.styleSheetWatcher.getResourceId(
+ this._parentSheet
+ );
+ stylesheetText = await this.pageStyle.styleSheetWatcher.getText(
+ resourceId
+ );
+ } else {
+ const { str } = await this.sheetActor.getText();
+ stylesheetText = str;
+ }
+
+ const [start, end] = getSelectorOffsets(
+ stylesheetText,
+ this.line,
+ this.column
+ );
+ selectorText = stylesheetText.substring(start, end);
+ }
+
+ // CSS rule type as a string "@media", "@supports", "@keyframes", etc.
+ const typeName = CSSRuleTypeName[this.type];
+
+ // When dealing with at-rules, getSelectorOffsets() will not return the rule type.
+ // We prepend it ourselves.
+ if (typeName) {
+ text = `${typeName}${selectorText} {${ruleBodyText}}`;
+ } else {
+ text = `${selectorText} {${ruleBodyText}}`;
+ }
+
+ const { result } = prettifyCSS(text);
+ return Promise.resolve(result);
+ },
+
+ /**
+ * Set the contents of the rule. This rewrites the rule in the
+ * stylesheet and causes it to be re-evaluated.
+ *
+ * @param {String} newText
+ * The new text of the rule
+ * @param {Array} modifications
+ * Array with modifications applied to the rule. Contains objects like:
+ * {
+ * type: "set",
+ * index: <number>,
+ * name: <string>,
+ * value: <string>,
+ * priority: <optional string>
+ * }
+ * or
+ * {
+ * type: "remove",
+ * index: <number>,
+ * name: <string>,
+ * }
+ * @returns the rule with updated properties
+ */
+ async setRuleText(newText, modifications = []) {
+ if (!this.canSetRuleText) {
+ throw new Error("invalid call to setRuleText");
+ }
+
+ // Log the changes before applying them so we have access to the previous values.
+ modifications.map(mod => this.logDeclarationChange(mod));
+
+ if (this.type === ELEMENT_STYLE) {
+ // For element style rules, set the node's style attribute.
+ this.rawNode.setAttributeDevtools("style", newText);
+ } else if (this.pageStyle.styleSheetWatcher) {
+ await this.pageStyle.styleSheetWatcher.ensureResourceAvailable(
+ this._parentSheet
+ );
+ const resourceId = this.pageStyle.styleSheetWatcher.getResourceId(
+ this._parentSheet
+ );
+ let cssText = await this.pageStyle.styleSheetWatcher.getText(resourceId);
+
+ const { offset, text } = getRuleText(cssText, this.line, this.column);
+ cssText =
+ cssText.substring(0, offset) +
+ newText +
+ cssText.substring(offset + text.length);
+
+ await this.pageStyle.styleSheetWatcher.update(
+ resourceId,
+ cssText,
+ false,
+ UPDATE_PRESERVING_RULES
+ );
+ } else {
+ // For stylesheet rules, set the text in the stylesheet.
+ const parentStyleSheet = this.pageStyle._sheetRef(this._parentSheet);
+ let { str: cssText } = await parentStyleSheet.getText();
+
+ const { offset, text } = getRuleText(cssText, this.line, this.column);
+ cssText =
+ cssText.substring(0, offset) +
+ newText +
+ cssText.substring(offset + text.length);
+
+ await parentStyleSheet.update(cssText, false, UPDATE_PRESERVING_RULES);
+ }
+
+ this.authoredText = newText;
+ this.pageStyle.refreshObservedRules();
+
+ // Returning this updated actor over the protocol will update its corresponding front
+ // and any references to it.
+ return this;
+ },
+
+ /**
+ * Modify a rule's properties. Passed an array of modifications:
+ * {
+ * type: "set",
+ * index: <number>,
+ * name: <string>,
+ * value: <string>,
+ * priority: <optional string>
+ * }
+ * or
+ * {
+ * type: "remove",
+ * index: <number>,
+ * name: <string>,
+ * }
+ *
+ * @returns the rule with updated properties
+ */
+ modifyProperties: function(modifications) {
+ // Use a fresh element for each call to this function to prevent side
+ // effects that pop up based on property values that were already set on the
+ // element.
+
+ let document;
+ if (this.rawNode) {
+ document = this.rawNode.ownerDocument;
+ } else {
+ let parentStyleSheet = this._parentSheet;
+ while (parentStyleSheet.ownerRule) {
+ parentStyleSheet = parentStyleSheet.ownerRule.parentStyleSheet;
+ }
+
+ document = this.getDocument(parentStyleSheet);
+ }
+
+ const tempElement = document.createElementNS(XHTML_NS, "div");
+
+ for (const mod of modifications) {
+ this.logDeclarationChange(mod);
+ if (mod.type === "set") {
+ tempElement.style.setProperty(mod.name, mod.value, mod.priority || "");
+ this.rawStyle.setProperty(
+ mod.name,
+ tempElement.style.getPropertyValue(mod.name),
+ mod.priority || ""
+ );
+ } else if (mod.type === "remove" || mod.type === "disable") {
+ this.rawStyle.removeProperty(mod.name);
+ }
+ }
+
+ this.pageStyle.refreshObservedRules();
+
+ return this;
+ },
+
+ /**
+ * Helper function for modifySelector, inserts the new
+ * rule with the new selector into the parent style sheet and removes the
+ * current rule. Returns the newly inserted css rule or null if the rule is
+ * unsuccessfully inserted to the parent style sheet.
+ *
+ * @param {String} value
+ * The new selector value
+ * @param {Boolean} editAuthored
+ * True if the selector should be updated by editing the
+ * authored text; false if the selector should be updated via
+ * CSSOM.
+ *
+ * @returns {CSSRule}
+ * The new CSS rule added
+ */
+ async _addNewSelector(value, editAuthored) {
+ const rule = this.rawRule;
+ const parentStyleSheet = this._parentSheet;
+
+ // We know the selector modification is ok, so if the client asked
+ // for the authored text to be edited, do it now.
+ if (editAuthored) {
+ const document = this.getDocument(this._parentSheet);
+ try {
+ document.querySelector(value);
+ } catch (e) {
+ return null;
+ }
+
+ if (this.pageStyle.styleSheetWatcher) {
+ await this.pageStyle.styleSheetWatcher.ensureResourceAvailable(
+ this._parentSheet
+ );
+ const resourceId = this.pageStyle.styleSheetWatcher.getResourceId(
+ this._parentSheet
+ );
+ let authoredText = await this.pageStyle.styleSheetWatcher.getText(
+ resourceId
+ );
+
+ const [startOffset, endOffset] = getSelectorOffsets(
+ authoredText,
+ this.line,
+ this.column
+ );
+ authoredText =
+ authoredText.substring(0, startOffset) +
+ value +
+ authoredText.substring(endOffset);
+
+ await this.pageStyle.styleSheetWatcher.update(
+ resourceId,
+ authoredText,
+ false,
+ UPDATE_PRESERVING_RULES
+ );
+ } else {
+ const sheetActor = this.pageStyle._sheetRef(parentStyleSheet);
+ let { str: authoredText } = await sheetActor.getText();
+
+ const [startOffset, endOffset] = getSelectorOffsets(
+ authoredText,
+ this.line,
+ this.column
+ );
+ authoredText =
+ authoredText.substring(0, startOffset) +
+ value +
+ authoredText.substring(endOffset);
+
+ await sheetActor.update(authoredText, false, UPDATE_PRESERVING_RULES);
+ }
+ } else {
+ const cssRules = parentStyleSheet.cssRules;
+ const cssText = rule.cssText;
+ const selectorText = rule.selectorText;
+
+ for (let i = 0; i < cssRules.length; i++) {
+ if (rule === cssRules.item(i)) {
+ try {
+ // Inserts the new style rule into the current style sheet and
+ // delete the current rule
+ const ruleText = cssText.slice(selectorText.length).trim();
+ parentStyleSheet.insertRule(value + " " + ruleText, i);
+ parentStyleSheet.deleteRule(i + 1);
+ break;
+ } catch (e) {
+ // The selector could be invalid, or the rule could fail to insert.
+ return null;
+ }
+ }
+ }
+ }
+
+ return this._getRuleFromIndex(parentStyleSheet);
+ },
+
+ /**
+ * Take an object with instructions to modify a CSS declaration and log an object with
+ * normalized metadata which describes the change in the context of this rule.
+ *
+ * @param {Object} change
+ * Data about a modification to a declaration. @see |modifyProperties()|
+ */
+ logDeclarationChange(change) {
+ // Position of the declaration within its rule.
+ const index = change.index;
+ // Destructure properties from the previous CSS declaration at this index, if any,
+ // to new variable names to indicate the previous state.
+ let {
+ value: prevValue,
+ name: prevName,
+ priority: prevPriority,
+ commentOffsets,
+ } = this._declarations[index] || {};
+ // A declaration is disabled if it has a `commentOffsets` array.
+ // Here we type coerce the value to a boolean with double-bang (!!)
+ const prevDisabled = !!commentOffsets;
+ // Append the "!important" string if defined in the previous priority flag.
+ prevValue =
+ prevValue && prevPriority ? `${prevValue} !important` : prevValue;
+
+ const data = this.metadata;
+
+ switch (change.type) {
+ case "set":
+ data.type = prevValue ? "declaration-add" : "declaration-update";
+ // If `change.newName` is defined, use it because the property is being renamed.
+ // Otherwise, a new declaration is being created or the value of an existing
+ // declaration is being updated. In that case, use the provided `change.name`.
+ const name = change.newName ? change.newName : change.name;
+ // Append the "!important" string if defined in the incoming priority flag.
+ const newValue = change.priority
+ ? `${change.value} !important`
+ : change.value;
+ // Reuse the previous value string, when the property is renamed.
+ // Otherwise, use the incoming value string.
+ const value = change.newName ? prevValue : newValue;
+
+ data.add = [{ property: name, value, index }];
+ // If there is a previous value, log its removal together with the previous
+ // property name. Using the previous name handles the case for renaming a property
+ // and is harmless when updating an existing value (the name stays the same).
+ if (prevValue) {
+ data.remove = [{ property: prevName, value: prevValue, index }];
+ } else {
+ data.remove = null;
+ }
+
+ // When toggling a declaration from OFF to ON, if not renaming the property,
+ // do not mark the previous declaration for removal, otherwise the add and
+ // remove operations will cancel each other out when tracked. Tracked changes
+ // have no context of "disabled", only "add" or remove, like diffs.
+ if (prevDisabled && !change.newName && prevValue === newValue) {
+ data.remove = null;
+ }
+
+ break;
+
+ case "remove":
+ data.type = "declaration-remove";
+ data.add = null;
+ data.remove = [{ property: change.name, value: prevValue, index }];
+ break;
+
+ case "disable":
+ data.type = "declaration-disable";
+ data.add = null;
+ data.remove = [{ property: change.name, value: prevValue, index }];
+ break;
+ }
+
+ TrackChangeEmitter.trackChange(data);
+ },
+
+ /**
+ * Helper method for tracking CSS changes. Logs the change of this rule's selector as
+ * two operations: a removal using the old selector and an addition using the new one.
+ *
+ * @param {String} oldSelector
+ * This rule's previous selector.
+ * @param {String} newSelector
+ * This rule's new selector.
+ */
+ logSelectorChange(oldSelector, newSelector) {
+ TrackChangeEmitter.trackChange({
+ ...this.metadata,
+ type: "selector-remove",
+ add: null,
+ remove: null,
+ selector: oldSelector,
+ });
+
+ TrackChangeEmitter.trackChange({
+ ...this.metadata,
+ type: "selector-add",
+ add: null,
+ remove: null,
+ selector: newSelector,
+ });
+ },
+
+ /**
+ * Modify the current rule's selector by inserting a new rule with the new
+ * selector value and removing the current rule.
+ *
+ * Returns information about the new rule and applied style
+ * so that consumers can immediately display the new rule, whether or not the
+ * selector matches the current element without having to refresh the whole
+ * list.
+ *
+ * @param {DOMNode} node
+ * The current selected element
+ * @param {String} value
+ * The new selector value
+ * @param {Boolean} editAuthored
+ * True if the selector should be updated by editing the
+ * authored text; false if the selector should be updated via
+ * CSSOM.
+ * @returns {Object}
+ * Returns an object that contains the applied style properties of the
+ * new rule and a boolean indicating whether or not the new selector
+ * matches the current selected element
+ */
+ modifySelector: function(node, value, editAuthored = false) {
+ if (this.type === ELEMENT_STYLE || this.rawRule.selectorText === value) {
+ return { ruleProps: null, isMatching: true };
+ }
+
+ // The rule's previous selector is lost after calling _addNewSelector(). Save it now.
+ const oldValue = this.rawRule.selectorText;
+ let selectorPromise = this._addNewSelector(value, editAuthored);
+
+ if (editAuthored) {
+ selectorPromise = selectorPromise.then(newCssRule => {
+ if (newCssRule) {
+ this.logSelectorChange(oldValue, value);
+ const style = this.pageStyle._styleRef(newCssRule);
+ // See the comment in |form| to understand this.
+ return style.getAuthoredCssText().then(() => newCssRule);
+ }
+ return newCssRule;
+ });
+ }
+
+ return selectorPromise.then(newCssRule => {
+ let ruleProps = null;
+ let isMatching = false;
+
+ if (newCssRule) {
+ const ruleEntry = this.pageStyle.findEntryMatchingRule(
+ node,
+ newCssRule
+ );
+ if (ruleEntry.length === 1) {
+ ruleProps = this.pageStyle.getAppliedProps(node, ruleEntry, {
+ matchedSelectors: true,
+ });
+ } else {
+ ruleProps = this.pageStyle.getNewAppliedProps(node, newCssRule);
+ }
+
+ isMatching = ruleProps.entries.some(
+ ruleProp => ruleProp.matchedSelectors.length > 0
+ );
+ }
+
+ return { ruleProps, isMatching };
+ });
+ },
+
+ /**
+ * Using the latest computed style applicable to the selected element,
+ * check the states of declarations in this CSS rule.
+ *
+ * If any have changed their used/unused state, potentially as a result of changes in
+ * another rule, fire a "rule-updated" event with this rule actor in its latest state.
+ */
+ refresh() {
+ let hasChanged = false;
+ const el = this.pageStyle.selectedElement;
+ const style = CssLogic.getComputedStyle(el);
+
+ for (const decl of this._declarations) {
+ // TODO: convert from Object to Boolean. See Bug 1574471
+ const isUsed = inactivePropertyHelper.isPropertyUsed(
+ el,
+ style,
+ this.rawRule,
+ decl.name
+ );
+
+ if (decl.isUsed.used !== isUsed.used) {
+ decl.isUsed = isUsed;
+ hasChanged = true;
+ }
+ }
+
+ if (hasChanged) {
+ // ⚠️ IMPORTANT ⚠️
+ // When an event is emitted via the protocol with the StyleRuleActor as payload, the
+ // corresponding StyleRuleFront will be automatically updated under the hood.
+ // Therefore, when the client looks up properties on the front reference it already
+ // has, it will get the latest values set on the actor, not the ones it originally
+ // had when the front was created. The client is not required to explicitly replace
+ // its previous front reference to the one it receives as this event's payload.
+ // The client doesn't even need to explicitly listen for this event.
+ // The update of the front happens automatically.
+ this.emit("rule-updated", this);
+ }
+ },
+});
+exports.StyleRuleActor = StyleRuleActor;
+
+/**
+ * Compute the start and end offsets of a rule's selector text, given
+ * the CSS text and the line and column at which the rule begins.
+ * @param {String} initialText
+ * @param {Number} line (1-indexed)
+ * @param {Number} column (1-indexed)
+ * @return {array} An array with two elements: [startOffset, endOffset].
+ * The elements mark the bounds in |initialText| of
+ * the CSS rule's selector.
+ */
+function getSelectorOffsets(initialText, line, column) {
+ if (typeof line === "undefined" || typeof column === "undefined") {
+ throw new Error("Location information is missing");
+ }
+
+ const { offset: textOffset, text } = getTextAtLineColumn(
+ initialText,
+ line,
+ column
+ );
+ const lexer = getCSSLexer(text);
+
+ // Search forward for the opening brace.
+ let endOffset;
+ while (true) {
+ const token = lexer.nextToken();
+ if (!token) {
+ break;
+ }
+ if (token.tokenType === "symbol" && token.text === "{") {
+ if (endOffset === undefined) {
+ break;
+ }
+ return [textOffset, textOffset + endOffset];
+ }
+ // Preserve comments and whitespace just before the "{".
+ if (token.tokenType !== "comment" && token.tokenType !== "whitespace") {
+ endOffset = token.endOffset;
+ }
+ }
+
+ throw new Error("could not find bounds of rule");
+}
diff --git a/devtools/server/actors/style-sheet.js b/devtools/server/actors/style-sheet.js
new file mode 100644
index 0000000000..866d4a1294
--- /dev/null
+++ b/devtools/server/actors/style-sheet.js
@@ -0,0 +1,528 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const protocol = require("devtools/shared/protocol");
+const { LongStringActor } = require("devtools/server/actors/string");
+const { MediaRuleActor } = require("devtools/server/actors/media-rule");
+const { fetch } = require("devtools/shared/DevToolsUtils");
+const { styleSheetSpec } = require("devtools/shared/specs/style-sheet");
+const InspectorUtils = require("InspectorUtils");
+const {
+ getSourcemapBaseURL,
+} = require("devtools/server/actors/utils/source-map-utils");
+
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/shared/inspector/css-logic"
+);
+loader.lazyRequireGetter(
+ this,
+ ["addPseudoClassLock", "removePseudoClassLock"],
+ "devtools/server/actors/highlighters/utils/markup",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "loadSheet",
+ "devtools/shared/layout/utils",
+ true
+);
+
+var TRANSITION_PSEUDO_CLASS = ":-moz-styleeditor-transitioning";
+var TRANSITION_DURATION_MS = 500;
+var TRANSITION_BUFFER_MS = 1000;
+var TRANSITION_RULE_SELECTOR = `:root${TRANSITION_PSEUDO_CLASS}, :root${TRANSITION_PSEUDO_CLASS} *`;
+
+var TRANSITION_SHEET =
+ "data:text/css;charset=utf-8," +
+ encodeURIComponent(`
+ ${TRANSITION_RULE_SELECTOR} {
+ transition-duration: ${TRANSITION_DURATION_MS}ms !important;
+ transition-delay: 0ms !important;
+ transition-timing-function: ease-out !important;
+ transition-property: all !important;
+ }
+`);
+
+// The possible kinds of style-applied events.
+// UPDATE_PRESERVING_RULES means that the update is guaranteed to
+// preserve the number and order of rules on the style sheet.
+// UPDATE_GENERAL covers any other kind of change to the style sheet.
+const UPDATE_PRESERVING_RULES = 0;
+exports.UPDATE_PRESERVING_RULES = UPDATE_PRESERVING_RULES;
+const UPDATE_GENERAL = 1;
+exports.UPDATE_GENERAL = UPDATE_GENERAL;
+
+// If the user edits a style sheet, we stash a copy of the edited text
+// here, keyed by the style sheet. This way, if the tools are closed
+// and then reopened, the edited text will be available. A weak map
+// is used so that navigation by the user will eventually cause the
+// edited text to be collected.
+const modifiedStyleSheets = new WeakMap();
+
+function getSheetText(sheet) {
+ const cssText = modifiedStyleSheets.get(sheet);
+ if (cssText !== undefined) {
+ return Promise.resolve(cssText);
+ }
+
+ if (!sheet.href) {
+ // this is an inline <style> sheet
+ const content = sheet.ownerNode.textContent;
+ return Promise.resolve(content);
+ }
+
+ return fetchStylesheet(sheet).then(({ content }) => content);
+}
+
+exports.getSheetText = getSheetText;
+
+/**
+ * Get the charset of the stylesheet.
+ */
+function getCSSCharset(sheet) {
+ if (sheet) {
+ // charset attribute of <link> or <style> element, if it exists
+ if (sheet.ownerNode?.getAttribute) {
+ const linkCharset = sheet.ownerNode.getAttribute("charset");
+ if (linkCharset != null) {
+ return linkCharset;
+ }
+ }
+
+ // charset of referring document.
+ if (sheet.ownerNode?.ownerDocument.characterSet) {
+ return sheet.ownerNode.ownerDocument.characterSet;
+ }
+ }
+
+ return "UTF-8";
+}
+
+/**
+ * Fetch a stylesheet at the provided URL. Returns a promise that will resolve the
+ * result of the fetch command.
+ *
+ * @return {Promise} a promise that resolves with an object with the following members
+ * on success:
+ * - content: the document at that URL, as a string,
+ * - contentType: the content type of the document
+ * If an error occurs, the promise is rejected with that error.
+ */
+async function fetchStylesheet(sheet) {
+ const href = sheet.href;
+
+ const options = {
+ loadFromCache: true,
+ policy: Ci.nsIContentPolicy.TYPE_INTERNAL_STYLESHEET,
+ charset: getCSSCharset(sheet),
+ };
+
+ // Bug 1282660 - We use the system principal to load the default internal
+ // stylesheets instead of the content principal since such stylesheets
+ // require system principal to load. At meanwhile, we strip the loadGroup
+ // for preventing the assertion of the userContextId mismatching.
+
+ // chrome|file|resource|moz-extension protocols rely on the system principal.
+ const excludedProtocolsRe = /^(chrome|file|resource|moz-extension):\/\//;
+ if (!excludedProtocolsRe.test(href)) {
+ // Stylesheets using other protocols should use the content principal.
+ if (sheet.ownerNode) {
+ // eslint-disable-next-line mozilla/use-ownerGlobal
+ options.window = sheet.ownerNode.ownerDocument.defaultView;
+ options.principal = sheet.ownerNode.ownerDocument.nodePrincipal;
+ }
+ }
+
+ let result;
+
+ try {
+ result = await fetch(href, options);
+ } catch (e) {
+ // The list of excluded protocols can be missing some protocols, try to use the
+ // system principal if the first fetch failed.
+ console.error(
+ `stylesheets actor: fetch failed for ${href},` +
+ ` using system principal instead.`
+ );
+ options.window = undefined;
+ options.principal = undefined;
+ result = await fetch(href, options);
+ }
+
+ return result;
+}
+
+/**
+ * A StyleSheetActor represents a stylesheet on the server.
+ */
+var StyleSheetActor = protocol.ActorClassWithSpec(styleSheetSpec, {
+ toString: function() {
+ return "[StyleSheetActor " + this.actorID + "]";
+ },
+
+ /**
+ * Window of target
+ */
+ get window() {
+ return this.parentActor.window;
+ },
+
+ /**
+ * Document of target.
+ */
+ get document() {
+ return this.window.document;
+ },
+
+ /**
+ * StyleSheet's window.
+ */
+ get ownerWindow() {
+ // eslint-disable-next-line mozilla/use-ownerGlobal
+ return this.ownerDocument.defaultView;
+ },
+
+ get ownerNode() {
+ return this.rawSheet.ownerNode;
+ },
+
+ /**
+ * URL of underlying stylesheet.
+ */
+ get href() {
+ return this.rawSheet.href;
+ },
+
+ /**
+ * Returns the stylesheet href or the document href if the sheet is inline.
+ */
+ get safeHref() {
+ let href = this.href;
+ if (!href) {
+ if (this.ownerNode.nodeType == this.ownerNode.DOCUMENT_NODE) {
+ href = this.ownerNode.location.href;
+ } else if (
+ this.ownerNode.ownerDocument &&
+ this.ownerNode.ownerDocument.location
+ ) {
+ href = this.ownerNode.ownerDocument.location.href;
+ }
+ }
+ return href;
+ },
+
+ /**
+ * Retrieve the index (order) of stylesheet in the document.
+ *
+ * @return number
+ */
+ get styleSheetIndex() {
+ if (this._styleSheetIndex == -1) {
+ const styleSheets = InspectorUtils.getAllStyleSheets(this.document, true);
+ for (let i = 0; i < styleSheets.length; i++) {
+ if (styleSheets[i] == this.rawSheet) {
+ this._styleSheetIndex = i;
+ break;
+ }
+ }
+ }
+ return this._styleSheetIndex;
+ },
+
+ destroy: function() {
+ if (this._transitionTimeout && this.window) {
+ this.window.clearTimeout(this._transitionTimeout);
+ removePseudoClassLock(
+ this.document.documentElement,
+ TRANSITION_PSEUDO_CLASS
+ );
+ }
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ initialize: function(styleSheet, parentActor) {
+ protocol.Actor.prototype.initialize.call(this, parentActor.conn);
+
+ this.rawSheet = styleSheet;
+ this.parentActor = parentActor;
+ this.conn = this.parentActor.conn;
+
+ // text and index are unknown until source load
+ this.text = null;
+ this._styleSheetIndex = -1;
+
+ // When the style is imported, `styleSheet.ownerNode` is null,
+ // so retrieve the topmost parent style sheet which has an ownerNode
+ let parentStyleSheet = styleSheet;
+ while (parentStyleSheet.parentStyleSheet) {
+ parentStyleSheet = parentStyleSheet.parentStyleSheet;
+ }
+ // When the style is injected via nsIDOMWindowUtils.loadSheet, even
+ // the parent style sheet has no owner, so default back to target actor
+ // document
+ if (parentStyleSheet.ownerNode) {
+ this.ownerDocument = parentStyleSheet.ownerNode.ownerDocument;
+ } else {
+ this.ownerDocument = parentActor.window;
+ }
+ },
+
+ /**
+ * Test whether this sheet has been modified by CSSOM.
+ * @return {Boolean} true if changed by CSSOM.
+ */
+ hasRulesModifiedByCSSOM: function() {
+ return InspectorUtils.hasRulesModifiedByCSSOM(this.rawSheet);
+ },
+
+ /**
+ * Get the raw stylesheet's cssRules once the sheet has been loaded.
+ *
+ * @return {Promise}
+ * Promise that resolves with a CSSRuleList
+ */
+ getCSSRules: function() {
+ let rules;
+ try {
+ rules = this.rawSheet.cssRules;
+ } catch (e) {
+ // sheet isn't loaded yet
+ }
+
+ if (rules) {
+ return Promise.resolve(rules);
+ }
+
+ if (!this.ownerNode) {
+ return Promise.resolve([]);
+ }
+
+ if (this._cssRules) {
+ return this._cssRules;
+ }
+
+ // cache so we don't add many listeners if this is called multiple times.
+ this._cssRules = new Promise(resolve => {
+ const onSheetLoaded = event => {
+ this.ownerNode.removeEventListener("load", onSheetLoaded);
+
+ resolve(this.rawSheet.cssRules);
+ };
+
+ this.ownerNode.addEventListener("load", onSheetLoaded);
+ });
+
+ return this._cssRules;
+ },
+
+ /**
+ * Get the current state of the actor
+ *
+ * @return {object}
+ * With properties of the underlying stylesheet, plus 'text',
+ * 'styleSheetIndex' and 'parentActor' if it's @imported
+ */
+ form: function() {
+ let docHref;
+ if (this.ownerNode) {
+ if (this.ownerNode.nodeType == this.ownerNode.DOCUMENT_NODE) {
+ docHref = this.ownerNode.location.href;
+ } else if (
+ this.ownerNode.ownerDocument &&
+ this.ownerNode.ownerDocument.location
+ ) {
+ docHref = this.ownerNode.ownerDocument.location.href;
+ }
+ }
+
+ const form = {
+ actor: this.actorID, // actorID is set when this actor is added to a pool
+ href: this.href,
+ nodeHref: docHref,
+ disabled: this.rawSheet.disabled,
+ title: this.rawSheet.title,
+ system: CssLogic.isAgentStylesheet(this.rawSheet),
+ styleSheetIndex: this.styleSheetIndex,
+ sourceMapBaseURL: getSourcemapBaseURL(
+ // Technically resolveSourceURL should be used here alongside
+ // "this.rawSheet.sourceURL", but the style inspector does not support
+ // /*# sourceURL=*/ in CSS, so we're omitting it here (bug 880831).
+ this.href || docHref,
+ this.ownerWindow
+ ),
+ sourceMapURL: this.rawSheet.sourceMapURL,
+ };
+
+ try {
+ form.ruleCount = this.rawSheet.cssRules.length;
+ } catch (e) {
+ // stylesheet had an @import rule that wasn't loaded yet
+ this.getCSSRules().then(() => {
+ this._notifyPropertyChanged("ruleCount");
+ });
+ }
+ return form;
+ },
+
+ /**
+ * Toggle the disabled property of the style sheet
+ *
+ * @return {object}
+ * 'disabled' - the disabled state after toggling.
+ */
+ toggleDisabled: function() {
+ this.rawSheet.disabled = !this.rawSheet.disabled;
+ this._notifyPropertyChanged("disabled");
+
+ return this.rawSheet.disabled;
+ },
+
+ /**
+ * Send an event notifying that a property of the stylesheet
+ * has changed.
+ *
+ * @param {string} property
+ * Name of the changed property
+ */
+ _notifyPropertyChanged: function(property) {
+ this.emit("property-change", property, this.form()[property]);
+ },
+
+ /**
+ * Protocol method to get the text of this stylesheet.
+ */
+ getText: function() {
+ return this._getText().then(text => {
+ return new LongStringActor(this.conn, text || "");
+ });
+ },
+
+ /**
+ * Fetch the text for this stylesheet from the cache or network. Return
+ * cached text if it's already been fetched.
+ *
+ * @return {Promise}
+ * Promise that resolves with a string text of the stylesheet.
+ */
+ _getText: function() {
+ if (typeof this.text === "string") {
+ return Promise.resolve(this.text);
+ }
+
+ return getSheetText(this.rawSheet).then(text => {
+ this.text = text;
+ return text;
+ });
+ },
+
+ /**
+ * Protocol method to get the media rules for the stylesheet.
+ */
+ getMediaRules: function() {
+ return this._getMediaRules();
+ },
+
+ /**
+ * Get all the @media rules in this stylesheet.
+ *
+ * @return {promise}
+ * A promise that resolves with an array of MediaRuleActors.
+ */
+ _getMediaRules: function() {
+ return this.getCSSRules().then(rules => {
+ const mediaRules = [];
+ for (let i = 0; i < rules.length; i++) {
+ const rule = rules[i];
+ if (rule.type != CSSRule.MEDIA_RULE) {
+ continue;
+ }
+ const actor = new MediaRuleActor(rule, this);
+ this.manage(actor);
+
+ mediaRules.push(actor);
+ }
+ return mediaRules;
+ });
+ },
+
+ /**
+ * Update the style sheet in place with new text.
+ *
+ * @param {string} text: new text
+ * @param {boolean} transition: whether to do CSS transition for change.
+ * @param {string} kind: either UPDATE_PRESERVING_RULES or UPDATE_GENERAL
+ * @param {string|null} cause: indicates the cause of this update
+ */
+ update: function(text, transition, kind = UPDATE_GENERAL, cause) {
+ InspectorUtils.parseStyleSheet(this.rawSheet, text);
+
+ modifiedStyleSheets.set(this.rawSheet, text);
+
+ this.text = text;
+
+ if (kind != UPDATE_PRESERVING_RULES) {
+ this._notifyPropertyChanged("ruleCount");
+ }
+
+ if (transition) {
+ this._startTransition(kind, cause);
+ } else {
+ this.emit("style-applied", kind, this, cause);
+ }
+
+ this._getMediaRules().then(rules => {
+ this.emit("media-rules-changed", rules);
+ });
+ },
+
+ /**
+ * Insert a catch-all transition sheet into the document. Set a timeout
+ * to remove the transition after a certain time.
+ *
+ * @param {string} kind: either UPDATE_PRESERVING_RULES or UPDATE_GENERAL
+ * @param {string|null} cause: indicates the cause of this update
+ */
+ _startTransition: function(kind, cause) {
+ if (!this._transitionSheetLoaded) {
+ this._transitionSheetLoaded = true;
+ // We don't remove this sheet. It uses an internal selector that
+ // we only apply via locks, so there's no need to load and unload
+ // it all the time.
+ loadSheet(this.window, TRANSITION_SHEET);
+ }
+
+ addPseudoClassLock(this.document.documentElement, TRANSITION_PSEUDO_CLASS);
+
+ // Set up clean up and commit after transition duration (+buffer)
+ // @see _onTransitionEnd
+ this.window.clearTimeout(this._transitionTimeout);
+ this._transitionTimeout = this.window.setTimeout(
+ this._onTransitionEnd.bind(this, kind, cause),
+ TRANSITION_DURATION_MS + TRANSITION_BUFFER_MS
+ );
+ },
+
+ /**
+ * This cleans up class and rule added for transition effect and then
+ * notifies that the style has been applied.
+ *
+ * @param {string} kind: either UPDATE_PRESERVING_RULES or UPDATE_GENERAL
+ * @param {string|null} cause: indicates the cause of this update
+ */
+ _onTransitionEnd: function(kind, cause) {
+ this._transitionTimeout = null;
+ removePseudoClassLock(
+ this.document.documentElement,
+ TRANSITION_PSEUDO_CLASS
+ );
+ this.emit("style-applied", kind, this, cause);
+ },
+});
+
+exports.StyleSheetActor = StyleSheetActor;
diff --git a/devtools/server/actors/style-sheets.js b/devtools/server/actors/style-sheets.js
new file mode 100644
index 0000000000..3b99590aca
--- /dev/null
+++ b/devtools/server/actors/style-sheets.js
@@ -0,0 +1,387 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const { LongStringActor } = require("devtools/server/actors/string");
+const { styleSheetsSpec } = require("devtools/shared/specs/style-sheets");
+const InspectorUtils = require("InspectorUtils");
+
+const {
+ TYPES,
+ getResourceWatcher,
+} = require("devtools/server/actors/resources/index");
+
+loader.lazyRequireGetter(
+ this,
+ "UPDATE_GENERAL",
+ "devtools/server/actors/style-sheet",
+ true
+);
+
+/**
+ * Creates a StyleSheetsActor. StyleSheetsActor provides remote access to the
+ * stylesheets of a document.
+ */
+var StyleSheetsActor = protocol.ActorClassWithSpec(styleSheetsSpec, {
+ /**
+ * The window we work with, taken from the parent actor.
+ */
+ get window() {
+ return this.parentActor.window;
+ },
+
+ /**
+ * The current content document of the window we work with.
+ */
+ get document() {
+ return this.window.document;
+ },
+
+ initialize: function(conn, targetActor) {
+ protocol.Actor.prototype.initialize.call(this, targetActor.conn);
+
+ this.parentActor = targetActor;
+
+ this._onApplicableStateChanged = this._onApplicableStateChanged.bind(this);
+ this._onNewStyleSheetActor = this._onNewStyleSheetActor.bind(this);
+ this._onWindowReady = this._onWindowReady.bind(this);
+ this._transitionSheetLoaded = false;
+
+ this.parentActor.on("stylesheet-added", this._onNewStyleSheetActor);
+ this.parentActor.on("window-ready", this._onWindowReady);
+
+ this.parentActor.chromeEventHandler.addEventListener(
+ "StyleSheetApplicableStateChanged",
+ this._onApplicableStateChanged,
+ true
+ );
+ },
+
+ getTraits() {
+ return {
+ traits: {},
+ };
+ },
+
+ destroy: function() {
+ for (const win of this.parentActor.windows) {
+ // This flag only exists for devtools, so we are free to clear
+ // it when we're done.
+ win.document.styleSheetChangeEventsEnabled = false;
+ }
+
+ this.parentActor.off("stylesheet-added", this._onNewStyleSheetActor);
+ this.parentActor.off("window-ready", this._onWindowReady);
+
+ this.parentActor.chromeEventHandler.removeEventListener(
+ "StyleSheetApplicableStateChanged",
+ this._onApplicableStateChanged,
+ true
+ );
+
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ /**
+ * Event handler that is called when a the target actor emits window-ready.
+ *
+ * @param {Event} evt
+ * The triggering event.
+ */
+ _onWindowReady: function(evt) {
+ this._addStyleSheets(evt.window);
+ },
+
+ /**
+ * Event handler that is called when a the target actor emits stylesheet-added.
+ *
+ * @param {StyleSheetActor} actor
+ * The new style sheet actor.
+ */
+ _onNewStyleSheetActor: function(actor) {
+ const info = this._addingStyleSheetInfo?.get(actor.rawSheet);
+ this._addingStyleSheetInfo?.delete(actor.rawSheet);
+
+ // Forward it to the client side.
+ this.emit(
+ "stylesheet-added",
+ actor,
+ info ? info.isNew : false,
+ info ? info.fileName : null
+ );
+ },
+
+ /**
+ * Protocol method for getting a list of StyleSheetActors representing
+ * all the style sheets in this document.
+ */
+ async getStyleSheets() {
+ let actors = [];
+
+ const windows = this.parentActor.windows;
+ for (const win of windows) {
+ const sheets = await this._addStyleSheets(win);
+ actors = actors.concat(sheets);
+ }
+ return actors;
+ },
+
+ /**
+ * Check if we should be showing this stylesheet.
+ *
+ * @param {DOMCSSStyleSheet} sheet
+ * Stylesheet we're interested in
+ *
+ * @return boolean
+ * Whether the stylesheet should be listed.
+ */
+ _shouldListSheet: function(sheet) {
+ // Special case about:PreferenceStyleSheet, as it is generated on the
+ // fly and the URI is not registered with the about: handler.
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=935803#c37
+ if (sheet.href?.toLowerCase() === "about:preferencestylesheet") {
+ return false;
+ }
+
+ return true;
+ },
+
+ /**
+ * Event handler that is called when the state of applicable of style sheet is changed.
+ *
+ * For now, StyleSheetApplicableStateChanged event will be called at following timings.
+ * - Append <link> of stylesheet to document
+ * - Append <style> to document
+ * - Change disable attribute of stylesheet object
+ * - Change disable attribute of <link> to false
+ * When appending <link>, <style> or changing `disable` attribute to false, `applicable`
+ * is passed as true. The other hand, when changing `disable` to true, this will be
+ * false.
+ * NOTE: For now, StyleSheetApplicableStateChanged will not be called when removing the
+ * link and style element.
+ *
+ * @param {StyleSheetApplicableStateChanged}
+ * The triggering event.
+ */
+ _onApplicableStateChanged: function({ applicable, stylesheet }) {
+ if (
+ // Have interest in applicable stylesheet only.
+ applicable &&
+ // No ownerNode means that this stylesheet is *not* associated to a DOM Element.
+ stylesheet.ownerNode &&
+ this._shouldListSheet(stylesheet) &&
+ !this._haveAncestorWithSameURL(stylesheet)
+ ) {
+ this.parentActor.createStyleSheetActor(stylesheet);
+ }
+ },
+
+ /**
+ * Add all the stylesheets for the document in this window to the map and
+ * create an actor for each one if not already created.
+ *
+ * @param {Window} win
+ * Window for which to add stylesheets
+ *
+ * @return {Promise}
+ * Promise that resolves to an array of StyleSheetActors
+ */
+ _addStyleSheets: function(win) {
+ return async function() {
+ const doc = win.document;
+ // We have to set this flag in order to get the
+ // StyleSheetApplicableStateChanged events. See Document.webidl.
+ doc.styleSheetChangeEventsEnabled = true;
+
+ const documentOnly = !doc.nodePrincipal.isSystemPrincipal;
+ const styleSheets = InspectorUtils.getAllStyleSheets(doc, documentOnly);
+
+ let actors = [];
+ for (let i = 0; i < styleSheets.length; i++) {
+ const sheet = styleSheets[i];
+ if (!this._shouldListSheet(sheet)) {
+ continue;
+ }
+
+ const actor = this.parentActor.createStyleSheetActor(sheet);
+ actors.push(actor);
+
+ // Get all sheets, including imported ones
+ const imports = await this._getImported(doc, actor);
+ actors = actors.concat(imports);
+ }
+ return actors;
+ }.bind(this)();
+ },
+
+ /**
+ * Get all the stylesheets @imported from a stylesheet.
+ *
+ * @param {Document} doc
+ * The document including the stylesheet
+ * @param {DOMStyleSheet} styleSheet
+ * Style sheet to search
+ * @return {Promise}
+ * A promise that resolves with an array of StyleSheetActors
+ */
+ _getImported: function(doc, styleSheet) {
+ return async function() {
+ const rules = await styleSheet.getCSSRules();
+ let imported = [];
+
+ for (let i = 0; i < rules.length; i++) {
+ const rule = rules[i];
+ if (rule.type == CSSRule.IMPORT_RULE) {
+ // With the Gecko style system, the associated styleSheet may be null
+ // if it has already been seen because an import cycle for the same
+ // URL. With Stylo, the styleSheet will exist (which is correct per
+ // the latest CSSOM spec), so we also need to check ancestors for the
+ // same URL to avoid cycles.
+ const sheet = rule.styleSheet;
+ if (
+ !sheet ||
+ this._haveAncestorWithSameURL(sheet) ||
+ !this._shouldListSheet(sheet)
+ ) {
+ continue;
+ }
+ const actor = this.parentActor.createStyleSheetActor(rule.styleSheet);
+ imported.push(actor);
+
+ // recurse imports in this stylesheet as well
+ const children = await this._getImported(doc, actor);
+ imported = imported.concat(children);
+ } else if (rule.type != CSSRule.CHARSET_RULE) {
+ // @import rules must precede all others except @charset
+ break;
+ }
+ }
+
+ return imported;
+ }.bind(this)();
+ },
+
+ /**
+ * Check all ancestors to see if this sheet's URL matches theirs as a way to
+ * detect an import cycle.
+ *
+ * @param {DOMStyleSheet} sheet
+ */
+ _haveAncestorWithSameURL(sheet) {
+ const sheetHref = sheet.href;
+ while (sheet.parentStyleSheet) {
+ if (sheet.parentStyleSheet.href == sheetHref) {
+ return true;
+ }
+ sheet = sheet.parentStyleSheet;
+ }
+ return false;
+ },
+
+ /**
+ * Create a new style sheet in the document with the given text.
+ * Return an actor for it.
+ *
+ * @param {object} request
+ * Debugging protocol request object, with 'text property'
+ * @param {string} fileName
+ * If the stylesheet adding is from file, `fileName` indicates the path.
+ * @return {object}
+ * Object with 'styelSheet' property for form on new actor.
+ */
+ async addStyleSheet(text, fileName = null) {
+ const styleSheetsWatcher = this._getStyleSheetsWatcher();
+ if (styleSheetsWatcher) {
+ await styleSheetsWatcher.addStyleSheet(this.document, text, fileName);
+ return;
+ }
+
+ // Following code can be removed once we enable STYLESHEET resource on the watcher/server
+ // side by default. For now it is being preffed off and we have to support the two
+ // codepaths. Once enabled we will only support the stylesheet watcher codepath.
+ const parent = this.document.documentElement;
+ const style = this.document.createElementNS(
+ "http://www.w3.org/1999/xhtml",
+ "style"
+ );
+ style.setAttribute("type", "text/css");
+
+ if (text) {
+ style.appendChild(this.document.createTextNode(text));
+ }
+ parent.appendChild(style);
+
+ // This is a bit convoluted. The style sheet actor may be created
+ // by a notification from platform. In this case, we can't easily
+ // pass the "new" flag through to createStyleSheetActor, so we set
+ // a flag locally and check it before sending an event to the
+ // client. See |_onNewStyleSheetActor|.
+ if (!this._addingStyleSheetInfo) {
+ this._addingStyleSheetInfo = new WeakMap();
+ }
+ this._addingStyleSheetInfo.set(style.sheet, { isNew: true, fileName });
+
+ const actor = this.parentActor.createStyleSheetActor(style.sheet);
+ // eslint-disable-next-line consistent-return
+ return actor;
+ },
+
+ _getStyleSheetActor(resourceId) {
+ return this.parentActor._targetScopedActorPool.getActorByID(resourceId);
+ },
+
+ _getStyleSheetsWatcher() {
+ return getResourceWatcher(this.parentActor, TYPES.STYLESHEET);
+ },
+
+ toggleDisabled(resourceId) {
+ const styleSheetsWatcher = this._getStyleSheetsWatcher();
+ if (styleSheetsWatcher) {
+ return styleSheetsWatcher.toggleDisabled(resourceId);
+ }
+
+ // Following code can be removed once we enable STYLESHEET resource on the watcher/server
+ // side by default. For now it is being preffed off and we have to support the two
+ // codepaths. Once enabled we will only support the stylesheet watcher codepath.
+ const actor = this._getStyleSheetActor(resourceId);
+ return actor.toggleDisabled();
+ },
+
+ async getText(resourceId) {
+ const styleSheetsWatcher = this._getStyleSheetsWatcher();
+ if (styleSheetsWatcher) {
+ const text = await styleSheetsWatcher.getText(resourceId);
+ return new LongStringActor(this.conn, text || "");
+ }
+
+ // Following code can be removed once we enable STYLESHEET resource on the watcher/server
+ // side by default. For now it is being preffed off and we have to support the two
+ // codepaths. Once enabled we will only support the stylesheet watcher codepath.
+ const actor = this._getStyleSheetActor(resourceId);
+ return actor.getText();
+ },
+
+ update(resourceId, text, transition, cause = "") {
+ const styleSheetsWatcher = this._getStyleSheetsWatcher();
+ if (styleSheetsWatcher) {
+ return styleSheetsWatcher.update(
+ resourceId,
+ text,
+ transition,
+ UPDATE_GENERAL,
+ cause
+ );
+ }
+
+ // Following code can be removed once we enable STYLESHEET resource on the watcher/server
+ // side by default. For now it is being preffed off and we have to support the two
+ // codepaths. Once enabled we will only support the stylesheet watcher codepath.
+ const actor = this._getStyleSheetActor(resourceId);
+ return actor.update(text, transition, UPDATE_GENERAL, cause);
+ },
+});
+
+exports.StyleSheetsActor = StyleSheetsActor;
diff --git a/devtools/server/actors/targets/browsing-context.js b/devtools/server/actors/targets/browsing-context.js
new file mode 100644
index 0000000000..d7debfcb2f
--- /dev/null
+++ b/devtools/server/actors/targets/browsing-context.js
@@ -0,0 +1,1899 @@
+/* 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";
+
+/* global XPCNativeWrapper */
+
+// protocol.js uses objects as exceptions in order to define
+// error packets.
+/* eslint-disable no-throw-literal */
+
+/*
+ * BrowsingContextTargetActor is an abstract class used by target actors that hold
+ * documents, such as frames, chrome windows, etc.
+ *
+ * This class is extended by FrameTargetActor, ParentProcessTargetActor, and
+ * ChromeWindowTargetActor.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ *
+ * For performance matters, this file should only be loaded in the targeted context's
+ * process. For example, it shouldn't be evaluated in the parent process until we try to
+ * debug a document living in the parent process.
+ */
+
+var { Ci, Cu, Cr, Cc } = require("chrome");
+var Services = require("Services");
+const ChromeUtils = require("ChromeUtils");
+var { ActorRegistry } = require("devtools/server/actors/utils/actor-registry");
+var DevToolsUtils = require("devtools/shared/DevToolsUtils");
+var { assert } = DevToolsUtils;
+var {
+ SourcesManager,
+} = require("devtools/server/actors/utils/sources-manager");
+var makeDebugger = require("devtools/server/actors/utils/make-debugger");
+const InspectorUtils = require("InspectorUtils");
+const Targets = require("devtools/server/actors/targets/index");
+const { TargetActorRegistry } = ChromeUtils.import(
+ "resource://devtools/server/actors/targets/target-actor-registry.jsm"
+);
+
+const EXTENSION_CONTENT_JSM = "resource://gre/modules/ExtensionContent.jsm";
+
+const { Actor, Pool } = require("devtools/shared/protocol");
+const {
+ LazyPool,
+ createExtraActors,
+} = require("devtools/shared/protocol/lazy-pool");
+const {
+ browsingContextTargetSpec,
+} = require("devtools/shared/specs/targets/browsing-context");
+const Resources = require("devtools/server/actors/resources/index");
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+loader.lazyRequireGetter(
+ this,
+ ["ThreadActor", "unwrapDebuggerObjectGlobal"],
+ "devtools/server/actors/thread",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WorkerDescriptorActorList",
+ "devtools/server/actors/worker/worker-descriptor-actor-list",
+ true
+);
+loader.lazyImporter(this, "ExtensionContent", EXTENSION_CONTENT_JSM);
+
+loader.lazyRequireGetter(
+ this,
+ ["StyleSheetActor", "getSheetText"],
+ "devtools/server/actors/style-sheet",
+ true
+);
+
+function getWindowID(window) {
+ return window.windowGlobalChild.innerWindowId;
+}
+
+function getDocShellChromeEventHandler(docShell) {
+ let handler = docShell.chromeEventHandler;
+ if (!handler) {
+ try {
+ // Toplevel xul window's docshell doesn't have chromeEventHandler
+ // attribute. The chrome event handler is just the global window object.
+ handler = docShell.domWindow;
+ } catch (e) {
+ // ignore
+ }
+ }
+ return handler;
+}
+
+function getChildDocShells(parentDocShell) {
+ const allDocShells = parentDocShell.getAllDocShellsInSubtree(
+ Ci.nsIDocShellTreeItem.typeAll,
+ Ci.nsIDocShell.ENUMERATE_FORWARDS
+ );
+
+ const docShells = [];
+ for (const docShell of allDocShells) {
+ docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ docShells.push(docShell);
+ }
+ return docShells;
+}
+
+exports.getChildDocShells = getChildDocShells;
+
+/**
+ * Browser-specific actors.
+ */
+
+function getInnerId(window) {
+ return window.windowGlobalChild.innerWindowId;
+}
+
+const browsingContextTargetPrototype = {
+ /**
+ * BrowsingContextTargetActor is an abstract class used by target actors that
+ * hold documents, such as frames, chrome windows, etc. The term "browsing
+ * context" is defined in the HTML spec as "an environment in which `Document`
+ * objects are presented to the user". In Gecko, this means a browsing context
+ * is a `docShell`.
+ *
+ * The main goal of this class is to expose the target-scoped actors being registered
+ * via `ActorRegistry.registerModule` and manage their lifetimes. In addition, this
+ * class also tracks the lifetime of the targeted browsing context.
+ *
+ * ### Main requests:
+ *
+ * `attach`/`detach` requests:
+ * - start/stop document watching:
+ * Starts watching for new documents and emits `tabNavigated` and
+ * `frameUpdate` over RDP.
+ * - retrieve the thread actor:
+ * Instantiates a ThreadActor that can be later attached to in order to
+ * debug JS sources in the document.
+ * `switchToFrame`:
+ * Change the targeted document of the whole actor, and its child target-scoped actors
+ * to an iframe or back to its original document.
+ *
+ * Most properties (like `chromeEventHandler` or `docShells`) are meant to be
+ * used by the various child target actors.
+ *
+ * ### RDP events:
+ *
+ * - `tabNavigated`:
+ * Sent when the browsing context is about to navigate or has just navigated
+ * to a different document.
+ * This event contains the following attributes:
+ * * url (string)
+ * The new URI being loaded.
+ * * nativeConsoleAPI (boolean)
+ * `false` if the console API of the page has been overridden (e.g. by Firebug)
+ * `true` if the Gecko implementation is used
+ * * state (string)
+ * `start` if we just start requesting the new URL
+ * `stop` if the new URL is done loading
+ * * isFrameSwitching (boolean)
+ * Indicates the event is dispatched when switching the actor context to a
+ * different frame. When we switch to an iframe, there is no document
+ * load. The targeted document is most likely going to be already done
+ * loading.
+ * * title (string)
+ * The document title being loaded. (sent only on state=stop)
+ *
+ * - `frameUpdate`:
+ * Sent when there was a change in the child frames contained in the document
+ * or when the actor's context was switched to another frame.
+ * This event can have four different forms depending on the type of change:
+ * * One or many frames are updated:
+ * { frames: [{ id, url, title, parentID }, ...] }
+ * * One frame got destroyed:
+ * { frames: [{ id, destroy: true }]}
+ * * All frames got destroyed:
+ * { destroyAll: true }
+ * * We switched the context of the actor to a specific frame:
+ * { selected: #id }
+ *
+ * ### Internal, non-rdp events:
+ *
+ * Various events are also dispatched on the actor itself without being sent to
+ * the client. They all relate to the documents tracked by this target actor
+ * (its main targeted document, but also any of its iframes):
+ * - will-navigate
+ * This event fires once navigation starts. All pending user prompts are
+ * dealt with, but it is fired before the first request starts.
+ * - navigate
+ * This event is fired once the document's readyState is "complete".
+ * - window-ready
+ * This event is fired in various distinct scenarios:
+ * * When a new Window object is crafted, equivalent of `DOMWindowCreated`.
+ * It is dispatched before any page script is executed.
+ * * We will have already received a window-ready event for this window
+ * when it was created, but we received a window-destroyed event when
+ * it was frozen into the bfcache, and now the user navigated back to
+ * this page, so it's now live again and we should resume handling it.
+ * * For each existing document, when an `attach` request is received.
+ * At this point scripts in the page will be already loaded.
+ * * When `swapFrameLoaders` is used, such as with moving browsing contexts
+ * between windows or toggling Responsive Design Mode.
+ * - window-destroyed
+ * This event is fired in two cases:
+ * * When the window object is destroyed, i.e. when the related document
+ * is garbage collected. This can happen when the browsing context is
+ * closed or the iframe is removed from the DOM.
+ * It is equivalent of `inner-window-destroyed` event.
+ * * When the page goes into the bfcache and gets frozen.
+ * The equivalent of `pagehide`.
+ * - changed-toplevel-document
+ * This event fires when we switch the actor's targeted document
+ * to one of its iframes, or back to its original top document.
+ * It is dispatched between window-destroyed and window-ready.
+ * - stylesheet-added
+ * This event is fired when a StyleSheetActor is created.
+ * It contains the following attribute:
+ * * actor (StyleSheetActor) The created actor.
+ *
+ * Note that *all* these events are dispatched in the following order
+ * when we switch the context of the actor to a given iframe:
+ * - will-navigate
+ * - window-destroyed
+ * - changed-toplevel-document
+ * - window-ready
+ * - navigate
+ *
+ * This class is subclassed by FrameTargetActor and others.
+ * Subclasses are expected to implement a getter for the docShell property.
+ *
+ * @param connection DevToolsServerConnection
+ * The conection to the client.
+ * @param docShell nsIDocShell
+ * The |docShell| for the debugged frame.
+ * @param options Object
+ * Object with following attributes:
+ * - followWindowGlobalLifeCycle Boolean
+ * If true, the target actor will only inspect the current WindowGlobal (and its children windows).
+ * But won't inspect next document loaded in the same BrowsingContext.
+ * The actor will behave more like a WindowGlobalTarget rather than a BrowsingContextTarget.
+ * We may eventually switch everything to this, i.e. uses only WindowGlobalTarget.
+ * But for now, we restrict this behavior to remoted iframes.
+ * - doNotFireFrameUpdates Boolean
+ * If true, omit emitting `frameUpdate` events. This is only useful
+ * for the top level target, in order to populate the toolbox iframe selector dropdown.
+ * But we can avoid sending these RDP messages for any additional remote target.
+ */
+ initialize: function(connection, docShell, options = {}) {
+ Actor.prototype.initialize.call(this, connection);
+
+ if (!docShell) {
+ throw new Error(
+ "A docShell should be provided as constructor argument of BrowsingContextTargetActor"
+ );
+ }
+ this.docShell = docShell;
+
+ this.followWindowGlobalLifeCycle = options.followWindowGlobalLifeCycle;
+ this.doNotFireFrameUpdates = options.doNotFireFrameUpdates;
+
+ // A map of actor names to actor instances provided by extensions.
+ this._extraActors = {};
+ this._exited = false;
+ this._sourcesManager = null;
+
+ // Map of DOM stylesheets to StyleSheetActors
+ this._styleSheetActors = new Map();
+
+ this._shouldAddNewGlobalAsDebuggee = this._shouldAddNewGlobalAsDebuggee.bind(
+ this
+ );
+
+ this.makeDebugger = makeDebugger.bind(null, {
+ findDebuggees: () => {
+ return this.windows.concat(this.webextensionsContentScriptGlobals);
+ },
+ shouldAddNewGlobalAsDebuggee: this._shouldAddNewGlobalAsDebuggee,
+ });
+
+ // Flag eventually overloaded by sub classes in order to watch new docshells
+ // Used by the ParentProcessTargetActor to list all frames in the Browser Toolbox
+ this.watchNewDocShells = false;
+
+ this.traits = {
+ reconfigure: true,
+ // Supports frame listing via `listFrames` request and `frameUpdate` events
+ // as well as frame switching via `switchToFrame` request
+ frames: true,
+ // Supports the logInPage request.
+ logInPage: true,
+ // Supports watchpoints in the server. We need to keep this trait because target
+ // actors that don't extend BrowsingContextTargetActor (Worker, ContentProcess, …)
+ // might not support watchpoints.
+ watchpoints: true,
+ // Supports back and forward navigation
+ navigation: true,
+ };
+
+ this._workerDescriptorActorList = null;
+ this._workerDescriptorActorPool = null;
+ this._onWorkerDescriptorActorListChanged = this._onWorkerDescriptorActorListChanged.bind(
+ this
+ );
+
+ TargetActorRegistry.registerTargetActor(this);
+ },
+
+ traits: null,
+
+ // Optional console API listener options (e.g. used by the WebExtensionActor to
+ // filter console messages by addonID), set to an empty (no options) object by default.
+ consoleAPIListenerOptions: {},
+
+ // Optional SourcesManager filter function (e.g. used by the WebExtensionActor to filter
+ // sources by addonID), allow all sources by default.
+ _allowSource() {
+ return true;
+ },
+
+ get exited() {
+ return this._exited;
+ },
+
+ get attached() {
+ return !!this._attached;
+ },
+
+ /*
+ * Return a Debugger instance or create one if there is none yet
+ */
+ get dbg() {
+ if (!this._dbg) {
+ this._dbg = this.makeDebugger();
+ }
+ return this._dbg;
+ },
+
+ /**
+ * Try to locate the console actor if it exists.
+ */
+ get _consoleActor() {
+ if (this.exited || this.isDestroyed()) {
+ return null;
+ }
+ const form = this.form();
+ return this.conn._getOrCreateActor(form.consoleActor);
+ },
+
+ _targetScopedActorPool: null,
+
+ /**
+ * An object on which listen for DOMWindowCreated and pageshow events.
+ */
+ get chromeEventHandler() {
+ return getDocShellChromeEventHandler(this.docShell);
+ },
+
+ /**
+ * Getter for the nsIMessageManager associated to the browsing context.
+ */
+ get messageManager() {
+ try {
+ return this.docShell.messageManager;
+ } catch (e) {
+ // In some cases we can't get a docshell. We just have no message manager
+ // then,
+ return null;
+ }
+ },
+
+ /**
+ * Getter for the list of all `docShell`s in the browsing context.
+ * @return {Array}
+ */
+ get docShells() {
+ return getChildDocShells(this.docShell);
+ },
+
+ /**
+ * Getter for the browsing context's current DOM window.
+ */
+ get window() {
+ return this.docShell && this.docShell.domWindow;
+ },
+
+ get outerWindowID() {
+ if (this.docShell) {
+ return this.docShell.outerWindowID;
+ }
+ return null;
+ },
+
+ get browsingContext() {
+ return this.docShell?.browsingContext;
+ },
+
+ get browsingContextID() {
+ return this.browsingContext?.id;
+ },
+
+ get browserId() {
+ return this.browsingContext?.browserId;
+ },
+
+ /**
+ * Getter for the WebExtensions ContentScript globals related to the
+ * browsing context's current DOM window.
+ */
+ get webextensionsContentScriptGlobals() {
+ // Only retrieve the content scripts globals if the ExtensionContent JSM module
+ // has been already loaded (which is true if the WebExtensions internals have already
+ // been loaded in the same content process).
+ if (Cu.isModuleLoaded(EXTENSION_CONTENT_JSM)) {
+ return ExtensionContent.getContentScriptGlobals(this.window);
+ }
+
+ return [];
+ },
+
+ /**
+ * Getter for the list of all content DOM windows in the browsing context.
+ * @return {Array}
+ */
+ get windows() {
+ return this.docShells.map(docShell => {
+ return docShell.domWindow;
+ });
+ },
+
+ /**
+ * Getter for the original docShell this actor got attached to in the first
+ * place.
+ * Note that your actor should normally *not* rely on this top level docShell
+ * if you want it to show information relative to the iframe that's currently
+ * being inspected in the toolbox.
+ */
+ get originalDocShell() {
+ if (!this._originalWindow) {
+ return this.docShell;
+ }
+
+ return this._originalWindow.docShell;
+ },
+
+ /**
+ * Getter for the original window this actor got attached to in the first
+ * place.
+ * Note that your actor should normally *not* rely on this top level window if
+ * you want it to show information relative to the iframe that's currently
+ * being inspected in the toolbox.
+ */
+ get originalWindow() {
+ return this._originalWindow || this.window;
+ },
+
+ /**
+ * Getter for the nsIWebProgress for watching this window.
+ */
+ get webProgress() {
+ return this.docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ },
+
+ /**
+ * Getter for the nsIWebNavigation for the target.
+ */
+ get webNavigation() {
+ return this.docShell.QueryInterface(Ci.nsIWebNavigation);
+ },
+
+ /**
+ * Getter for the browsing context's document.
+ */
+ get contentDocument() {
+ return this.webNavigation.document;
+ },
+
+ /**
+ * Getter for the browsing context's title.
+ */
+ get title() {
+ return this.contentDocument.contentTitle;
+ },
+
+ /**
+ * Getter for the browsing context's URL.
+ */
+ get url() {
+ if (this.webNavigation.currentURI) {
+ return this.webNavigation.currentURI.spec;
+ }
+ // Abrupt closing of the browser window may leave callbacks without a
+ // currentURI.
+ return null;
+ },
+
+ get sourcesManager() {
+ if (!this._sourcesManager) {
+ this._sourcesManager = new SourcesManager(
+ this.threadActor,
+ this._allowSource
+ );
+ }
+ return this._sourcesManager;
+ },
+
+ _createExtraActors() {
+ // Always use the same Pool, so existing actor instances
+ // (created in createExtraActors) are not lost.
+ if (!this._targetScopedActorPool) {
+ this._targetScopedActorPool = new LazyPool(this.conn);
+ }
+
+ // Walk over target-scoped actor factories and make sure they are all
+ // instantiated and added into the Pool.
+ return createExtraActors(
+ ActorRegistry.targetScopedActorFactories,
+ this._targetScopedActorPool,
+ this
+ );
+ },
+
+ form() {
+ assert(!this.exited, "form() shouldn't be called on exited browser actor.");
+ assert(this.actorID, "Actor should have an actorID.");
+
+ const response = {
+ actor: this.actorID,
+ browsingContextID: this.browsingContextID,
+ traits: {
+ // @backward-compat { version 64 } Exposes a new trait to help identify
+ // BrowsingContextActor's inherited actors from the client side.
+ isBrowsingContext: true,
+ },
+ };
+
+ // We may try to access window while the document is closing, then accessing window
+ // throws.
+ if (!this.docShell.isBeingDestroyed()) {
+ response.title = this.title;
+ response.url = this.url;
+ response.outerWindowID = this.outerWindowID;
+ }
+
+ const actors = this._createExtraActors();
+ Object.assign(response, actors);
+
+ // The thread actor is the only actor manually created by the target actor.
+ // It is not registered in targetScopedActorFactoriesand therefore needs
+ // to be added here manually.
+ if (this.threadActor) {
+ Object.assign(response, {
+ threadActor: this.threadActor.actorID,
+ });
+ }
+
+ return response;
+ },
+
+ /**
+ * Called when the actor is removed from the connection.
+ */
+ destroy() {
+ this.exit();
+ Actor.prototype.destroy.call(this);
+ TargetActorRegistry.unregisterTargetActor(this);
+ Resources.unwatchAllTargetResources(this);
+ },
+
+ /**
+ * Called by the root actor when the underlying browsing context is closed.
+ */
+ exit() {
+ if (this.exited) {
+ return;
+ }
+
+ // Tell the thread actor that the browsing context is closed, so that it may terminate
+ // instead of resuming the debuggee script.
+ if (this._attached) {
+ // TODO: Bug 997119: Remove this coupling with thread actor
+ this.threadActor._parentClosed = true;
+ }
+
+ this._detach();
+
+ this.docShell = null;
+
+ this._extraActors = null;
+
+ this._exited = true;
+ },
+
+ /**
+ * Return true if the given global is associated with this browsing context and should
+ * be added as a debuggee, false otherwise.
+ */
+ _shouldAddNewGlobalAsDebuggee(wrappedGlobal) {
+ // Otherwise, check if it is a WebExtension content script sandbox
+ const global = unwrapDebuggerObjectGlobal(wrappedGlobal);
+ if (!global) {
+ return false;
+ }
+
+ // Check if the global is a sdk page-mod sandbox.
+ let metadata = {};
+ let id = "";
+ try {
+ id = getInnerId(this.window);
+ metadata = Cu.getSandboxMetadata(global);
+ } catch (e) {
+ // ignore
+ }
+ if (metadata?.["inner-window-id"] && metadata["inner-window-id"] == id) {
+ return true;
+ }
+
+ return false;
+ },
+
+ /**
+ * Does the actual work of attaching to a browsing context.
+ */
+ _attach() {
+ if (this._attached) {
+ return;
+ }
+
+ // Create a pool for context-lifetime actors.
+ this._createThreadActor();
+
+ this._progressListener = new DebuggerProgressListener(this);
+
+ // Save references to the original document we attached to
+ this._originalWindow = this.window;
+
+ this._docShellsObserved = false;
+
+ // Ensure replying to attach() request first
+ // before notifying about new docshells.
+ DevToolsUtils.executeSoon(() => this._watchDocshells());
+
+ this._attached = true;
+ },
+
+ _watchDocshells() {
+ // If for some unexpected reason, the actor is immediately destroyed,
+ // avoid registering leaking observer listener.
+ if (this.exited) {
+ return;
+ }
+
+ // In child processes, we watch all docshells living in the process.
+ Services.obs.addObserver(this, "webnavigation-create");
+ Services.obs.addObserver(this, "webnavigation-destroy");
+ this._docShellsObserved = true;
+
+ // We watch for all child docshells under the current document,
+ this._progressListener.watch(this.docShell);
+
+ // And list all already existing ones.
+ this._updateChildDocShells();
+ },
+
+ _unwatchDocshells() {
+ if (this._progressListener) {
+ this._progressListener.destroy();
+ this._progressListener = null;
+ this._originalWindow = null;
+ }
+
+ // Removes the observers being set in _watchDocshells, but only
+ // if _watchDocshells has been called. The target actor may be immediately destroyed
+ // and doesn't have time to register them.
+ // (Calling removeObserver without having called addObserver throws)
+ if (this._docShellsObserved) {
+ Services.obs.removeObserver(this, "webnavigation-create");
+ Services.obs.removeObserver(this, "webnavigation-destroy");
+ this._docShellsObserved = true;
+ }
+ },
+
+ _unwatchDocShell(docShell) {
+ if (this._progressListener) {
+ this._progressListener.unwatch(docShell);
+ }
+ },
+
+ switchToFrame(request) {
+ const windowId = request.windowId;
+ let win;
+
+ try {
+ win = Services.wm.getOuterWindowWithId(windowId);
+ } catch (e) {
+ // ignore
+ }
+ if (!win) {
+ throw {
+ error: "noWindow",
+ message: "The related docshell is destroyed or not found",
+ };
+ } else if (win == this.window) {
+ return {};
+ }
+
+ // Reply first before changing the document
+ DevToolsUtils.executeSoon(() => this._changeTopLevelDocument(win));
+
+ return {};
+ },
+
+ listFrames(request) {
+ const windows = this._docShellsToWindows(this.docShells);
+ return { frames: windows };
+ },
+
+ ensureWorkerDescriptorActorList() {
+ if (this._workerDescriptorActorList === null) {
+ this._workerDescriptorActorList = new WorkerDescriptorActorList(
+ this.conn,
+ {
+ type: Ci.nsIWorkerDebugger.TYPE_DEDICATED,
+ window: this.window,
+ }
+ );
+ }
+ return this._workerDescriptorActorList;
+ },
+
+ pauseWorkersUntilAttach(shouldPause) {
+ this.ensureWorkerDescriptorActorList().workerPauser.setPauseMatching(
+ shouldPause
+ );
+ },
+
+ listWorkers(request) {
+ if (!this.attached) {
+ throw {
+ error: "wrongState",
+ };
+ }
+
+ return this.ensureWorkerDescriptorActorList()
+ .getList()
+ .then(actors => {
+ const pool = new Pool(this.conn, "worker-targets");
+ for (const actor of actors) {
+ pool.manage(actor);
+ }
+
+ // Do not destroy the pool before transfering ownership to the newly created
+ // pool, so that we do not accidently destroy actors that are still in use.
+ if (this._workerDescriptorActorPool) {
+ this._workerDescriptorActorPool.destroy();
+ }
+
+ this._workerDescriptorActorPool = pool;
+ this._workerDescriptorActorList.onListChanged = this._onWorkerDescriptorActorListChanged;
+
+ return {
+ workers: actors,
+ };
+ });
+ },
+
+ logInPage(request) {
+ const { text, category, flags } = request;
+ const scriptErrorClass = Cc["@mozilla.org/scripterror;1"];
+ const scriptError = scriptErrorClass.createInstance(Ci.nsIScriptError);
+ scriptError.initWithWindowID(
+ text,
+ null,
+ null,
+ 0,
+ 0,
+ flags,
+ category,
+ getInnerId(this.window)
+ );
+ Services.console.logMessage(scriptError);
+ return {};
+ },
+
+ _onWorkerDescriptorActorListChanged() {
+ this._workerDescriptorActorList.onListChanged = null;
+ this.emit("workerListChanged");
+ },
+
+ observe(subject, topic, data) {
+ // Ignore any event that comes before/after the actor is attached.
+ // That typically happens during Firefox shutdown.
+ if (!this.attached) {
+ return;
+ }
+
+ subject.QueryInterface(Ci.nsIDocShell);
+
+ if (topic == "webnavigation-create") {
+ this._onDocShellCreated(subject);
+ } else if (topic == "webnavigation-destroy") {
+ this._onDocShellDestroy(subject);
+ }
+ },
+
+ _onDocShellCreated(docShell) {
+ // (chrome-)webnavigation-create is fired very early during docshell
+ // construction. In new root docshells within child processes, involving
+ // BrowserChild, this event is from within this call:
+ // https://hg.mozilla.org/mozilla-central/annotate/74d7fb43bb44/dom/ipc/TabChild.cpp#l912
+ // whereas the chromeEventHandler (and most likely other stuff) is set
+ // later:
+ // https://hg.mozilla.org/mozilla-central/annotate/74d7fb43bb44/dom/ipc/TabChild.cpp#l944
+ // So wait a tick before watching it:
+ DevToolsUtils.executeSoon(() => {
+ // Bug 1142752: sometimes, the docshell appears to be immediately
+ // destroyed, bailout early to prevent random exceptions.
+ if (docShell.isBeingDestroyed()) {
+ return;
+ }
+
+ // In child processes, we have new root docshells,
+ // let's watch them and all their child docshells.
+ if (this._isRootDocShell(docShell) && this.watchNewDocShells) {
+ this._progressListener.watch(docShell);
+ }
+ this._notifyDocShellsUpdate([docShell]);
+ });
+ },
+
+ _onDocShellDestroy(docShell) {
+ // Stop watching this docshell (the unwatch() method will check if we
+ // started watching it before).
+ this._unwatchDocShell(docShell);
+
+ const webProgress = docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ this._notifyDocShellDestroy(webProgress);
+
+ if (webProgress.DOMWindow == this._originalWindow) {
+ // If the original top level document we connected to is removed,
+ // we try to switch to any other top level document
+ const rootDocShells = this.docShells.filter(d => {
+ return d != this.docShell && this._isRootDocShell(d);
+ });
+ if (rootDocShells.length > 0) {
+ const newRoot = rootDocShells[0];
+ this._originalWindow = newRoot.DOMWindow;
+ this._changeTopLevelDocument(this._originalWindow);
+ } else {
+ // If for some reason (typically during Firefox shutdown), the original
+ // document is destroyed, and there is no other top level docshell,
+ // we detach the actor to unregister all listeners and prevent any
+ // exception.
+ this.exit();
+ }
+ return;
+ }
+
+ // If the currently targeted browsing context is destroyed, and we aren't on
+ // the top-level document, we have to switch to the top-level one.
+ if (
+ webProgress.DOMWindow == this.window &&
+ this.window != this._originalWindow
+ ) {
+ this._changeTopLevelDocument(this._originalWindow);
+ }
+ },
+
+ _isRootDocShell(docShell) {
+ // Should report as root docshell:
+ // - New top level window's docshells, when using ParentProcessTargetActor against a
+ // process. It allows tracking iframes of the newly opened windows
+ // like Browser console or new browser windows.
+ // - MozActivities or window.open frames on B2G, where a new root docshell
+ // is spawn in the child process of the app.
+ return !docShell.parent;
+ },
+
+ _docShellToWindow(docShell) {
+ const webProgress = docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ const window = webProgress.DOMWindow;
+ const id = docShell.outerWindowID;
+ let parentID = undefined;
+ // Ignore the parent of the original document on non-e10s firefox,
+ // as we get the xul window as parent and don't care about it.
+ // Furthermore, ignore setting parentID when parent window is same as
+ // current window in order to deal with front end. e.g. toolbox will be fall
+ // into infinite loop due to recursive search with by using parent id.
+ if (
+ window.parent &&
+ window.parent != window &&
+ window != this._originalWindow
+ ) {
+ parentID = window.parent.docShell.outerWindowID;
+ }
+
+ return {
+ id,
+ parentID,
+ url: window.location.href,
+ title: window.document.title,
+ };
+ },
+
+ // Convert docShell list to windows objects list being sent to the client
+ _docShellsToWindows(docshells) {
+ return docshells.map(docShell => this._docShellToWindow(docShell));
+ },
+
+ _notifyDocShellsUpdate(docshells) {
+ // Only top level target uses frameUpdate in order to update the iframe dropdown.
+ // This may eventually be replaced by Target listening and target switching.
+ if (this.doNotFireFrameUpdates) {
+ return;
+ }
+
+ const windows = this._docShellsToWindows(docshells);
+
+ // Do not send the `frameUpdate` event if the windows array is empty.
+ if (windows.length == 0) {
+ return;
+ }
+
+ this.emit("frameUpdate", {
+ frames: windows,
+ });
+ },
+
+ _updateChildDocShells() {
+ this._notifyDocShellsUpdate(this.docShells);
+ },
+
+ _notifyDocShellDestroy(webProgress) {
+ // Only top level target uses frameUpdate in order to update the iframe dropdown.
+ // This may eventually be replaced by Target listening and target switching.
+ if (this.doNotFireFrameUpdates) {
+ return;
+ }
+
+ webProgress = webProgress.QueryInterface(Ci.nsIWebProgress);
+ const id = webProgress.DOMWindow.docShell.outerWindowID;
+ this.emit("frameUpdate", {
+ frames: [
+ {
+ id,
+ destroy: true,
+ },
+ ],
+ });
+ },
+
+ _notifyDocShellDestroyAll() {
+ // Only top level target uses frameUpdate in order to update the iframe dropdown.
+ // This may eventually be replaced by Target listening and target switching.
+ if (this.doNotFireFrameUpdates) {
+ return;
+ }
+
+ this.emit("frameUpdate", {
+ destroyAll: true,
+ });
+ },
+
+ /**
+ * Creates and manages the thread actor as part of the Browsing Context Target pool.
+ * This sets up the content window for being debugged
+ */
+ _createThreadActor() {
+ this.threadActor = new ThreadActor(this, this.window);
+ this.manage(this.threadActor);
+ },
+
+ /**
+ * Exits the current thread actor and removes it from the Browsing Context Target pool.
+ * The content window is no longer being debugged after this call.
+ */
+ _destroyThreadActor() {
+ this.threadActor.destroy();
+ this.threadActor = null;
+
+ if (this._sourcesManager) {
+ this._sourcesManager.destroy();
+ this._sourcesManager = null;
+ }
+ },
+
+ /**
+ * Does the actual work of detaching from a browsing context.
+ *
+ * @returns false if the actor wasn't attached or true of detaching succeeds.
+ */
+ _detach() {
+ if (!this.attached) {
+ return false;
+ }
+
+ // Check for `docShell` availability, as it can be already gone during
+ // Firefox shutdown.
+ if (this.docShell) {
+ this._unwatchDocShell(this.docShell);
+ this._restoreDocumentSettings();
+ }
+ this._unwatchDocshells();
+
+ this._destroyThreadActor();
+
+ // Shut down actors that belong to this target's pool.
+ this._styleSheetActors.clear();
+ if (this._targetScopedActorPool) {
+ this._targetScopedActorPool.destroy();
+ this._targetScopedActorPool = null;
+ }
+
+ // Make sure that no more workerListChanged notifications are sent.
+ if (this._workerDescriptorActorList !== null) {
+ this._workerDescriptorActorList.destroy();
+ this._workerDescriptorActorList = null;
+ }
+
+ if (this._workerDescriptorActorPool !== null) {
+ this._workerDescriptorActorPool.destroy();
+ this._workerDescriptorActorPool = null;
+ }
+
+ if (this._dbg) {
+ this._dbg.disable();
+ this._dbg = null;
+ }
+
+ this._attached = false;
+
+ // When the target actor acts as a WindowGlobalTarget, the actor will be destroyed
+ // without having to send an RDP event. The parent process will receive a window-global-destroyed
+ // and report the target actor as destroyed via the Watcher actor.
+ if (this.followWindowGlobalLifeCycle) {
+ return true;
+ }
+
+ this.emit("tabDetached");
+
+ return true;
+ },
+
+ // Protocol Request Handlers
+
+ attach(request) {
+ if (this.exited) {
+ throw {
+ error: "exited",
+ };
+ }
+
+ this._attach();
+
+ return {
+ threadActor: this.threadActor.actorID,
+ cacheDisabled: this._getCacheDisabled(),
+ javascriptEnabled: this._getJavascriptEnabled(),
+ traits: this.traits,
+ };
+ },
+
+ detach(request) {
+ if (!this._detach()) {
+ throw {
+ error: "wrongState",
+ };
+ }
+
+ return {};
+ },
+
+ /**
+ * Bring the browsing context's window to front.
+ */
+ focus() {
+ if (this.window) {
+ this.window.focus();
+ }
+ return {};
+ },
+
+ goForward() {
+ // Wait a tick so that the response packet can be dispatched before the
+ // subsequent navigation event packet.
+ Services.tm.dispatchToMainThread(
+ DevToolsUtils.makeInfallible(() => {
+ // This won't work while the browser is shutting down and we don't really
+ // care.
+ if (Services.startup.shuttingDown) {
+ return;
+ }
+
+ this.webNavigation.goForward();
+ }, "BrowsingContextTargetActor.prototype.goForward's delayed body")
+ );
+
+ return {};
+ },
+
+ goBack() {
+ // Wait a tick so that the response packet can be dispatched before the
+ // subsequent navigation event packet.
+ Services.tm.dispatchToMainThread(
+ DevToolsUtils.makeInfallible(() => {
+ // This won't work while the browser is shutting down and we don't really
+ // care.
+ if (Services.startup.shuttingDown) {
+ return;
+ }
+
+ this.webNavigation.goBack();
+ }, "BrowsingContextTargetActor.prototype.goBack's delayed body")
+ );
+
+ return {};
+ },
+
+ /**
+ * Reload the page in this browsing context.
+ */
+ reload(request) {
+ const force = request?.options?.force;
+ // Wait a tick so that the response packet can be dispatched before the
+ // subsequent navigation event packet.
+ Services.tm.dispatchToMainThread(
+ DevToolsUtils.makeInfallible(() => {
+ // This won't work while the browser is shutting down and we don't really
+ // care.
+ if (Services.startup.shuttingDown) {
+ return;
+ }
+
+ this.webNavigation.reload(
+ force
+ ? Ci.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE
+ : Ci.nsIWebNavigation.LOAD_FLAGS_NONE
+ );
+ }, "BrowsingContextTargetActor.prototype.reload's delayed body")
+ );
+ return {};
+ },
+
+ /**
+ * Navigate this browsing context to a new location
+ */
+ navigateTo(request) {
+ // Wait a tick so that the response packet can be dispatched before the
+ // subsequent navigation event packet.
+ Services.tm.dispatchToMainThread(
+ DevToolsUtils.makeInfallible(() => {
+ this.window.location = request.url;
+ }, "BrowsingContextTargetActor.prototype.navigateTo's delayed body:" + request.url)
+ );
+ return {};
+ },
+
+ /**
+ * Reconfigure options.
+ */
+ reconfigure(request) {
+ const options = request.options || {};
+
+ if (!this.docShell) {
+ // The browsing context is already closed.
+ return {};
+ }
+ this._toggleDevToolsSettings(options);
+
+ return {};
+ },
+
+ /**
+ * Ensure that CSS error reporting is enabled.
+ */
+ async ensureCSSErrorReportingEnabled(request) {
+ const promises = [];
+ for (const docShell of this.docShells) {
+ if (docShell.cssErrorReportingEnabled) {
+ continue;
+ }
+ try {
+ docShell.cssErrorReportingEnabled = true;
+ } catch (e) {
+ continue;
+ }
+ // Ensure docShell.document is available.
+ docShell.QueryInterface(Ci.nsIWebNavigation);
+ // We don't really want to reparse UA sheets and such, but want to do
+ // Shadow DOM / XBL.
+ const sheets = InspectorUtils.getAllStyleSheets(
+ docShell.document,
+ /* documentOnly = */ true
+ );
+ for (const sheet of sheets) {
+ if (InspectorUtils.hasRulesModifiedByCSSOM(sheet)) {
+ continue;
+ }
+ // Reparse the sheet so that we see the existing errors.
+ const onStyleSheetParsed = getSheetText(sheet)
+ .then(text => {
+ InspectorUtils.parseStyleSheet(sheet, text, /* aUpdate = */ false);
+ })
+ .catch(e => console.error("Error while parsing stylesheet"));
+ promises.push(onStyleSheetParsed);
+ }
+ }
+ await Promise.all(promises);
+ return {};
+ },
+
+ /**
+ * Handle logic to enable/disable JS/cache/Service Worker testing.
+ */
+ _toggleDevToolsSettings(options) {
+ // Wait a tick so that the response packet can be dispatched before the
+ // subsequent navigation event packet.
+ let reload = false;
+
+ if (
+ typeof options.javascriptEnabled !== "undefined" &&
+ options.javascriptEnabled !== this._getJavascriptEnabled()
+ ) {
+ this._setJavascriptEnabled(options.javascriptEnabled);
+ reload = true;
+ }
+ if (
+ typeof options.cacheDisabled !== "undefined" &&
+ options.cacheDisabled !== this._getCacheDisabled()
+ ) {
+ this._setCacheDisabled(options.cacheDisabled);
+ }
+ if (
+ typeof options.paintFlashing !== "undefined" &&
+ options.PaintFlashing !== this._getPaintFlashing()
+ ) {
+ this._setPaintFlashingEnabled(options.paintFlashing);
+ }
+ if (
+ typeof options.serviceWorkersTestingEnabled !== "undefined" &&
+ options.serviceWorkersTestingEnabled !==
+ this._getServiceWorkersTestingEnabled()
+ ) {
+ this._setServiceWorkersTestingEnabled(
+ options.serviceWorkersTestingEnabled
+ );
+ }
+ if (typeof options.restoreFocus == "boolean") {
+ this._restoreFocus = options.restoreFocus;
+ }
+
+ // Reload if:
+ // - there's an explicit `performReload` flag and it's true
+ // - there's no `performReload` flag, but it makes sense to do so
+ const hasExplicitReloadFlag = "performReload" in options;
+ if (
+ (hasExplicitReloadFlag && options.performReload) ||
+ (!hasExplicitReloadFlag && reload)
+ ) {
+ this.reload();
+ }
+ },
+
+ /**
+ * Opposite of the _toggleDevToolsSettings method, that reset document state
+ * when closing the toolbox.
+ */
+ _restoreDocumentSettings() {
+ this._restoreJavascript();
+ this._setCacheDisabled(false);
+ this._setServiceWorkersTestingEnabled(false);
+ this._setPaintFlashingEnabled(false);
+
+ if (this._restoreFocus && this.browsingContext?.isActive) {
+ this.window.focus();
+ }
+ },
+
+ /**
+ * Disable or enable the cache via docShell.
+ */
+ _setCacheDisabled(disabled) {
+ const enable = Ci.nsIRequest.LOAD_NORMAL;
+ const disable = Ci.nsIRequest.LOAD_BYPASS_CACHE;
+
+ this.docShell.defaultLoadFlags = disabled ? disable : enable;
+ },
+
+ /**
+ * Disable or enable JS via docShell.
+ */
+ _wasJavascriptEnabled: null,
+ _setJavascriptEnabled(allow) {
+ if (this._wasJavascriptEnabled === null) {
+ this._wasJavascriptEnabled = this.docShell.allowJavascript;
+ }
+ this.docShell.allowJavascript = allow;
+ },
+
+ /**
+ * Restore JS state, before the actor modified it.
+ */
+ _restoreJavascript() {
+ if (this._wasJavascriptEnabled !== null) {
+ this._setJavascriptEnabled(this._wasJavascriptEnabled);
+ this._wasJavascriptEnabled = null;
+ }
+ },
+
+ /**
+ * Return JS allowed status.
+ */
+ _getJavascriptEnabled() {
+ if (!this.docShell) {
+ // The browsing context is already closed.
+ return null;
+ }
+
+ return this.docShell.allowJavascript;
+ },
+
+ /**
+ * Disable or enable the service workers testing features.
+ */
+ _setServiceWorkersTestingEnabled(enabled) {
+ const windowUtils = this.window.windowUtils;
+ windowUtils.serviceWorkersTestingEnabled = enabled;
+ },
+
+ /**
+ * Disable or enable the paint flashing on the target.
+ */
+ _setPaintFlashingEnabled(enabled) {
+ const windowUtils = this.window.windowUtils;
+ windowUtils.paintFlashing = enabled;
+ },
+
+ /**
+ * Return cache allowed status.
+ */
+ _getCacheDisabled() {
+ if (!this.docShell) {
+ // The browsing context is already closed.
+ return null;
+ }
+
+ const disable = Ci.nsIRequest.LOAD_BYPASS_CACHE;
+ return this.docShell.defaultLoadFlags === disable;
+ },
+
+ /**
+ * Return paint flashing status.
+ */
+ _getPaintFlashing() {
+ if (!this.docShell) {
+ // The browsing context is already closed.
+ return null;
+ }
+
+ return this.window.windowUtils.paintFlashing;
+ },
+
+ /**
+ * Return service workers testing allowed status.
+ */
+ _getServiceWorkersTestingEnabled() {
+ if (!this.docShell) {
+ // The browsing context is already closed.
+ return null;
+ }
+
+ const windowUtils = this.window.windowUtils;
+ return windowUtils.serviceWorkersTestingEnabled;
+ },
+
+ _changeTopLevelDocument(window) {
+ // Fake a will-navigate on the previous document
+ // to let a chance to unregister it
+ this._willNavigate(this.window, window.location.href, null, true);
+
+ this._windowDestroyed(this.window, null, true);
+
+ // Immediately change the window as this window, if in process of unload
+ // may already be non working on the next cycle and start throwing
+ this._setWindow(window);
+
+ DevToolsUtils.executeSoon(() => {
+ // No need to do anything more if the actor is not attached anymore
+ // e.g. the client has been closed and the actors destroyed in the meantime.
+ if (!this.attached) {
+ return;
+ }
+
+ // Then fake window-ready and navigate on the given document
+ this._windowReady(window, { isFrameSwitching: true });
+ DevToolsUtils.executeSoon(() => {
+ this._navigate(window, true);
+ });
+ });
+ },
+
+ _setWindow(window) {
+ // Here is the very important call where we switch the currently targeted
+ // browsing context (it will indirectly update this.window and many other
+ // attributes defined from docShell).
+ this.docShell = window.docShell;
+ this.emit("changed-toplevel-document");
+ this.emit("frameUpdate", {
+ selected: this.outerWindowID,
+ });
+ },
+
+ /**
+ * Handle location changes, by clearing the previous debuggees and enabling
+ * debugging, which may have been disabled temporarily by the
+ * DebuggerProgressListener.
+ */
+ _windowReady(window, { isFrameSwitching, isBFCache } = {}) {
+ const isTopLevel = window == this.window;
+
+ // We just reset iframe list on WillNavigate, so we now list all existing
+ // frames when we load a new document in the original window
+ if (window == this._originalWindow && !isFrameSwitching) {
+ this._updateChildDocShells();
+ }
+
+ this.emit("window-ready", {
+ window: window,
+ isTopLevel: isTopLevel,
+ isBFCache,
+ id: getWindowID(window),
+ });
+ },
+
+ _windowDestroyed(window, id = null, isFrozen = false) {
+ this.emit("window-destroyed", {
+ window: window,
+ isTopLevel: window == this.window,
+ id: id || getWindowID(window),
+ isFrozen: isFrozen,
+ });
+ },
+
+ /**
+ * Start notifying server and client about a new document being loaded in the
+ * currently targeted browsing context.
+ */
+ _willNavigate(window, newURI, request, isFrameSwitching = false) {
+ let isTopLevel = window == this.window;
+ let reset = false;
+
+ if (window == this._originalWindow && !isFrameSwitching) {
+ // Clear the iframe list if the original top-level document changes.
+ this._notifyDocShellDestroyAll();
+
+ // If the top level document changes and we are targeting an iframe, we
+ // need to reset to the upcoming new top level document. But for this
+ // will-navigate event, we will dispatch on the old window. (The inspector
+ // codebase expect to receive will-navigate for the currently displayed
+ // document in order to cleanup the markup view)
+ if (this.window != this._originalWindow) {
+ reset = true;
+ window = this.window;
+ isTopLevel = true;
+ }
+ }
+
+ // will-navigate event needs to be dispatched synchronously, by calling the
+ // listeners in the order or registration. This event fires once navigation
+ // starts, (all pending user prompts are dealt with), but before the first
+ // request starts.
+ this.emit("will-navigate", {
+ window: window,
+ isTopLevel: isTopLevel,
+ newURI: newURI,
+ request: request,
+ });
+
+ // We don't do anything for inner frames here.
+ // (we will only update thread actor on window-ready)
+ if (!isTopLevel) {
+ return;
+ }
+
+ // When the actor acts as a WindowGlobalTarget, will-navigate won't fired.
+ // Instead we will receive a new top level target with isTargetSwitching=true.
+ if (!this.followWindowGlobalLifeCycle) {
+ this.emit("tabNavigated", {
+ url: newURI,
+ nativeConsoleAPI: true,
+ state: "start",
+ isFrameSwitching: isFrameSwitching,
+ });
+ }
+
+ if (reset) {
+ this._setWindow(this._originalWindow);
+ }
+ },
+
+ /**
+ * Notify server and client about a new document done loading in the current
+ * targeted browsing context.
+ */
+ _navigate(window, isFrameSwitching = false) {
+ const isTopLevel = window == this.window;
+
+ // navigate event needs to be dispatched synchronously,
+ // by calling the listeners in the order or registration.
+ // This event is fired once the document is loaded,
+ // after the load event, it's document ready-state is 'complete'.
+ this.emit("navigate", {
+ window: window,
+ isTopLevel: isTopLevel,
+ });
+
+ // We don't do anything for inner frames here.
+ // (we will only update thread actor on window-ready)
+ if (!isTopLevel) {
+ return;
+ }
+
+ // We may still significate when the document is done loading, via navigate.
+ // But as we no longer fire the "will-navigate", may be it is better to find
+ // other ways to get to our means.
+ // Listening to "navigate" is misleading as the document may already be loaded
+ // if we just opened the DevTools. So it is better to use "watch" pattern
+ // and instead have the actor either emit immediately resources as they are
+ // already available, or later on as the load progresses.
+ if (this.followWindowGlobalLifeCycle) {
+ return;
+ }
+
+ this.emit("tabNavigated", {
+ url: this.url,
+ title: this.title,
+ nativeConsoleAPI: this.hasNativeConsoleAPI(this.window),
+ state: "stop",
+ isFrameSwitching: isFrameSwitching,
+ });
+ },
+
+ /**
+ * Tells if the window.console object is native or overwritten by script in
+ * the page.
+ *
+ * @param nsIDOMWindow window
+ * The window object you want to check.
+ * @return boolean
+ * True if the window.console object is native, or false otherwise.
+ */
+ hasNativeConsoleAPI(window) {
+ let isNative = false;
+ try {
+ // We are very explicitly examining the "console" property of
+ // the non-Xrayed object here.
+ const console = window.wrappedJSObject.console;
+ isNative = new XPCNativeWrapper(console).IS_NATIVE_CONSOLE;
+ } catch (ex) {
+ // ignore
+ }
+ return isNative;
+ },
+
+ /**
+ * Create or return the StyleSheetActor for a style sheet. This method
+ * is here because the Style Editor and Inspector share style sheet actors.
+ *
+ * @param DOMStyleSheet styleSheet
+ * The style sheet to create an actor for.
+ * @return StyleSheetActor actor
+ * The actor for this style sheet.
+ *
+ */
+ createStyleSheetActor(styleSheet) {
+ assert(!this.exited, "Target must not be exited to create a sheet actor.");
+ if (this._styleSheetActors.has(styleSheet)) {
+ return this._styleSheetActors.get(styleSheet);
+ }
+ const actor = new StyleSheetActor(styleSheet, this);
+ this._styleSheetActors.set(styleSheet, actor);
+
+ this._targetScopedActorPool.manage(actor);
+ this.emit("stylesheet-added", actor);
+
+ return actor;
+ },
+
+ removeActorByName(name) {
+ if (name in this._extraActors) {
+ const actor = this._extraActors[name];
+ if (this._targetScopedActorPool.has(actor)) {
+ this._targetScopedActorPool.removeActor(actor);
+ }
+ delete this._extraActors[name];
+ }
+ },
+};
+
+exports.browsingContextTargetPrototype = browsingContextTargetPrototype;
+exports.BrowsingContextTargetActor = TargetActorMixin(
+ Targets.TYPES.FRAME,
+ browsingContextTargetSpec,
+ browsingContextTargetPrototype
+);
+
+/**
+ * The DebuggerProgressListener object is an nsIWebProgressListener which
+ * handles onStateChange events for the targeted browsing context. If the user
+ * tries to navigate away from a paused page, the listener makes sure that the
+ * debuggee is resumed before the navigation begins.
+ *
+ * @param BrowsingContextTargetActor targetActor
+ * The browsing context target actor associated with this listener.
+ */
+function DebuggerProgressListener(targetActor) {
+ this._targetActor = targetActor;
+ this._onWindowCreated = this.onWindowCreated.bind(this);
+ this._onWindowHidden = this.onWindowHidden.bind(this);
+
+ // Watch for windows destroyed (global observer that will need filtering)
+ Services.obs.addObserver(this, "inner-window-destroyed");
+
+ // XXX: for now we maintain the list of windows we know about in this instance
+ // so that we can discriminate windows we care about when observing
+ // inner-window-destroyed events. Bug 1016952 would remove the need for this.
+ this._knownWindowIDs = new Map();
+
+ this._watchedDocShells = new WeakSet();
+}
+
+DebuggerProgressListener.prototype = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIWebProgressListener",
+ "nsISupportsWeakReference",
+ ]),
+
+ destroy() {
+ Services.obs.removeObserver(this, "inner-window-destroyed");
+ this._knownWindowIDs.clear();
+ this._knownWindowIDs = null;
+ },
+
+ watch(docShell) {
+ // Add the docshell to the watched set. We're actually adding the window,
+ // because docShell objects are not wrappercached and would be rejected
+ // by the WeakSet.
+ const docShellWindow = docShell.domWindow;
+ this._watchedDocShells.add(docShellWindow);
+
+ const webProgress = docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ webProgress.addProgressListener(
+ this,
+ Ci.nsIWebProgress.NOTIFY_STATE_WINDOW |
+ Ci.nsIWebProgress.NOTIFY_STATE_DOCUMENT
+ );
+
+ const handler = getDocShellChromeEventHandler(docShell);
+ handler.addEventListener("DOMWindowCreated", this._onWindowCreated, true);
+ handler.addEventListener("pageshow", this._onWindowCreated, true);
+ handler.addEventListener("pagehide", this._onWindowHidden, true);
+
+ // Dispatch the _windowReady event on the targetActor for pre-existing windows
+ for (const win of this._getWindowsInDocShell(docShell)) {
+ this._targetActor._windowReady(win);
+ this._knownWindowIDs.set(getWindowID(win), win);
+ }
+
+ // The `watchedByDevTools` enables gecko behavior tied to this flag, such as:
+ // - reporting the contents of HTML loaded in the docshells,
+ // - or capturing stacks for the network monitor.
+ //
+ // This attribute may already have been toggled by a parent BrowsingContext.
+ // Typically the parent process or tab target. Both are top level BrowsingContext.
+ if (docShell.browsingContext.top == docShell.browsingContext) {
+ docShell.browsingContext.watchedByDevTools = true;
+ }
+ },
+
+ unwatch(docShell) {
+ const docShellWindow = docShell.domWindow;
+ if (!this._watchedDocShells.has(docShellWindow)) {
+ return;
+ }
+ this._watchedDocShells.delete(docShellWindow);
+
+ const webProgress = docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ // During process shutdown, the docshell may already be cleaned up and throw
+ try {
+ webProgress.removeProgressListener(this);
+ } catch (e) {
+ // ignore
+ }
+
+ const handler = getDocShellChromeEventHandler(docShell);
+ handler.removeEventListener(
+ "DOMWindowCreated",
+ this._onWindowCreated,
+ true
+ );
+ handler.removeEventListener("pageshow", this._onWindowCreated, true);
+ handler.removeEventListener("pagehide", this._onWindowHidden, true);
+
+ for (const win of this._getWindowsInDocShell(docShell)) {
+ this._knownWindowIDs.delete(getWindowID(win));
+ }
+
+ // We can only toggle this attribute on top level BrowsingContext,
+ // this will be propagated over the whole tree of BC.
+ // So we only need to set it from Parent Process Target
+ // and Tab Target. Tab's BrowsingContext are actually considered as top level BC.
+ if (docShell.browsingContext.top == docShell.browsingContext) {
+ docShell.browsingContext.watchedByDevTools = false;
+ }
+ },
+
+ _getWindowsInDocShell(docShell) {
+ return getChildDocShells(docShell).map(d => {
+ return d.domWindow;
+ });
+ },
+
+ onWindowCreated: DevToolsUtils.makeInfallible(function(evt) {
+ if (!this._targetActor.attached) {
+ return;
+ }
+
+ // If we're in a frame swap (which occurs when toggling RDM, for example), then we can
+ // ignore this event, as the window never really went anywhere for our purposes.
+ if (evt.inFrameSwap) {
+ return;
+ }
+
+ const window = evt.target.defaultView;
+ if (!window) {
+ // Some old UIs might emit unrelated events called pageshow/pagehide on
+ // elements which are not documents. Bail in this case. See Bug 1669666.
+ return;
+ }
+
+ const innerID = getWindowID(window);
+
+ // This handler is called for two events: "DOMWindowCreated" and "pageshow".
+ // Bail out if we already processed this window.
+ if (this._knownWindowIDs.has(innerID)) {
+ return;
+ }
+ this._knownWindowIDs.set(innerID, window);
+
+ // For a regular page navigation, "DOMWindowCreated" is fired before
+ // "pageshow". If the current event is "pageshow" but we have not processed
+ // the window yet, it means this is a BF cache navigation. In theory,
+ // `event.persisted` should be set for BF cache navigation events, but it is
+ // not always available, so we fallback on checking if "pageshow" is the
+ // first event received for a given window (see Bug 1378133).
+ const isBFCache = evt.type == "pageshow";
+
+ this._targetActor._windowReady(window, { isBFCache });
+ }, "DebuggerProgressListener.prototype.onWindowCreated"),
+
+ onWindowHidden: DevToolsUtils.makeInfallible(function(evt) {
+ if (!this._targetActor.attached) {
+ return;
+ }
+
+ // If we're in a frame swap (which occurs when toggling RDM, for example), then we can
+ // ignore this event, as the window isn't really going anywhere for our purposes.
+ if (evt.inFrameSwap) {
+ return;
+ }
+
+ // Only act as if the window has been destroyed if the 'pagehide' event
+ // was sent for a persisted window (persisted is set when the page is put
+ // and frozen in the bfcache). If the page isn't persisted, the observer's
+ // inner-window-destroyed event will handle it.
+ if (!evt.persisted) {
+ return;
+ }
+
+ const window = evt.target.defaultView;
+ if (!window) {
+ // Some old UIs might emit unrelated events called pageshow/pagehide on
+ // elements which are not documents. Bail in this case. See Bug 1669666.
+ return;
+ }
+
+ this._targetActor._windowDestroyed(window, null, true);
+ this._knownWindowIDs.delete(getWindowID(window));
+ }, "DebuggerProgressListener.prototype.onWindowHidden"),
+
+ observe: DevToolsUtils.makeInfallible(function(subject, topic) {
+ if (!this._targetActor.attached) {
+ return;
+ }
+
+ // Because this observer will be called for all inner-window-destroyed in
+ // the application, we need to filter out events for windows we are not
+ // watching
+ const innerID = subject.QueryInterface(Ci.nsISupportsPRUint64).data;
+ const window = this._knownWindowIDs.get(innerID);
+ if (window) {
+ this._knownWindowIDs.delete(innerID);
+ this._targetActor._windowDestroyed(window, innerID);
+ }
+
+ // Bug 1598364: when debugging browser.xhtml from the Browser Toolbox
+ // the DOMWindowCreated/pageshow/pagehide event listeners have to be
+ // re-registered against the next document when we reload browser.html
+ // (or navigate to another doc).
+ // That's because we registered the listener on docShell.domWindow as
+ // top level windows don't have a chromeEventHandler.
+ if (
+ this._watchedDocShells.has(window) &&
+ !window.docShell.chromeEventHandler
+ ) {
+ // First cleanup all the existing listeners
+ this.unwatch(window.docShell);
+ // Re-register new ones. The docShell is already referencing the new document.
+ this.watch(window.docShell);
+ }
+ }, "DebuggerProgressListener.prototype.observe"),
+
+ onStateChange: DevToolsUtils.makeInfallible(function(
+ progress,
+ request,
+ flag,
+ status
+ ) {
+ if (!this._targetActor.attached) {
+ return;
+ }
+ progress.QueryInterface(Ci.nsIDocShell);
+ if (progress.isBeingDestroyed()) {
+ return;
+ }
+
+ const isStart = flag & Ci.nsIWebProgressListener.STATE_START;
+ const isStop = flag & Ci.nsIWebProgressListener.STATE_STOP;
+ const isDocument = flag & Ci.nsIWebProgressListener.STATE_IS_DOCUMENT;
+ const isWindow = flag & Ci.nsIWebProgressListener.STATE_IS_WINDOW;
+
+ // Catch any iframe location change
+ if (isDocument && isStop) {
+ // Watch document stop to ensure having the new iframe url.
+ this._targetActor._notifyDocShellsUpdate([progress]);
+ }
+
+ const window = progress.DOMWindow;
+ if (isDocument && isStart) {
+ // One of the earliest events that tells us a new URI
+ // is being loaded in this window.
+ const newURI = request instanceof Ci.nsIChannel ? request.URI.spec : null;
+ this._targetActor._willNavigate(window, newURI, request);
+ }
+ if (isWindow && isStop) {
+ // Don't dispatch "navigate" event just yet when there is a redirect to
+ // about:neterror page.
+ // Navigating to about:neterror will make `status` be something else than NS_OK.
+ // But for some error like NS_BINDING_ABORTED we don't want to emit any `navigate`
+ // event as the page load has been cancelled and the related page document is going
+ // to be a dead wrapper.
+ if (
+ request.status != Cr.NS_OK &&
+ request.status != Cr.NS_BINDING_ABORTED
+ ) {
+ // Instead, listen for DOMContentLoaded as about:neterror is loaded
+ // with LOAD_BACKGROUND flags and never dispatches load event.
+ // That may be the same reason why there is no onStateChange event
+ // for about:neterror loads.
+ const handler = getDocShellChromeEventHandler(progress);
+ const onLoad = evt => {
+ // Ignore events from iframes
+ if (evt.target === window.document) {
+ handler.removeEventListener("DOMContentLoaded", onLoad, true);
+ this._targetActor._navigate(window);
+ }
+ };
+ handler.addEventListener("DOMContentLoaded", onLoad, true);
+ } else {
+ // Somewhat equivalent of load event.
+ // (window.document.readyState == complete)
+ this._targetActor._navigate(window);
+ }
+ }
+ },
+ "DebuggerProgressListener.prototype.onStateChange"),
+};
diff --git a/devtools/server/actors/targets/chrome-window.js b/devtools/server/actors/targets/chrome-window.js
new file mode 100644
index 0000000000..5671f03d39
--- /dev/null
+++ b/devtools/server/actors/targets/chrome-window.js
@@ -0,0 +1,112 @@
+/* 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";
+
+/*
+ * Target actor for a single chrome window, like a browser window.
+ *
+ * This actor extends BrowsingContextTargetActor.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const { Ci } = require("chrome");
+const Services = require("Services");
+const {
+ BrowsingContextTargetActor,
+ browsingContextTargetPrototype,
+} = require("devtools/server/actors/targets/browsing-context");
+
+const { extend } = require("devtools/shared/extend");
+const {
+ chromeWindowTargetSpec,
+} = require("devtools/shared/specs/targets/chrome-window");
+const Targets = require("devtools/server/actors/targets/index");
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+/**
+ * Protocol.js expects only the prototype object, and does not maintain the
+ * prototype chain when it constructs the ActorClass. For this reason we are using
+ * `extend` to maintain the properties of BrowsingContextTargetActor.prototype
+ */
+const chromeWindowTargetPrototype = extend({}, browsingContextTargetPrototype);
+
+/**
+ * Creates a ChromeWindowTargetActor for debugging a single window, like a browser window
+ * in Firefox, but it can be used to reach any window in the process.
+ *
+ * Currently this is parent process only because the root actor's `onGetWindow` doesn't
+ * try to cross process boundaries. This actor technically would work for both chrome and
+ * content windows, but it can't reach (most) content windows since it's parent process
+ * only. Since these restrictions mean that chrome windows are the main use case for
+ * this at the moment, it's named to match.
+ *
+ * Most of the implementation is inherited from BrowsingContextTargetActor.
+ * ChromeWindowTargetActor exposes all target-scoped actors via its form() request, like
+ * BrowsingContextTargetActor.
+ *
+ * You can request a specific window's actor via RootActor.getWindow().
+ *
+ * @param connection DevToolsServerConnection
+ * The connection to the client.
+ * @param window DOMWindow
+ * The window.
+ */
+chromeWindowTargetPrototype.initialize = function(connection, window) {
+ BrowsingContextTargetActor.prototype.initialize.call(
+ this,
+ connection,
+ window.docShell
+ );
+};
+
+// Bug 1266561: This setting is mysteriously named, we should split up the
+// functionality that is triggered by it.
+chromeWindowTargetPrototype.isRootActor = true;
+
+chromeWindowTargetPrototype.observe = function(subject, topic, data) {
+ BrowsingContextTargetActor.prototype.observe.call(this, subject, topic, data);
+ if (!this.attached) {
+ return;
+ }
+ if (topic == "chrome-webnavigation-destroy") {
+ this._onDocShellDestroy(subject);
+ }
+};
+
+chromeWindowTargetPrototype._attach = function() {
+ if (this.attached) {
+ return false;
+ }
+
+ BrowsingContextTargetActor.prototype._attach.call(this);
+
+ // Listen for chrome docshells in addition to content docshells
+ if (this.docShell.itemType == Ci.nsIDocShellTreeItem.typeChrome) {
+ Services.obs.addObserver(this, "chrome-webnavigation-destroy");
+ }
+
+ return true;
+};
+
+chromeWindowTargetPrototype._detach = function() {
+ if (!this.attached) {
+ return false;
+ }
+
+ if (this.docShell.itemType == Ci.nsIDocShellTreeItem.typeChrome) {
+ Services.obs.removeObserver(this, "chrome-webnavigation-destroy");
+ }
+
+ BrowsingContextTargetActor.prototype._detach.call(this);
+
+ return true;
+};
+
+exports.ChromeWindowTargetActor = TargetActorMixin(
+ Targets.TYPES.FRAME,
+ chromeWindowTargetSpec,
+ chromeWindowTargetPrototype
+);
diff --git a/devtools/server/actors/targets/content-process.js b/devtools/server/actors/targets/content-process.js
new file mode 100644
index 0000000000..0da23e766e
--- /dev/null
+++ b/devtools/server/actors/targets/content-process.js
@@ -0,0 +1,242 @@
+/* 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";
+
+/*
+ * Target actor for all resources in a content process of Firefox (chrome sandboxes, frame
+ * scripts, documents, etc.)
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const { Cc, Ci, Cu } = require("chrome");
+const Services = require("Services");
+
+const { ThreadActor } = require("devtools/server/actors/thread");
+const { WebConsoleActor } = require("devtools/server/actors/webconsole");
+const makeDebugger = require("devtools/server/actors/utils/make-debugger");
+const { Pool } = require("devtools/shared/protocol");
+const { assert } = require("devtools/shared/DevToolsUtils");
+const {
+ SourcesManager,
+} = require("devtools/server/actors/utils/sources-manager");
+const { Actor } = require("devtools/shared/protocol");
+const {
+ contentProcessTargetSpec,
+} = require("devtools/shared/specs/targets/content-process");
+const Targets = require("devtools/server/actors/targets/index");
+const Resources = require("devtools/server/actors/resources/index");
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+loader.lazyRequireGetter(
+ this,
+ "WorkerDescriptorActorList",
+ "devtools/server/actors/worker/worker-descriptor-actor-list",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "MemoryActor",
+ "devtools/server/actors/memory",
+ true
+);
+
+const ContentProcessTargetActor = TargetActorMixin(
+ Targets.TYPES.PROCESS,
+ contentProcessTargetSpec,
+ {
+ initialize: function(connection) {
+ Actor.prototype.initialize.call(this, connection);
+ this.conn = connection;
+ this.threadActor = null;
+
+ // Use a see-everything debugger
+ this.makeDebugger = makeDebugger.bind(null, {
+ findDebuggees: dbg => dbg.findAllGlobals(),
+ shouldAddNewGlobalAsDebuggee: global => true,
+ });
+
+ const sandboxPrototype = {
+ get tabs() {
+ return Array.from(
+ Services.ww.getWindowEnumerator(),
+ win => win.docShell.messageManager
+ );
+ },
+ };
+
+ // Scope into which the webconsole executes:
+ // A sandbox with chrome privileges with a `tabs` getter.
+ const systemPrincipal = Cc[
+ "@mozilla.org/systemprincipal;1"
+ ].createInstance(Ci.nsIPrincipal);
+ const sandbox = Cu.Sandbox(systemPrincipal, {
+ sandboxPrototype,
+ wantGlobalProperties: ["ChromeUtils"],
+ });
+ this._consoleScope = sandbox;
+
+ this._workerList = null;
+ this._workerDescriptorActorPool = null;
+ this._onWorkerListChanged = this._onWorkerListChanged.bind(this);
+
+ // Try to destroy the Content Process Target when the content process shuts down.
+ // The parent process can't communicate during shutdown as the communication channel
+ // is already down (message manager or JS Window Actor API).
+ // So that we have to observe to some event fired from this process.
+ // While such cleanup doesn't sound ultimately necessary (the process will be completely destroyed)
+ // mochitests are asserting that there is no leaks during process shutdown.
+ // Do not override destroy as Protocol.js may override it when calling destroy,
+ // and we won't be able to call removeObserver correctly.
+ this.destroyObserver = this.destroy.bind(this);
+ Services.obs.addObserver(this.destroyObserver, "xpcom-shutdown");
+ },
+
+ get isRootActor() {
+ return true;
+ },
+
+ get exited() {
+ return !this._contextPool;
+ },
+
+ get url() {
+ return undefined;
+ },
+
+ get window() {
+ return this._consoleScope;
+ },
+
+ get sourcesManager() {
+ if (!this._sourcesManager) {
+ assert(
+ this.threadActor,
+ "threadActor should exist when creating SourcesManager."
+ );
+ this._sourcesManager = new SourcesManager(this.threadActor);
+ }
+ return this._sourcesManager;
+ },
+
+ /*
+ * Return a Debugger instance or create one if there is none yet
+ */
+ get dbg() {
+ if (!this._dbg) {
+ this._dbg = this.makeDebugger();
+ }
+ return this._dbg;
+ },
+
+ form: function() {
+ if (!this._consoleActor) {
+ this._consoleActor = new WebConsoleActor(this.conn, this);
+ this.manage(this._consoleActor);
+ }
+
+ if (!this.threadActor) {
+ this.threadActor = new ThreadActor(this, null);
+ this.manage(this.threadActor);
+ }
+ if (!this.memoryActor) {
+ this.memoryActor = new MemoryActor(this.conn, this);
+ this.manage(this.memoryActor);
+ }
+
+ return {
+ actor: this.actorID,
+ consoleActor: this._consoleActor.actorID,
+ threadActor: this.threadActor.actorID,
+ memoryActor: this.memoryActor.actorID,
+ processID: Services.appinfo.processID,
+
+ traits: {
+ networkMonitor: false,
+ },
+ };
+ },
+
+ ensureWorkerList() {
+ if (!this._workerList) {
+ this._workerList = new WorkerDescriptorActorList(this.conn, {});
+ }
+ return this._workerList;
+ },
+
+ listWorkers: function() {
+ return this.ensureWorkerList()
+ .getList()
+ .then(actors => {
+ const pool = new Pool(this.conn, "workers");
+ for (const actor of actors) {
+ pool.manage(actor);
+ }
+
+ // Do not destroy the pool before transfering ownership to the newly created
+ // pool, so that we do not accidentally destroy actors that are still in use.
+ if (this._workerDescriptorActorPool) {
+ this._workerDescriptorActorPool.destroy();
+ }
+
+ this._workerDescriptorActorPool = pool;
+ this._workerList.onListChanged = this._onWorkerListChanged;
+
+ return {
+ from: this.actorID,
+ workers: actors,
+ };
+ });
+ },
+
+ _onWorkerListChanged: function() {
+ this.conn.send({ from: this.actorID, type: "workerListChanged" });
+ this._workerList.onListChanged = null;
+ },
+
+ pauseMatchingServiceWorkers(request) {
+ this.ensureWorkerList().workerPauser.setPauseServiceWorkers(
+ request.origin
+ );
+ },
+
+ destroy: function() {
+ if (this.isDestroyed()) {
+ return;
+ }
+ Resources.unwatchAllTargetResources(this);
+
+ // Notify the client that this target is being destroyed.
+ // So that we can destroy the target front and all its children.
+ this.emit("tabDetached");
+
+ Actor.prototype.destroy.call(this);
+
+ if (this.threadActor) {
+ this.threadActor = null;
+ }
+
+ // Tell the live lists we aren't watching any more.
+ if (this._workerList) {
+ this._workerList.destroy();
+ this._workerList = null;
+ }
+
+ if (this._sourcesManager) {
+ this._sourcesManager.destroy();
+ this._sourcesManager = null;
+ }
+
+ if (this._dbg) {
+ this._dbg.disable();
+ this._dbg = null;
+ }
+
+ Services.obs.removeObserver(this.destroyObserver, "xpcom-shutdown");
+ },
+ }
+);
+
+exports.ContentProcessTargetActor = ContentProcessTargetActor;
diff --git a/devtools/server/actors/targets/frame.js b/devtools/server/actors/targets/frame.js
new file mode 100644
index 0000000000..cd9d97f026
--- /dev/null
+++ b/devtools/server/actors/targets/frame.js
@@ -0,0 +1,66 @@
+/* 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";
+
+/*
+ * Target actor for a frame / docShell in the content process (where the actual
+ * content lives).
+ *
+ * This actor extends BrowsingContextTargetActor.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+var {
+ BrowsingContextTargetActor,
+ browsingContextTargetPrototype,
+} = require("devtools/server/actors/targets/browsing-context");
+
+const { extend } = require("devtools/shared/extend");
+const { frameTargetSpec } = require("devtools/shared/specs/targets/frame");
+const Targets = require("devtools/server/actors/targets/index");
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+/**
+ * Protocol.js expects only the prototype object, and does not maintain the prototype
+ * chain when it constructs the ActorClass. For this reason we are using `extend` to
+ * maintain the properties of BrowsingContextTargetActor.prototype
+ */
+const frameTargetPrototype = extend({}, browsingContextTargetPrototype);
+
+/**
+ * Target actor for a frame / docShell in the content process.
+ *
+ * @param connection DevToolsServerConnection
+ * The conection to the client.
+ * @param docShell nsIDocShell
+ * The |docShell| for the debugged frame.
+ * @param options Object
+ * See BrowsingContextTargetActor.initialize doc.
+ */
+frameTargetPrototype.initialize = function(connection, docShell, options) {
+ BrowsingContextTargetActor.prototype.initialize.call(
+ this,
+ connection,
+ docShell,
+ options
+ );
+
+ this.traits.reconfigure = false;
+};
+
+Object.defineProperty(frameTargetPrototype, "title", {
+ get: function() {
+ return this.window.document.title;
+ },
+ enumerable: true,
+ configurable: true,
+});
+
+exports.FrameTargetActor = TargetActorMixin(
+ Targets.TYPES.FRAME,
+ frameTargetSpec,
+ frameTargetPrototype
+);
diff --git a/devtools/server/actors/targets/index.js b/devtools/server/actors/targets/index.js
new file mode 100644
index 0000000000..aced448459
--- /dev/null
+++ b/devtools/server/actors/targets/index.js
@@ -0,0 +1,12 @@
+/* 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";
+
+const TYPES = {
+ FRAME: "frame",
+ PROCESS: "process",
+ WORKER: "worker",
+};
+exports.TYPES = TYPES;
diff --git a/devtools/server/actors/targets/moz.build b/devtools/server/actors/targets/moz.build
new file mode 100644
index 0000000000..acc56390c5
--- /dev/null
+++ b/devtools/server/actors/targets/moz.build
@@ -0,0 +1,18 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "browsing-context.js",
+ "chrome-window.js",
+ "content-process.js",
+ "frame.js",
+ "index.js",
+ "parent-process.js",
+ "target-actor-mixin.js",
+ "target-actor-registry.jsm",
+ "webextension.js",
+ "worker.js",
+)
diff --git a/devtools/server/actors/targets/parent-process.js b/devtools/server/actors/targets/parent-process.js
new file mode 100644
index 0000000000..8bd7f82a1d
--- /dev/null
+++ b/devtools/server/actors/targets/parent-process.js
@@ -0,0 +1,165 @@
+/* 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";
+
+/*
+ * Target actor for the entire parent process.
+ *
+ * This actor extends BrowsingContextTargetActor.
+ * This actor is extended by WebExtensionTargetActor.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const { Ci } = require("chrome");
+const Services = require("Services");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const {
+ getChildDocShells,
+ BrowsingContextTargetActor,
+ browsingContextTargetPrototype,
+} = require("devtools/server/actors/targets/browsing-context");
+const makeDebugger = require("devtools/server/actors/utils/make-debugger");
+
+const { extend } = require("devtools/shared/extend");
+const {
+ parentProcessTargetSpec,
+} = require("devtools/shared/specs/targets/parent-process");
+const Targets = require("devtools/server/actors/targets/index");
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+/**
+ * Protocol.js expects only the prototype object, and does not maintain the prototype
+ * chain when it constructs the ActorClass. For this reason we are using `extend` to
+ * maintain the properties of BrowsingContextTargetActor.prototype
+ */
+const parentProcessTargetPrototype = extend({}, browsingContextTargetPrototype);
+
+/**
+ * Creates a target actor for debugging all the chrome content in the parent process.
+ * Most of the implementation is inherited from BrowsingContextTargetActor.
+ * ParentProcessTargetActor is a child of RootActor, it can be instantiated via
+ * RootActor.getProcess request. ParentProcessTargetActor exposes all target-scoped actors
+ * via its form() request, like BrowsingContextTargetActor.
+ *
+ * @param connection DevToolsServerConnection
+ * The connection to the client.
+ * @param window Window object (optional)
+ * If the upper class already knows against which window the actor should attach,
+ * it is passed as a constructor argument here.
+ */
+parentProcessTargetPrototype.initialize = function(connection, window) {
+ // Defines the default docshell selected for the target actor
+ if (!window) {
+ window = Services.wm.getMostRecentWindow(DevToolsServer.chromeWindowType);
+ }
+
+ // Default to any available top level window if there is no expected window
+ // eg when running ./mach run --chrome chrome://browser/content/aboutTabCrashed.xhtml --jsdebugger
+ if (!window) {
+ window = Services.wm.getMostRecentWindow(null);
+ }
+
+ // We really want _some_ window at least, so fallback to the hidden window if
+ // there's nothing else (such as during early startup).
+ if (!window) {
+ window = Services.appShell.hiddenDOMWindow;
+ }
+
+ BrowsingContextTargetActor.prototype.initialize.call(
+ this,
+ connection,
+ window.docShell
+ );
+
+ // This creates a Debugger instance for chrome debugging all globals.
+ this.makeDebugger = makeDebugger.bind(null, {
+ findDebuggees: dbg => dbg.findAllGlobals(),
+ shouldAddNewGlobalAsDebuggee: () => true,
+ });
+
+ // Ensure catching the creation of any new content docshell
+ this.watchNewDocShells = true;
+};
+
+parentProcessTargetPrototype.isRootActor = true;
+
+/**
+ * Getter for the list of all docshells in this targetActor
+ * @return {Array}
+ */
+Object.defineProperty(parentProcessTargetPrototype, "docShells", {
+ get: function() {
+ // Iterate over all top-level windows and all their docshells.
+ let docShells = [];
+ for (const { docShell } of Services.ww.getWindowEnumerator()) {
+ docShells = docShells.concat(getChildDocShells(docShell));
+ }
+
+ return docShells;
+ },
+});
+
+parentProcessTargetPrototype.observe = function(subject, topic, data) {
+ BrowsingContextTargetActor.prototype.observe.call(this, subject, topic, data);
+ if (!this.attached) {
+ return;
+ }
+
+ subject.QueryInterface(Ci.nsIDocShell);
+
+ if (topic == "chrome-webnavigation-create") {
+ this._onDocShellCreated(subject);
+ } else if (topic == "chrome-webnavigation-destroy") {
+ this._onDocShellDestroy(subject);
+ }
+};
+
+parentProcessTargetPrototype._attach = function() {
+ if (this.attached) {
+ return false;
+ }
+
+ BrowsingContextTargetActor.prototype._attach.call(this);
+
+ // Listen for any new/destroyed chrome docshell
+ Services.obs.addObserver(this, "chrome-webnavigation-create");
+ Services.obs.addObserver(this, "chrome-webnavigation-destroy");
+
+ // Iterate over all top-level windows.
+ for (const { docShell } of Services.ww.getWindowEnumerator()) {
+ if (docShell == this.docShell) {
+ continue;
+ }
+ this._progressListener.watch(docShell);
+ }
+ return undefined;
+};
+
+parentProcessTargetPrototype._detach = function() {
+ if (!this.attached) {
+ return false;
+ }
+
+ Services.obs.removeObserver(this, "chrome-webnavigation-create");
+ Services.obs.removeObserver(this, "chrome-webnavigation-destroy");
+
+ // Iterate over all top-level windows.
+ for (const { docShell } of Services.ww.getWindowEnumerator()) {
+ if (docShell == this.docShell) {
+ continue;
+ }
+ this._progressListener.unwatch(docShell);
+ }
+
+ return BrowsingContextTargetActor.prototype._detach.call(this);
+};
+
+exports.parentProcessTargetPrototype = parentProcessTargetPrototype;
+exports.ParentProcessTargetActor = TargetActorMixin(
+ Targets.TYPES.FRAME,
+ parentProcessTargetSpec,
+ parentProcessTargetPrototype
+);
diff --git a/devtools/server/actors/targets/target-actor-mixin.js b/devtools/server/actors/targets/target-actor-mixin.js
new file mode 100644
index 0000000000..8b989f5920
--- /dev/null
+++ b/devtools/server/actors/targets/target-actor-mixin.js
@@ -0,0 +1,121 @@
+/* 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";
+
+const { ActorClassWithSpec } = require("devtools/shared/protocol");
+
+const Resources = require("devtools/server/actors/resources/index");
+
+module.exports = function(targetType, targetActorSpec, implementation) {
+ const proto = {
+ /**
+ * Type of target, a string of Targets.TYPES.
+ * @return {string}
+ */
+ targetType,
+
+ /**
+ * Process a new data entry, which can be watched resources, breakpoints, ...
+ *
+ * @param string type
+ * The type of data to be added
+ * @param Array<Object> entries
+ * The values to be added to this type of data
+ */
+ async addWatcherDataEntry(type, entries) {
+ if (type == "resources") {
+ await this._watchTargetResources(entries);
+ } else if (type == "breakpoints") {
+ // Breakpoints require the target to be attached,
+ // mostly to have the thread actor instantiated
+ // (content process targets don't have attach method,
+ // instead they instantiate their ThreadActor immediately)
+ if (typeof this.attach == "function") {
+ this.attach();
+ }
+
+ await Promise.all(
+ entries.map(({ location, options }) =>
+ this.threadActor.setBreakpoint(location, options)
+ )
+ );
+ }
+ },
+
+ removeWatcherDataEntry(type, entries) {
+ if (type == "resources") {
+ return this._unwatchTargetResources(entries);
+ } else if (type == "breakpoints") {
+ for (const { location } of entries) {
+ this.threadActor.removeBreakpoint(location);
+ }
+ }
+
+ return Promise.resolve();
+ },
+
+ /**
+ * These two methods will create and destroy resource watchers
+ * for each resource type. This will end up calling `notifyResourceAvailable`
+ * whenever new resources are observed.
+ *
+ * We have these shortcut methods in this module, because this is called from DevToolsFrameChild
+ * which is a JSM and doesn't have a reference to a DevTools Loader.
+ */
+ _watchTargetResources(resourceTypes) {
+ return Resources.watchResources(this, resourceTypes);
+ },
+
+ _unwatchTargetResources(resourceTypes) {
+ return Resources.unwatchResources(this, resourceTypes);
+ },
+
+ /**
+ * Called by Watchers, when new resources are available.
+ *
+ * @param Array<json> resources
+ * List of all available resources. A resource is a JSON object piped over to the client.
+ * It may contain actor IDs, actor forms, to be manually marshalled by the client.
+ */
+ notifyResourceAvailable(resources) {
+ this._emitResourcesForm("resource-available-form", resources);
+ },
+
+ notifyResourceDestroyed(resources) {
+ this._emitResourcesForm("resource-destroyed-form", resources);
+ },
+
+ notifyResourceUpdated(resources) {
+ this._emitResourcesForm("resource-updated-form", resources);
+ },
+
+ /**
+ * Wrapper around emit for resource forms to bail early after destroy.
+ */
+ _emitResourcesForm(name, resources) {
+ if (resources.length === 0 || this.isDestroyed()) {
+ // Don't try to emit if the resources array is empty or the actor was
+ // destroyed.
+ return;
+ }
+ this.emit(name, resources);
+ },
+ };
+ // Use getOwnPropertyDescriptors in order to prevent calling getter from implementation
+ Object.defineProperties(
+ proto,
+ Object.getOwnPropertyDescriptors(implementation)
+ );
+ proto.initialize = function() {
+ this.notifyResourceAvailable = this.notifyResourceAvailable.bind(this);
+ this.notifyResourceDestroyed = this.notifyResourceDestroyed.bind(this);
+ this.notifyResourceUpdated = this.notifyResourceUpdated.bind(this);
+
+ if (typeof implementation.initialize == "function") {
+ implementation.initialize.apply(this, arguments);
+ }
+ };
+ return ActorClassWithSpec(targetActorSpec, proto);
+};
diff --git a/devtools/server/actors/targets/target-actor-registry.jsm b/devtools/server/actors/targets/target-actor-registry.jsm
new file mode 100644
index 0000000000..f3ba0da908
--- /dev/null
+++ b/devtools/server/actors/targets/target-actor-registry.jsm
@@ -0,0 +1,79 @@
+/* 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 EXPORTED_SYMBOLS = ["TargetActorRegistry"];
+
+// Keep track of all BrowsingContext target actors.
+// This is especially used to track the actors using Message manager connector,
+// or the ones running in the parent process.
+// Top level actors, like tab's top level target or parent process target
+// are still using message manager in order to avoid being destroyed on navigation.
+// And because of this, these actors aren't using JS Window Actor.
+const browsingContextTargetActors = new Set();
+
+var TargetActorRegistry = {
+ registerTargetActor(targetActor) {
+ browsingContextTargetActors.add(targetActor);
+ },
+
+ unregisterTargetActor(targetActor) {
+ browsingContextTargetActors.delete(targetActor);
+ },
+
+ /**
+ * Return the first target actor matching the passed browser element id. Returns null if
+ * no matching target actors could be found.
+ *
+ * @param {Integer} browserId: The browserId to retrieve targets for. Pass null to
+ * retrieve the parent process targets.
+ * @param {String} connectionPrefix: Optional prefix, in order to select only actor
+ * related to the same connection. i.e. the same client.
+ * @returns {TargetActor|null}
+ */
+ getTargetActor(browserId, connectionPrefix) {
+ return this.getTargetActors(browserId, connectionPrefix)[0] || null;
+ },
+
+ /**
+ * Return the target actors matching the passed browser element id.
+ * In some scenarios, the registry can have multiple target actors for a given
+ * browserId (e.g. the regular DevTools content toolbox + DevTools WebExtensions targets).
+ *
+ * @param {Integer} browserId: The browserId to retrieve targets for. Pass null to
+ * retrieve the parent process targets.
+ * @param {String} connectionPrefix: Optional prefix, in order to select only actor
+ * related to the same connection. i.e. the same client.
+ * @returns {Array<TargetActor>}
+ */
+ getTargetActors(browserId, connectionPrefix) {
+ const actors = [];
+ for (const actor of browsingContextTargetActors) {
+ if (
+ ((!connectionPrefix || actor.actorID.startsWith(connectionPrefix)) &&
+ actor.browserId == browserId) ||
+ (browserId === null && actor.typeName === "parentProcessTarget")
+ ) {
+ actors.push(actor);
+ }
+ }
+ return actors;
+ },
+
+ /**
+ * Return the parent process target actor. Returns null if it couldn't be found.
+ *
+ * @returns {TargetActor|null}
+ */
+ getParentProcessTargetActor() {
+ for (const actor of browsingContextTargetActors) {
+ if (actor.typeName === "parentProcessTarget") {
+ return actor;
+ }
+ }
+
+ return null;
+ },
+};
diff --git a/devtools/server/actors/targets/webextension.js b/devtools/server/actors/targets/webextension.js
new file mode 100644
index 0000000000..6262fb555f
--- /dev/null
+++ b/devtools/server/actors/targets/webextension.js
@@ -0,0 +1,430 @@
+/* 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";
+
+/*
+ * Target actor for a WebExtension add-on.
+ *
+ * This actor extends ParentProcessTargetActor.
+ *
+ * See devtools/docs/backend/actor-hierarchy.md for more details.
+ */
+
+const { extend } = require("devtools/shared/extend");
+const { Ci, Cu, Cc } = require("chrome");
+const Services = require("Services");
+
+const {
+ ParentProcessTargetActor,
+ parentProcessTargetPrototype,
+} = require("devtools/server/actors/targets/parent-process");
+const makeDebugger = require("devtools/server/actors/utils/make-debugger");
+const {
+ webExtensionTargetSpec,
+} = require("devtools/shared/specs/targets/webextension");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+
+const Targets = require("devtools/server/actors/targets/index");
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+loader.lazyRequireGetter(
+ this,
+ "unwrapDebuggerObjectGlobal",
+ "devtools/server/actors/thread",
+ true
+);
+const FALLBACK_DOC_URL =
+ "chrome://devtools/content/shared/webextension-fallback.html";
+
+/**
+ * Protocol.js expects only the prototype object, and does not maintain the prototype
+ * chain when it constructs the ActorClass. For this reason we are using `extend` to
+ * maintain the properties of BrowsingContextTargetActor.prototype
+ */
+const webExtensionTargetPrototype = extend({}, parentProcessTargetPrototype);
+
+/**
+ * Creates a target actor for debugging all the contexts associated to a target
+ * WebExtensions add-on running in a child extension process. Most of the implementation
+ * is inherited from ParentProcessTargetActor (which inherits most of its implementation
+ * from BrowsingContextTargetActor).
+ *
+ * WebExtensionTargetActor is created by a WebExtensionActor counterpart, when its
+ * parent actor's `connect` method has been called (on the listAddons RDP package),
+ * it runs in the same process that the extension is running into (which can be the main
+ * process if the extension is running in non-oop mode, or the child extension process
+ * if the extension is running in oop-mode).
+ *
+ * A WebExtensionTargetActor contains all target-scoped actors, like a regular
+ * ParentProcessTargetActor or BrowsingContextTargetActor.
+ *
+ * History lecture:
+ * - The add-on actors used to not inherit BrowsingContextTargetActor because of the
+ * different way the add-on APIs where exposed to the add-on itself, and for this reason
+ * the Addon Debugger has only a sub-set of the feature available in the Tab or in the
+ * Browser Toolbox.
+ * - In a WebExtensions add-on all the provided contexts (background, popups etc.),
+ * besides the Content Scripts which run in the content process, hooked to an existent
+ * tab, by creating a new WebExtensionActor which inherits from
+ * ParentProcessTargetActor, we can provide a full features Addon Toolbox (which is
+ * basically like a BrowserToolbox which filters the visible sources and frames to the
+ * one that are related to the target add-on).
+ * - When the WebExtensions OOP mode has been introduced, this actor has been refactored
+ * and moved from the main process to the new child extension process.
+ *
+ * @param {DevToolsServerConnection} conn
+ * The connection to the client.
+ * @param {nsIMessageSender} chromeGlobal.
+ * The chromeGlobal where this actor has been injected by the
+ * frame-connector.js connectToFrame method.
+ * @param {string} prefix
+ * the custom RDP prefix to use.
+ * @param {string} addonId
+ * the addonId of the target WebExtension.
+ */
+webExtensionTargetPrototype.initialize = function(
+ conn,
+ chromeGlobal,
+ prefix,
+ addonId
+) {
+ this.addonId = addonId;
+ this.chromeGlobal = chromeGlobal;
+
+ // Try to discovery an existent extension page to attach (which will provide the initial
+ // URL shown in the window tittle when the addon debugger is opened).
+ const extensionWindow = this._searchForExtensionWindow();
+
+ parentProcessTargetPrototype.initialize.call(this, conn, extensionWindow);
+ this._chromeGlobal = chromeGlobal;
+ this._prefix = prefix;
+
+ // Redefine the messageManager getter to return the chromeGlobal
+ // as the messageManager for this actor (which is the browser XUL
+ // element used by the parent actor running in the main process to
+ // connect to the extension process).
+ Object.defineProperty(this, "messageManager", {
+ enumerable: true,
+ configurable: true,
+ get: () => {
+ return this._chromeGlobal;
+ },
+ });
+
+ // Bind the _allowSource helper to this, it is used in the
+ // BrowsingContextTargetActor to lazily create the SourcesManager instance.
+ this._allowSource = this._allowSource.bind(this);
+ this._onParentExit = this._onParentExit.bind(this);
+
+ this._chromeGlobal.addMessageListener(
+ "debug:webext_parent_exit",
+ this._onParentExit
+ );
+
+ // Set the consoleAPIListener filtering options
+ // (retrieved and used in the related webconsole child actor).
+ this.consoleAPIListenerOptions = {
+ addonId: this.addonId,
+ };
+
+ this.aps = Cc["@mozilla.org/addons/policy-service;1"].getService(
+ Ci.nsIAddonPolicyService
+ );
+
+ // This creates a Debugger instance for debugging all the add-on globals.
+ this.makeDebugger = makeDebugger.bind(null, {
+ findDebuggees: dbg => {
+ return dbg.findAllGlobals().filter(this._shouldAddNewGlobalAsDebuggee);
+ },
+ shouldAddNewGlobalAsDebuggee: this._shouldAddNewGlobalAsDebuggee.bind(this),
+ });
+};
+
+// NOTE: This is needed to catch in the webextension webconsole all the
+// errors raised by the WebExtension internals that are not currently
+// associated with any window.
+webExtensionTargetPrototype.isRootActor = true;
+
+/**
+ * Called when the actor is removed from the connection.
+ */
+webExtensionTargetPrototype.exit = function() {
+ if (this._chromeGlobal) {
+ const chromeGlobal = this._chromeGlobal;
+ this._chromeGlobal = null;
+
+ chromeGlobal.removeMessageListener(
+ "debug:webext_parent_exit",
+ this._onParentExit
+ );
+
+ chromeGlobal.sendAsyncMessage("debug:webext_child_exit", {
+ actor: this.actorID,
+ });
+ }
+
+ this.addon = null;
+ this.addonId = null;
+
+ return ParentProcessTargetActor.prototype.exit.apply(this);
+};
+
+// Private helpers.
+
+webExtensionTargetPrototype._searchFallbackWindow = function() {
+ if (this.fallbackWindow) {
+ // Skip if there is already an existent fallback window.
+ return this.fallbackWindow;
+ }
+
+ // Set and initialize the fallbackWindow (which initially is a empty
+ // about:blank browser), this window is related to a XUL browser element
+ // specifically created for the devtools server and it is never used
+ // or navigated anywhere else.
+ this.fallbackWindow = this.chromeGlobal.content;
+ this.fallbackWindow.document.location.href = FALLBACK_DOC_URL;
+
+ return this.fallbackWindow;
+};
+
+webExtensionTargetPrototype._destroyFallbackWindow = function() {
+ if (this.fallbackWindow) {
+ this.fallbackWindow = null;
+ }
+};
+
+// Discovery an extension page to use as a default target window.
+// NOTE: This currently fail to discovery an extension page running in a
+// windowless browser when running in non-oop mode, and the background page
+// is set later using _onNewExtensionWindow.
+webExtensionTargetPrototype._searchForExtensionWindow = function() {
+ for (const window of Services.ww.getWindowEnumerator(null)) {
+ if (window.document.nodePrincipal.addonId == this.addonId) {
+ return window;
+ }
+ }
+
+ return this._searchFallbackWindow();
+};
+
+// Customized ParentProcessTargetActor/BrowsingContextTargetActor hooks.
+
+webExtensionTargetPrototype._onDocShellDestroy = function(docShell) {
+ // Stop watching this docshell (the unwatch() method will check if we
+ // started watching it before).
+ this._unwatchDocShell(docShell);
+
+ // Let the _onDocShellDestroy notify that the docShell has been destroyed.
+ const webProgress = docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ this._notifyDocShellDestroy(webProgress);
+
+ // If the destroyed docShell was the current docShell and the actor is
+ // currently attached, switch to the fallback window
+ if (this.attached && docShell == this.docShell) {
+ this._changeTopLevelDocument(this._searchForExtensionWindow());
+ }
+};
+
+webExtensionTargetPrototype._onNewExtensionWindow = function(window) {
+ if (!this.window || this.window === this.fallbackWindow) {
+ this._changeTopLevelDocument(window);
+ }
+};
+
+webExtensionTargetPrototype._attach = function() {
+ // NOTE: we need to be sure that `this.window` can return a window before calling the
+ // ParentProcessTargetActor.onAttach, or the BrowsingContextTargetActor will not be
+ // subscribed to the child doc shell updates.
+
+ if (
+ !this.window ||
+ this.window.document.nodePrincipal.addonId !== this.addonId
+ ) {
+ // Discovery an existent extension page (or fallback window) to attach.
+ this._setWindow(this._searchForExtensionWindow());
+ }
+
+ // Call ParentProcessTargetActor's _attach to listen for any new/destroyed chrome
+ // docshell.
+ ParentProcessTargetActor.prototype._attach.apply(this);
+};
+
+webExtensionTargetPrototype._detach = function() {
+ // Call ParentProcessTargetActor's _detach to unsubscribe new/destroyed chrome docshell
+ // listeners.
+ ParentProcessTargetActor.prototype._detach.apply(this);
+
+ // Stop watching for new extension windows.
+ this._destroyFallbackWindow();
+};
+
+/**
+ * Return the json details related to a docShell.
+ */
+webExtensionTargetPrototype._docShellToWindow = function(docShell) {
+ const baseWindowDetails = ParentProcessTargetActor.prototype._docShellToWindow.call(
+ this,
+ docShell
+ );
+
+ const webProgress = docShell
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIWebProgress);
+ const window = webProgress.DOMWindow;
+
+ // Collect the addonID from the document origin attributes and its sameType top level
+ // frame.
+ const addonID = window.document.nodePrincipal.addonId;
+ const sameTypeRootAddonID =
+ docShell.sameTypeRootTreeItem.domWindow.document.nodePrincipal.addonId;
+
+ return Object.assign(baseWindowDetails, {
+ addonID,
+ sameTypeRootAddonID,
+ });
+};
+
+/**
+ * Return an array of the json details related to an array/iterator of docShells.
+ */
+webExtensionTargetPrototype._docShellsToWindows = function(docshells) {
+ return ParentProcessTargetActor.prototype._docShellsToWindows
+ .call(this, docshells)
+ .filter(windowDetails => {
+ // Filter the docShells based on the addon id of the window or
+ // its sameType top level frame.
+ return (
+ windowDetails.addonID === this.addonId ||
+ windowDetails.sameTypeRootAddonID === this.addonId
+ );
+ });
+};
+
+webExtensionTargetPrototype.isExtensionWindow = function(window) {
+ return window.document.nodePrincipal.addonId == this.addonId;
+};
+
+webExtensionTargetPrototype.isExtensionWindowDescendent = function(window) {
+ // Check if the source is coming from a descendant docShell of an extension window.
+ const rootWin = window.docShell.sameTypeRootTreeItem.domWindow;
+ return this.isExtensionWindow(rootWin);
+};
+
+/**
+ * Return true if the given source is associated with this addon and should be
+ * added to the visible sources (retrieved and used by the webbrowser actor module).
+ */
+webExtensionTargetPrototype._allowSource = function(source) {
+ // Use the source.element to detect the allowed source, if any.
+ if (source.element) {
+ try {
+ const domEl = unwrapDebuggerObjectGlobal(source.element);
+ return (
+ this.isExtensionWindow(domEl.ownerGlobal) ||
+ this.isExtensionWindowDescendent(domEl.ownerGlobal)
+ );
+ } catch (e) {
+ // If the source's window is dead then the above will throw.
+ DevToolsUtils.reportException("WebExtensionTarget.allowSource", e);
+ return false;
+ }
+ }
+
+ // Fallback to check the uri if there is no source.element associated to the source.
+
+ // Retrieve the first component of source.url in the form "url1 -> url2 -> ...".
+ const url = source.url.split(" -> ").pop();
+
+ // Filter out the code introduced by evaluating code in the webconsole.
+ if (url === "debugger eval code" || url === "debugger eager eval code") {
+ return false;
+ }
+
+ let uri;
+
+ // Try to decode the url.
+ try {
+ uri = Services.io.newURI(url);
+ } catch (err) {
+ Cu.reportError(`Unexpected invalid url: ${url}`);
+ return false;
+ }
+
+ // Filter out resource and chrome sources (which are related to the loaded internals).
+ if (["resource", "chrome", "file"].includes(uri.scheme)) {
+ return false;
+ }
+
+ try {
+ const addonID = this.aps.extensionURIToAddonId(uri);
+
+ return addonID == this.addonId;
+ } catch (err) {
+ // extensionURIToAddonId raises an exception on non-extension URLs.
+ return false;
+ }
+};
+
+/**
+ * Return true if the given global is associated with this addon and should be
+ * added as a debuggee, false otherwise.
+ */
+webExtensionTargetPrototype._shouldAddNewGlobalAsDebuggee = function(
+ newGlobal
+) {
+ const global = unwrapDebuggerObjectGlobal(newGlobal);
+
+ if (global instanceof Ci.nsIDOMWindow) {
+ try {
+ global.document;
+ } catch (e) {
+ // The global might be a sandbox with a window object in its proto chain. If the
+ // window navigated away since the sandbox was created, it can throw a security
+ // exception during this property check as the sandbox no longer has access to
+ // its own proto.
+ return false;
+ }
+
+ // Change top level document as a simulated frame switching.
+ if (global.document.ownerGlobal && this.isExtensionWindow(global)) {
+ this._onNewExtensionWindow(global.document.ownerGlobal);
+ }
+
+ return (
+ global.document.ownerGlobal &&
+ this.isExtensionWindowDescendent(global.document.ownerGlobal)
+ );
+ }
+
+ try {
+ // This will fail for non-Sandbox objects, hence the try-catch block.
+ const metadata = Cu.getSandboxMetadata(global);
+ if (metadata) {
+ return metadata.addonID === this.addonId;
+ }
+ } catch (e) {
+ // Unable to retrieve the sandbox metadata.
+ }
+
+ return false;
+};
+
+// Handlers for the messages received from the parent actor.
+
+webExtensionTargetPrototype._onParentExit = function(msg) {
+ if (msg.json.actor !== this.actorID) {
+ return;
+ }
+
+ this.exit();
+};
+
+exports.WebExtensionTargetActor = TargetActorMixin(
+ Targets.TYPES.FRAME,
+ webExtensionTargetSpec,
+ webExtensionTargetPrototype
+);
diff --git a/devtools/server/actors/targets/worker.js b/devtools/server/actors/targets/worker.js
new file mode 100644
index 0000000000..22b368a41d
--- /dev/null
+++ b/devtools/server/actors/targets/worker.js
@@ -0,0 +1,114 @@
+/* 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";
+
+const { Actor } = require("devtools/shared/protocol");
+const { workerTargetSpec } = require("devtools/shared/specs/targets/worker");
+
+const { ThreadActor } = require("devtools/server/actors/thread");
+const { WebConsoleActor } = require("devtools/server/actors/webconsole");
+const Targets = require("devtools/server/actors/targets/index");
+
+const makeDebuggerUtil = require("devtools/server/actors/utils/make-debugger");
+const {
+ SourcesManager,
+} = require("devtools/server/actors/utils/sources-manager");
+
+const TargetActorMixin = require("devtools/server/actors/targets/target-actor-mixin");
+
+exports.WorkerTargetActor = TargetActorMixin(
+ Targets.TYPES.WORKER,
+ workerTargetSpec,
+ {
+ /**
+ * Target actor for a worker in the content process.
+ *
+ * @param {DevToolsServerConnection} connection: The connection to the client.
+ * @param {WorkerGlobalScope} workerGlobal: The worker global.
+ * @param {Object} workerDebuggerData: The worker debugger information
+ * @param {String} workerDebuggerData.id: The worker debugger id
+ * @param {String} workerDebuggerData.url: The worker debugger url
+ * @param {String} workerDebuggerData.type: The worker debugger type
+ */
+ initialize: function(connection, workerGlobal, workerDebuggerData) {
+ Actor.prototype.initialize.call(this, connection);
+
+ // workerGlobal is needed by the console actor for evaluations.
+ this.workerGlobal = workerGlobal;
+
+ this._workerDebuggerData = workerDebuggerData;
+ this._sourcesManager = null;
+
+ this.makeDebugger = makeDebuggerUtil.bind(null, {
+ findDebuggees: () => {
+ return [workerGlobal];
+ },
+ shouldAddNewGlobalAsDebuggee: () => true,
+ });
+ },
+
+ form() {
+ return {
+ actor: this.actorID,
+ threadActor: this.threadActor?.actorID,
+ consoleActor: this._consoleActor?.actorID,
+ id: this._workerDebuggerData.id,
+ type: this._workerDebuggerData.type,
+ url: this._workerDebuggerData.url,
+ traits: {},
+ };
+ },
+
+ attach() {
+ if (this.threadActor) {
+ return;
+ }
+
+ // needed by the console actor
+ this.threadActor = new ThreadActor(this, this.workerGlobal);
+
+ // needed by the thread actor to communicate with the console when evaluating logpoints.
+ this._consoleActor = new WebConsoleActor(this.conn, this);
+
+ this.manage(this.threadActor);
+ this.manage(this._consoleActor);
+ },
+
+ get dbg() {
+ if (!this._dbg) {
+ this._dbg = this.makeDebugger();
+ }
+ return this._dbg;
+ },
+
+ get sourcesManager() {
+ if (this._sourcesManager === null) {
+ this._sourcesManager = new SourcesManager(this.threadActor);
+ }
+
+ return this._sourcesManager;
+ },
+
+ // This is called from the ThreadActor#onAttach method
+ onThreadAttached() {
+ // This isn't an RDP event and is only listened to from startup/worker.js.
+ this.emit("worker-thread-attached");
+ },
+
+ destroy() {
+ Actor.prototype.destroy.call(this);
+
+ if (this._sourcesManager) {
+ this._sourcesManager.destroy();
+ this._sourcesManager = null;
+ }
+
+ this.workerGlobal = null;
+ this._dbg = null;
+ this._consoleActor = null;
+ this.threadActor = null;
+ },
+ }
+);
diff --git a/devtools/server/actors/thread.js b/devtools/server/actors/thread.js
new file mode 100644
index 0000000000..5c1e234380
--- /dev/null
+++ b/devtools/server/actors/thread.js
@@ -0,0 +1,2258 @@
+/* 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";
+
+// protocol.js uses objects as exceptions in order to define
+// error packets.
+/* eslint-disable no-throw-literal */
+
+const DebuggerNotificationObserver = require("DebuggerNotificationObserver");
+const Services = require("Services");
+const { Cr, Ci } = require("chrome");
+const { Pool } = require("devtools/shared/protocol/Pool");
+const { createValueGrip } = require("devtools/server/actors/object/utils");
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const Debugger = require("Debugger");
+const { assert, dumpn, reportException } = DevToolsUtils;
+const { threadSpec } = require("devtools/shared/specs/thread");
+const {
+ getAvailableEventBreakpoints,
+ eventBreakpointForNotification,
+ eventsRequireNotifications,
+ firstStatementBreakpointId,
+ makeEventBreakpointMessage,
+} = require("devtools/server/actors/utils/event-breakpoints");
+const {
+ WatchpointMap,
+} = require("devtools/server/actors/utils/watchpoint-map");
+const {
+ getDebuggerSourceURL,
+} = require("devtools/server/actors/utils/source-url");
+
+const { logEvent } = require("devtools/server/actors/utils/logEvent");
+
+loader.lazyRequireGetter(
+ this,
+ "EnvironmentActor",
+ "devtools/server/actors/environment",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "BreakpointActorMap",
+ "devtools/server/actors/utils/breakpoint-actor-map",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "PauseScopedObjectActor",
+ "devtools/server/actors/pause-scoped",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "EventLoopStack",
+ "devtools/server/actors/utils/event-loop",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["FrameActor", "getSavedFrameParent", "isValidSavedFrame"],
+ "devtools/server/actors/frame",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "HighlighterEnvironment",
+ "devtools/server/actors/highlighters",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "PausedDebuggerOverlay",
+ "devtools/server/actors/highlighters/paused-debugger",
+ true
+);
+
+const PROMISE_REACTIONS = new WeakMap();
+function cacheReactionsForFrame(frame) {
+ if (frame.asyncPromise) {
+ const reactions = frame.asyncPromise.getPromiseReactions();
+ const existingReactions = PROMISE_REACTIONS.get(frame.asyncPromise);
+ if (
+ reactions.length > 0 &&
+ (!existingReactions || reactions.length > existingReactions.length)
+ ) {
+ PROMISE_REACTIONS.set(frame.asyncPromise, reactions);
+ }
+ }
+}
+
+function createStepForReactionTracking(onStep) {
+ return function() {
+ cacheReactionsForFrame(this);
+ return onStep ? onStep.apply(this, arguments) : undefined;
+ };
+}
+
+const getAsyncParentFrame = frame => {
+ if (!frame.asyncPromise) {
+ return null;
+ }
+
+ // We support returning Frame actors for frames that are suspended
+ // at an 'await', and here we want to walk upward to look for the first
+ // frame that will be resumed when the current frame's promise resolves.
+ let reactions =
+ PROMISE_REACTIONS.get(frame.asyncPromise) ||
+ frame.asyncPromise.getPromiseReactions();
+
+ while (true) {
+ // We loop here because we may have code like:
+ //
+ // async function inner(){ debugger; }
+ //
+ // async function outer() {
+ // await Promise.resolve().then(() => inner());
+ // }
+ //
+ // where we can see that when `inner` resolves, we will resume from
+ // `outer`, even though there is a layer of promises between, and
+ // that layer could be any number of promises deep.
+ if (!(reactions[0] instanceof Debugger.Object)) {
+ break;
+ }
+
+ reactions = reactions[0].getPromiseReactions();
+ }
+
+ if (reactions[0] instanceof Debugger.Frame) {
+ return reactions[0];
+ }
+ return null;
+};
+const RESTARTED_FRAMES = new WeakSet();
+
+// Thread actor possible states:
+const STATES = {
+ // Before ThreadActor.attach is called:
+ DETACHED: "detached",
+ // After the actor is destroyed:
+ EXITED: "exited",
+
+ // States possible in between DETACHED AND EXITED:
+ // Default state, when the thread isn't paused,
+ RUNNING: "running",
+ // When paused on any type of breakpoint, or, when the client requested an interrupt.
+ PAUSED: "paused",
+};
+
+/**
+ * JSD2 actors.
+ */
+
+/**
+ * Creates a ThreadActor.
+ *
+ * ThreadActors manage a JSInspector object and manage execution/inspection
+ * of debuggees.
+ *
+ * @param aParent object
+ * This |ThreadActor|'s parent actor. It must implement the following
+ * properties:
+ * - url: The URL string of the debuggee.
+ * - window: The global window object.
+ * - preNest: Function called before entering a nested event loop.
+ * - postNest: Function called after exiting a nested event loop.
+ * - dbg: a Debugger instance that manages its globals on its own.
+ * @param aGlobal object [optional]
+ * An optional (for content debugging only) reference to the content
+ * window.
+ */
+const ThreadActor = ActorClassWithSpec(threadSpec, {
+ initialize(parent, global) {
+ Actor.prototype.initialize.call(this, parent.conn);
+ this._state = STATES.DETACHED;
+ this._frameActors = [];
+ this._parent = parent;
+ this._dbg = null;
+ this._gripDepth = 0;
+ this._threadLifetimePool = null;
+ this._parentClosed = false;
+ this._xhrBreakpoints = [];
+ this._observingNetwork = false;
+ this._activeEventBreakpoints = new Set();
+ this._activeEventPause = null;
+ this._pauseOverlay = null;
+ this._priorPause = null;
+ this._frameActorMap = new WeakMap();
+
+ this._watchpointsMap = new WatchpointMap(this);
+
+ this._options = {
+ skipBreakpoints: false,
+ };
+
+ this.breakpointActorMap = new BreakpointActorMap(this);
+
+ this._debuggerSourcesSeen = new WeakSet();
+
+ // A Set of URLs string to watch for when new sources are found by
+ // the debugger instance.
+ this._onLoadBreakpointURLs = new Set();
+
+ // A WeakMap from Debugger.Frame to an exception value which will be ignored
+ // when deciding to pause if the value is thrown by the frame. When we are
+ // pausing on exceptions then we only want to pause when the youngest frame
+ // throws a particular exception, instead of for all older frames as well.
+ this._handledFrameExceptions = new WeakMap();
+
+ this.global = global;
+
+ this.onNewSourceEvent = this.onNewSourceEvent.bind(this);
+
+ this.createCompletionGrip = this.createCompletionGrip.bind(this);
+ this.onDebuggerStatement = this.onDebuggerStatement.bind(this);
+ this.onNewScript = this.onNewScript.bind(this);
+ this.objectGrip = this.objectGrip.bind(this);
+ this.pauseObjectGrip = this.pauseObjectGrip.bind(this);
+ this._onOpeningRequest = this._onOpeningRequest.bind(this);
+ this._onNewDebuggee = this._onNewDebuggee.bind(this);
+ this._onExceptionUnwind = this._onExceptionUnwind.bind(this);
+ this._eventBreakpointListener = this._eventBreakpointListener.bind(this);
+ this._onWindowReady = this._onWindowReady.bind(this);
+ this._onWillNavigate = this._onWillNavigate.bind(this);
+ this._onNavigate = this._onNavigate.bind(this);
+
+ this._parent.on("window-ready", this._onWindowReady);
+ this._parent.on("will-navigate", this._onWillNavigate);
+ this._parent.on("navigate", this._onNavigate);
+
+ this._firstStatementBreakpoint = null;
+ this._debuggerNotificationObserver = new DebuggerNotificationObserver();
+ },
+
+ // Used by the ObjectActor to keep track of the depth of grip() calls.
+ _gripDepth: null,
+
+ get dbg() {
+ if (!this._dbg) {
+ this._dbg = this._parent.dbg;
+ // Keep the debugger disabled until a client attaches.
+ if (this._state === STATES.DETACHED) {
+ this._dbg.disable();
+ } else {
+ this._dbg.enable();
+ }
+ }
+ return this._dbg;
+ },
+
+ // Current state of the thread actor:
+ // - detached: state, before ThreadActor.attach is called,
+ // - exited: state, after the actor is destroyed,
+ // States possible in between these two states:
+ // - running: default state, when the thread isn't paused,
+ // - paused: state, when paused on any type of breakpoint, or, when the client requested an interrupt.
+ get state() {
+ return this._state;
+ },
+
+ // XXX: soon to be equivalent to !isDestroyed once the thread actor is initialized on target creation.
+ get attached() {
+ return this.state == STATES.RUNNING || this.state == STATES.PAUSED;
+ },
+
+ get threadLifetimePool() {
+ if (!this._threadLifetimePool) {
+ this._threadLifetimePool = new Pool(this.conn, "thread");
+ this._threadLifetimePool.objectActors = new WeakMap();
+ }
+ return this._threadLifetimePool;
+ },
+
+ getThreadLifetimeObject(raw) {
+ return this.threadLifetimePool.objectActors.get(raw);
+ },
+
+ createValueGrip(value) {
+ return createValueGrip(value, this.threadLifetimePool, this.objectGrip);
+ },
+
+ get sourcesManager() {
+ return this._parent.sourcesManager;
+ },
+
+ get breakpoints() {
+ return this._parent.breakpoints;
+ },
+
+ get youngestFrame() {
+ if (this.state != STATES.PAUSED) {
+ return null;
+ }
+ return this.dbg.getNewestFrame();
+ },
+
+ get skipBreakpointsOption() {
+ return (
+ this._options.skipBreakpoints ||
+ (this.insideClientEvaluation && this.insideClientEvaluation.eager)
+ );
+ },
+
+ /**
+ * Keep track of all of the nested event loops we use to pause the debuggee
+ * when we hit a breakpoint/debugger statement/etc in one place so we can
+ * resolve them when we get resume packets. We have more than one (and keep
+ * them in a stack) because we can pause within client evals.
+ */
+ _threadPauseEventLoops: null,
+ _pushThreadPause() {
+ if (!this._threadPauseEventLoops) {
+ this._threadPauseEventLoops = [];
+ }
+ const eventLoop = this._nestedEventLoops.push();
+ this._threadPauseEventLoops.push(eventLoop);
+ eventLoop.enter();
+ },
+ _popThreadPause() {
+ const eventLoop = this._threadPauseEventLoops.pop();
+ assert(eventLoop, "Should have an event loop.");
+ eventLoop.resolve();
+ },
+
+ isPaused() {
+ return this._state === STATES.PAUSED;
+ },
+
+ /**
+ * Remove all debuggees and clear out the thread's sources.
+ */
+ clearDebuggees() {
+ if (this._dbg) {
+ this.dbg.removeAllDebuggees();
+ }
+ },
+
+ /**
+ * Destroy the debugger and put the actor in the exited state.
+ *
+ * As part of destroy, we: clean up listeners, debuggees and
+ * clear actor pools associated with the lifetime of this actor.
+ */
+ destroy() {
+ dumpn("in ThreadActor.prototype.destroy");
+ if (this._state == STATES.PAUSED) {
+ this.doResume();
+ }
+
+ this.removeAllWatchpoints();
+ this._xhrBreakpoints = [];
+ this._updateNetworkObserver();
+
+ this._activeEventBreakpoints = new Set();
+ this._debuggerNotificationObserver.removeListener(
+ this._eventBreakpointListener
+ );
+
+ for (const global of this.dbg.getDebuggees()) {
+ try {
+ this._debuggerNotificationObserver.disconnect(
+ global.unsafeDereference()
+ );
+ } catch (e) {}
+ }
+
+ this._parent.off("window-ready", this._onWindowReady);
+ this._parent.off("will-navigate", this._onWillNavigate);
+ this._parent.off("navigate", this._onNavigate);
+
+ this.sourcesManager.off("newSource", this.onNewSourceEvent);
+ this.clearDebuggees();
+ this._threadLifetimePool.destroy();
+ this._threadLifetimePool = null;
+ this._dbg = null;
+ this._state = STATES.EXITED;
+
+ Actor.prototype.destroy.call(this);
+ },
+
+ // Request handlers
+ attach(options) {
+ if (this.state === STATES.EXITED) {
+ throw {
+ error: "exited",
+ message: "threadActor has exited",
+ };
+ }
+
+ if (this.state !== STATES.DETACHED) {
+ throw {
+ error: "wrongState",
+ message: "Current state is " + this.state,
+ };
+ }
+
+ this.dbg.onDebuggerStatement = this.onDebuggerStatement;
+ this.dbg.onNewScript = this.onNewScript;
+ this.dbg.onNewDebuggee = this._onNewDebuggee;
+
+ this.sourcesManager.on("newSource", this.onNewSourceEvent);
+
+ // Initialize an event loop stack. This can't be done in the constructor,
+ // because this.conn is not yet initialized by the actor pool at that time.
+ this._nestedEventLoops = new EventLoopStack({
+ thread: this,
+ });
+
+ this.dbg.enable();
+ this.reconfigure(options);
+
+ // Set everything up so that breakpoint can work
+ this._state = STATES.RUNNING;
+
+ // Notify the parent that we've finished attaching. If this is a worker
+ // thread which was paused until attaching, this will allow content to
+ // begin executing.
+ if (this._parent.onThreadAttached) {
+ this._parent.onThreadAttached();
+ }
+ if (Services.obs) {
+ // Set a wrappedJSObject property so |this| can be sent via the observer service
+ // for the xpcshell harness.
+ this.wrappedJSObject = this;
+ Services.obs.notifyObservers(this, "devtools-thread-ready");
+ }
+ },
+
+ toggleEventLogging(logEventBreakpoints) {
+ this._options.logEventBreakpoints = logEventBreakpoints;
+ return this._options.logEventBreakpoints;
+ },
+
+ get pauseOverlay() {
+ if (this._pauseOverlay) {
+ return this._pauseOverlay;
+ }
+
+ const env = new HighlighterEnvironment();
+ env.initFromTargetActor(this._parent);
+ const highlighter = new PausedDebuggerOverlay(env, {
+ resume: () => this.resume(null),
+ stepOver: () => this.resume({ type: "next" }),
+ });
+ this._pauseOverlay = highlighter;
+ return highlighter;
+ },
+
+ _canShowOverlay() {
+ // The CanvasFrameAnonymousContentHelper class we're using to create the paused overlay
+ // need to have access to a documentElement.
+ // Accept only browsing context target which exposes such element, but ignore
+ // privileged document (top level window, special about:* pages, …).
+ return (
+ // We might have access to a non-chrome window getter that is a Sandox (e.g. in the
+ // case of ContentProcessTargetActor).
+ this._parent.window?.document?.documentElement &&
+ !this._parent.window.isChromeWindow
+ );
+ },
+
+ async showOverlay() {
+ if (
+ this._options.shouldShowOverlay &&
+ this.isPaused() &&
+ this._canShowOverlay() &&
+ this._parent.on &&
+ this.pauseOverlay
+ ) {
+ const reason = this._priorPause.why.type;
+ await this.pauseOverlay.isReady;
+
+ // we might not be paused anymore.
+ if (!this.isPaused()) {
+ return;
+ }
+
+ this.pauseOverlay.show(reason);
+ }
+ },
+
+ hideOverlay() {
+ if (this._canShowOverlay() && this._pauseOverlay) {
+ this.pauseOverlay.hide();
+ }
+ },
+
+ /**
+ * Tell the thread to automatically add a breakpoint on the first line of
+ * a given file, when it is first loaded.
+ *
+ * This is currently only used by the xpcshell test harness, and unless
+ * we decide to expand the scope of this feature, we should keep it that way.
+ */
+ setBreakpointOnLoad(urls) {
+ this._onLoadBreakpointURLs = new Set(urls);
+ },
+
+ _findXHRBreakpointIndex(p, m) {
+ return this._xhrBreakpoints.findIndex(
+ ({ path, method }) => path === p && method === m
+ );
+ },
+
+ // We clear the priorPause field when a breakpoint is added or removed
+ // at the same location because we are no longer worried about pausing twice
+ // at that location (e.g. debugger statement, stepping).
+ _maybeClearPriorPause(location) {
+ if (!this._priorPause) {
+ return;
+ }
+
+ const { where } = this._priorPause.frame;
+ if (where.line === location.line && where.column === location.column) {
+ this._priorPause = null;
+ }
+ },
+
+ async setBreakpoint(location, options) {
+ const actor = this.breakpointActorMap.getOrCreateBreakpointActor(location);
+ actor.setOptions(options);
+ this._maybeClearPriorPause(location);
+
+ if (location.sourceUrl) {
+ // There can be multiple source actors for a URL if there are multiple
+ // inline sources on an HTML page.
+ const sourceActors = this.sourcesManager.getSourceActorsByURL(
+ location.sourceUrl
+ );
+ for (const sourceActor of sourceActors) {
+ await sourceActor.applyBreakpoint(actor);
+ }
+ } else {
+ const sourceActor = this.sourcesManager.getSourceActorById(
+ location.sourceId
+ );
+ if (sourceActor) {
+ await sourceActor.applyBreakpoint(actor);
+ }
+ }
+ },
+
+ removeBreakpoint(location) {
+ const actor = this.breakpointActorMap.getOrCreateBreakpointActor(location);
+ this._maybeClearPriorPause(location);
+ actor.delete();
+ },
+
+ removeXHRBreakpoint(path, method) {
+ const index = this._findXHRBreakpointIndex(path, method);
+
+ if (index >= 0) {
+ this._xhrBreakpoints.splice(index, 1);
+ }
+ return this._updateNetworkObserver();
+ },
+
+ setXHRBreakpoint(path, method) {
+ // request.path is a string,
+ // If requested url contains the path, then we pause.
+ const index = this._findXHRBreakpointIndex(path, method);
+
+ if (index === -1) {
+ this._xhrBreakpoints.push({ path, method });
+ }
+ return this._updateNetworkObserver();
+ },
+
+ getAvailableEventBreakpoints() {
+ return getAvailableEventBreakpoints();
+ },
+ getActiveEventBreakpoints() {
+ return Array.from(this._activeEventBreakpoints);
+ },
+ setActiveEventBreakpoints(ids) {
+ this._activeEventBreakpoints = new Set(ids);
+
+ if (eventsRequireNotifications(ids)) {
+ this._debuggerNotificationObserver.addListener(
+ this._eventBreakpointListener
+ );
+ } else {
+ this._debuggerNotificationObserver.removeListener(
+ this._eventBreakpointListener
+ );
+ }
+
+ if (this._activeEventBreakpoints.has(firstStatementBreakpointId())) {
+ this._ensureFirstStatementBreakpointInitialized();
+
+ this._firstStatementBreakpoint.hit = frame =>
+ this._pauseAndRespondEventBreakpoint(
+ frame,
+ firstStatementBreakpointId()
+ );
+ } else if (this._firstStatementBreakpoint) {
+ // Disabling the breakpoint disables the feature as much as we need it
+ // to. We do not bother removing breakpoints from the scripts themselves
+ // here because the breakpoints will be a no-op if `hit` is `null`, and
+ // if we wanted to remove them, we'd need a way to iterate through them
+ // all, which would require us to hold strong references to them, which
+ // just isn't needed. Plus, if the user disables and then re-enables the
+ // feature again later, the breakpoints will still be there to work.
+ this._firstStatementBreakpoint.hit = null;
+ }
+ },
+
+ _ensureFirstStatementBreakpointInitialized() {
+ if (this._firstStatementBreakpoint) {
+ return;
+ }
+
+ this._firstStatementBreakpoint = { hit: null };
+ for (const script of this.dbg.findScripts()) {
+ this._maybeTrackFirstStatementBreakpoint(script);
+ }
+ },
+
+ _maybeTrackFirstStatementBreakpointForNewGlobal(global) {
+ if (this._firstStatementBreakpoint) {
+ for (const script of this.dbg.findScripts({ global })) {
+ this._maybeTrackFirstStatementBreakpoint(script);
+ }
+ }
+ },
+
+ _maybeTrackFirstStatementBreakpoint(script) {
+ if (
+ // If the feature is not enabled yet, there is nothing to do.
+ !this._firstStatementBreakpoint ||
+ // WASM files don't have a first statement.
+ script.format !== "js" ||
+ // All "top-level" scripts are non-functions, whether that's because
+ // the script is a module, a global script, or an eval or what.
+ script.isFunction
+ ) {
+ return;
+ }
+
+ const bps = script.getPossibleBreakpoints();
+
+ // Scripts aren't guaranteed to have a step start if for instance the
+ // file contains only function declarations, so in that case we try to
+ // fall back to whatever we can find.
+ let meta = bps.find(bp => bp.isStepStart) || bps[0];
+ if (!meta) {
+ // We've tried to avoid using `getAllColumnOffsets()` because the set of
+ // locations included in this list is very under-defined, but for this
+ // usecase it's not the end of the world. Maybe one day we could have an
+ // "onEnterFrame" that was scoped to a specific script to avoid this.
+ meta = script.getAllColumnOffsets()[0];
+ }
+
+ if (!meta) {
+ // Not certain that this is actually possible, but including for sanity
+ // so that we don't throw unexpectedly.
+ return;
+ }
+ script.setBreakpoint(meta.offset, this._firstStatementBreakpoint);
+ },
+
+ _onNewDebuggee(global) {
+ this._maybeTrackFirstStatementBreakpointForNewGlobal(global);
+ try {
+ this._debuggerNotificationObserver.connect(global.unsafeDereference());
+ } catch (e) {}
+ },
+
+ _updateNetworkObserver() {
+ // Workers don't have access to `Services` and even if they did, network
+ // requests are all dispatched to the main thread, so there would be
+ // nothing here to listen for. We'll need to revisit implementing
+ // XHR breakpoints for workers.
+ if (isWorker) {
+ return false;
+ }
+
+ if (this._xhrBreakpoints.length > 0 && !this._observingNetwork) {
+ this._observingNetwork = true;
+ Services.obs.addObserver(
+ this._onOpeningRequest,
+ "http-on-opening-request"
+ );
+ } else if (this._xhrBreakpoints.length === 0 && this._observingNetwork) {
+ this._observingNetwork = false;
+ Services.obs.removeObserver(
+ this._onOpeningRequest,
+ "http-on-opening-request"
+ );
+ }
+
+ return true;
+ },
+
+ _onOpeningRequest(subject) {
+ if (this.skipBreakpointsOption) {
+ return;
+ }
+
+ const channel = subject.QueryInterface(Ci.nsIHttpChannel);
+ const url = channel.URI.asciiSpec;
+ const requestMethod = channel.requestMethod;
+
+ let causeType = Ci.nsIContentPolicy.TYPE_OTHER;
+ if (channel.loadInfo) {
+ causeType = channel.loadInfo.externalContentPolicyType;
+ }
+
+ const isXHR =
+ causeType === Ci.nsIContentPolicy.TYPE_XMLHTTPREQUEST ||
+ causeType === Ci.nsIContentPolicy.TYPE_FETCH;
+
+ if (!isXHR) {
+ // We currently break only if the request is either fetch or xhr
+ return;
+ }
+
+ let shouldPause = false;
+ for (const { path, method } of this._xhrBreakpoints) {
+ if (method !== "ANY" && method !== requestMethod) {
+ continue;
+ }
+ if (url.includes(path)) {
+ shouldPause = true;
+ break;
+ }
+ }
+
+ if (shouldPause) {
+ const frame = this.dbg.getNewestFrame();
+
+ // If there is no frame, this request was dispatched by logic that isn't
+ // primarily JS, so pausing the event loop wouldn't make sense.
+ // This covers background requests like loading the initial page document,
+ // or loading favicons. This also includes requests dispatched indirectly
+ // from workers. We'll need to handle them separately in the future.
+ if (frame) {
+ this._pauseAndRespond(frame, { type: "XHR" });
+ }
+ }
+ },
+
+ reconfigure(options = {}) {
+ if (this.state == STATES.EXITED) {
+ throw {
+ error: "wrongState",
+ };
+ }
+ this._options = { ...this._options, ...options };
+
+ if ("observeAsmJS" in options) {
+ this.dbg.allowUnobservedAsmJS = !options.observeAsmJS;
+ }
+
+ if (
+ "pauseWorkersUntilAttach" in options &&
+ this._parent.pauseWorkersUntilAttach
+ ) {
+ this._parent.pauseWorkersUntilAttach(options.pauseWorkersUntilAttach);
+ }
+
+ if (options.breakpoints) {
+ for (const breakpoint of Object.values(options.breakpoints)) {
+ this.setBreakpoint(breakpoint.location, breakpoint.options);
+ }
+ }
+
+ if (options.eventBreakpoints) {
+ this.setActiveEventBreakpoints(options.eventBreakpoints);
+ }
+
+ this.maybePauseOnExceptions();
+ },
+
+ _eventBreakpointListener(notification) {
+ if (this._state === STATES.PAUSED || this._state === STATES.DETACHED) {
+ return;
+ }
+
+ const eventBreakpoint = eventBreakpointForNotification(
+ this.dbg,
+ notification
+ );
+
+ if (!this._activeEventBreakpoints.has(eventBreakpoint)) {
+ return;
+ }
+
+ if (notification.phase === "pre" && !this._activeEventPause) {
+ this._activeEventPause = this._captureDebuggerHooks();
+
+ this.dbg.onEnterFrame = this._makeEventBreakpointEnterFrame(
+ eventBreakpoint
+ );
+ } else if (notification.phase === "post" && this._activeEventPause) {
+ this._restoreDebuggerHooks(this._activeEventPause);
+ this._activeEventPause = null;
+ } else if (!notification.phase && !this._activeEventPause) {
+ const frame = this.dbg.getNewestFrame();
+ if (frame) {
+ if (this.sourcesManager.isFrameBlackBoxed(frame)) {
+ return;
+ }
+
+ this._pauseAndRespondEventBreakpoint(frame, eventBreakpoint);
+ }
+ }
+ },
+
+ _makeEventBreakpointEnterFrame(eventBreakpoint) {
+ return frame => {
+ if (this.sourcesManager.isFrameBlackBoxed(frame)) {
+ return undefined;
+ }
+
+ this._restoreDebuggerHooks(this._activeEventPause);
+ this._activeEventPause = null;
+
+ return this._pauseAndRespondEventBreakpoint(frame, eventBreakpoint);
+ };
+ },
+
+ _pauseAndRespondEventBreakpoint(frame, eventBreakpoint) {
+ if (this.skipBreakpointsOption) {
+ return undefined;
+ }
+
+ if (this._options.logEventBreakpoints) {
+ return logEvent({
+ threadActor: this,
+ frame,
+ level: "logPoint",
+ expression: `[_event]`,
+ bindings: { _event: frame.arguments[0] },
+ });
+ }
+
+ return this._pauseAndRespond(frame, {
+ type: "eventBreakpoint",
+ breakpoint: eventBreakpoint,
+ message: makeEventBreakpointMessage(eventBreakpoint),
+ });
+ },
+
+ _captureDebuggerHooks() {
+ return {
+ onEnterFrame: this.dbg.onEnterFrame,
+ onStep: this.dbg.onStep,
+ onPop: this.dbg.onPop,
+ };
+ },
+
+ _restoreDebuggerHooks(hooks) {
+ this.dbg.onEnterFrame = hooks.onEnterFrame;
+ this.dbg.onStep = hooks.onStep;
+ this.dbg.onPop = hooks.onPop;
+ },
+
+ /**
+ * Pause the debuggee, by entering a nested event loop, and return a 'paused'
+ * packet to the client.
+ *
+ * @param Debugger.Frame frame
+ * The newest debuggee frame in the stack.
+ * @param object reason
+ * An object with a 'type' property containing the reason for the pause.
+ * @param function onPacket
+ * Hook to modify the packet before it is sent. Feel free to return a
+ * promise.
+ */
+ _pauseAndRespond(frame, reason, onPacket = k => k) {
+ try {
+ const packet = this._paused(frame);
+ if (!packet) {
+ return undefined;
+ }
+
+ const {
+ sourceActor,
+ line,
+ column,
+ } = this.sourcesManager.getFrameLocation(frame);
+
+ packet.why = reason;
+
+ if (!sourceActor) {
+ // If the frame location is in a source that not pass the 'allowSource'
+ // check and thus has no actor, we do not bother pausing.
+ return undefined;
+ }
+
+ packet.frame.where = {
+ actor: sourceActor.actorID,
+ line: line,
+ column: column,
+ };
+ const pkt = onPacket(packet);
+
+ this._priorPause = pkt;
+ this.emit("paused", pkt);
+ this.showOverlay();
+ } catch (error) {
+ reportException("DBG-SERVER", error);
+ this.conn.send({
+ error: "unknownError",
+ message: error.message + "\n" + error.stack,
+ });
+ return undefined;
+ }
+
+ try {
+ this._pushThreadPause();
+ } catch (e) {
+ reportException("TA__pauseAndRespond", e);
+ }
+
+ if (this._requestedFrameRestart) {
+ return null;
+ }
+
+ // If the parent actor has been closed, terminate the debuggee script
+ // instead of continuing. Executing JS after the content window is gone is
+ // a bad idea.
+ return this._parentClosed ? null : undefined;
+ },
+
+ _makeOnEnterFrame({ pauseAndRespond }) {
+ return frame => {
+ if (this._requestedFrameRestart) {
+ return null;
+ }
+
+ // Continue forward until we get to a valid step target.
+ const { onStep, onPop } = this._makeSteppingHooks({
+ steppingType: "next",
+ });
+
+ if (this.sourcesManager.isFrameBlackBoxed(frame)) {
+ return undefined;
+ }
+
+ frame.onStep = onStep;
+ frame.onPop = onPop;
+ return undefined;
+ };
+ },
+
+ _makeOnPop({ pauseAndRespond, steppingType }) {
+ const thread = this;
+ return function(completion) {
+ if (thread._requestedFrameRestart === this) {
+ return thread.restartFrame(this);
+ }
+
+ // onPop is called when we temporarily leave an async/generator
+ if (steppingType != "finish" && (completion.await || completion.yield)) {
+ thread.suspendedFrame = this;
+ thread.dbg.onEnterFrame = undefined;
+ return undefined;
+ }
+
+ // Note that we're popping this frame; we need to watch for
+ // subsequent step events on its caller.
+ this.reportedPop = true;
+
+ // Cache the frame so that the onPop and onStep hooks are cleared
+ // on the next pause.
+ thread.suspendedFrame = this;
+
+ if (
+ steppingType != "finish" &&
+ !thread.sourcesManager.isFrameBlackBoxed(this)
+ ) {
+ const pauseAndRespValue = pauseAndRespond(this, packet =>
+ thread.createCompletionGrip(packet, completion)
+ );
+
+ // If the requested frame to restart differs from this frame, we don't
+ // need to restart it at this point.
+ if (thread._requestedFrameRestart === this) {
+ return thread.restartFrame(this);
+ }
+
+ return pauseAndRespValue;
+ }
+
+ thread._attachSteppingHooks(this, "next", completion);
+ return undefined;
+ };
+ },
+
+ restartFrame(frame) {
+ this._requestedFrameRestart = null;
+ this._priorPause = null;
+
+ if (
+ frame.type !== "call" ||
+ frame.script.isGeneratorFunction ||
+ frame.script.isAsyncFunction
+ ) {
+ return undefined;
+ }
+ RESTARTED_FRAMES.add(frame);
+
+ const completion = frame.callee.apply(frame.this, frame.arguments);
+
+ return completion;
+ },
+
+ hasMoved(frame, newType) {
+ const newLocation = this.sourcesManager.getFrameLocation(frame);
+
+ if (!this._priorPause) {
+ return true;
+ }
+
+ // Recursion/Loops makes it okay to resume and land at
+ // the same breakpoint or debugger statement.
+ // It is not okay to transition from a breakpoint to debugger statement
+ // or a step to a debugger statement.
+ const { type } = this._priorPause.why;
+
+ if (type == newType) {
+ return true;
+ }
+
+ const { line, column } = this._priorPause.frame.where;
+ return line !== newLocation.line || column !== newLocation.column;
+ },
+
+ _makeOnStep({ pauseAndRespond, startFrame, steppingType, completion }) {
+ const thread = this;
+ return function() {
+ if (thread._validFrameStepOffset(this, startFrame, this.offset)) {
+ return pauseAndRespond(this, packet =>
+ thread.createCompletionGrip(packet, completion)
+ );
+ }
+
+ return undefined;
+ };
+ },
+
+ _validFrameStepOffset(frame, startFrame, offset) {
+ const meta = frame.script.getOffsetMetadata(offset);
+
+ // Continue if:
+ // 1. the location is not a valid breakpoint position
+ // 2. the source is blackboxed
+ // 3. we have not moved since the last pause
+ if (
+ !meta.isBreakpoint ||
+ this.sourcesManager.isFrameBlackBoxed(frame) ||
+ !this.hasMoved(frame)
+ ) {
+ return false;
+ }
+
+ // Pause if:
+ // 1. the frame has changed
+ // 2. the location is a step position.
+ return frame !== startFrame || meta.isStepStart;
+ },
+
+ atBreakpointLocation(frame) {
+ const location = this.sourcesManager.getFrameLocation(frame);
+ return !!this.breakpointActorMap.get(location);
+ },
+
+ createCompletionGrip(packet, completion) {
+ if (!completion) {
+ return packet;
+ }
+
+ const createGrip = value =>
+ createValueGrip(value, this._pausePool, this.objectGrip);
+ packet.why.frameFinished = {};
+
+ if (completion.hasOwnProperty("return")) {
+ packet.why.frameFinished.return = createGrip(completion.return);
+ } else if (completion.hasOwnProperty("yield")) {
+ packet.why.frameFinished.return = createGrip(completion.yield);
+ } else if (completion.hasOwnProperty("throw")) {
+ packet.why.frameFinished.throw = createGrip(completion.throw);
+ }
+
+ return packet;
+ },
+
+ /**
+ * Define the JS hook functions for stepping.
+ */
+ _makeSteppingHooks({ steppingType, startFrame, completion }) {
+ // Bind these methods and state because some of the hooks are called
+ // with 'this' set to the current frame. Rather than repeating the
+ // binding in each _makeOnX method, just do it once here and pass it
+ // in to each function.
+ const steppingHookState = {
+ pauseAndRespond: (frame, onPacket = k => k) =>
+ this._pauseAndRespond(frame, { type: "resumeLimit" }, onPacket),
+ startFrame: startFrame || this.youngestFrame,
+ steppingType,
+ completion,
+ };
+
+ return {
+ onEnterFrame: this._makeOnEnterFrame(steppingHookState),
+ onPop: this._makeOnPop(steppingHookState),
+ onStep: this._makeOnStep(steppingHookState),
+ };
+ },
+
+ /**
+ * Handle attaching the various stepping hooks we need to attach when we
+ * receive a resume request with a resumeLimit property.
+ *
+ * @param Object { resumeLimit }
+ * The values received over the RDP.
+ * @returns A promise that resolves to true once the hooks are attached, or is
+ * rejected with an error packet.
+ */
+ async _handleResumeLimit({ resumeLimit, frameActorID }) {
+ const steppingType = resumeLimit.type;
+ if (
+ !["break", "step", "next", "finish", "restart"].includes(steppingType)
+ ) {
+ return Promise.reject({
+ error: "badParameterType",
+ message: "Unknown resumeLimit type",
+ });
+ }
+
+ let frame = this.youngestFrame;
+
+ if (frameActorID) {
+ frame = this._framesPool.getActorByID(frameActorID).frame;
+ if (!frame) {
+ throw new Error("Frame should exist in the frames pool.");
+ }
+ }
+
+ if (steppingType === "restart") {
+ if (
+ frame.type !== "call" ||
+ frame.script.isGeneratorFunction ||
+ frame.script.isAsyncFunction
+ ) {
+ return undefined;
+ }
+ this._requestedFrameRestart = frame;
+ }
+
+ return this._attachSteppingHooks(frame, steppingType, undefined);
+ },
+
+ _attachSteppingHooks(frame, steppingType, completion) {
+ // If we are stepping out of the onPop handler, we want to use "next" mode
+ // so that the parent frame's handlers behave consistently.
+ if (steppingType === "finish" && frame.reportedPop) {
+ steppingType = "next";
+ }
+
+ // If there are no more frames on the stack, use "step" mode so that we will
+ // pause on the next script to execute.
+ const stepFrame = this._getNextStepFrame(frame);
+ if (!stepFrame) {
+ steppingType = "step";
+ }
+
+ const { onEnterFrame, onPop, onStep } = this._makeSteppingHooks({
+ steppingType,
+ completion,
+ startFrame: frame,
+ });
+
+ if (steppingType === "step" || steppingType === "restart") {
+ this.dbg.onEnterFrame = onEnterFrame;
+ }
+
+ if (stepFrame) {
+ switch (steppingType) {
+ case "step":
+ case "break":
+ case "next":
+ if (stepFrame.script) {
+ if (!this.sourcesManager.isFrameBlackBoxed(stepFrame)) {
+ stepFrame.onStep = onStep;
+ }
+ }
+ // eslint-disable no-fallthrough
+ case "finish":
+ stepFrame.onStep = createStepForReactionTracking(stepFrame.onStep);
+ // eslint-disable no-fallthrough
+ case "restart":
+ stepFrame.onPop = onPop;
+ break;
+ }
+ }
+
+ return true;
+ },
+
+ /**
+ * Clear the onStep and onPop hooks for all frames on the stack.
+ */
+ _clearSteppingHooks() {
+ if (this.suspendedFrame) {
+ this.suspendedFrame.onStep = undefined;
+ this.suspendedFrame.onPop = undefined;
+ this.suspendedFrame = undefined;
+ }
+
+ let frame = this.youngestFrame;
+ if (frame?.onStack) {
+ while (frame) {
+ frame.onStep = undefined;
+ frame.onPop = undefined;
+ frame = frame.older;
+ }
+ }
+ },
+
+ /**
+ * Handle a protocol request to resume execution of the debuggee.
+ */
+ async resume(resumeLimit, frameActorID) {
+ if (this._state !== STATES.PAUSED) {
+ return {
+ error: "wrongState",
+ message:
+ "Can't resume when debuggee isn't paused. Current state is '" +
+ this._state +
+ "'",
+ state: this._state,
+ };
+ }
+
+ // In case of multiple nested event loops (due to multiple debuggers open in
+ // different tabs or multiple devtools clients connected to the same tab)
+ // only allow resumption in a LIFO order.
+ if (
+ this._nestedEventLoops.size &&
+ this._nestedEventLoops.lastPausedThreadActor &&
+ this._nestedEventLoops.lastPausedThreadActor !== this
+ ) {
+ return {
+ error: "wrongOrder",
+ message: "trying to resume in the wrong order.",
+ };
+ }
+
+ try {
+ if (resumeLimit) {
+ await this._handleResumeLimit({ resumeLimit, frameActorID });
+ } else {
+ this._clearSteppingHooks();
+ }
+
+ this.doResume({ resumeLimit });
+ return {};
+ } catch (error) {
+ return error instanceof Error
+ ? {
+ error: "unknownError",
+ message: DevToolsUtils.safeErrorString(error),
+ }
+ : // It is a known error, and the promise was rejected with an error
+ // packet.
+ error;
+ }
+ },
+
+ /**
+ * Only resume and notify necessary observers. This should be used in cases
+ * when we do not want to notify the front end of a resume, for example when
+ * we are shutting down.
+ */
+ doResume({ resumeLimit } = {}) {
+ this._state = STATES.RUNNING;
+
+ // Drop the actors in the pause actor pool.
+ this._pausePool.destroy();
+ this._pausePool = null;
+
+ this._pauseActor = null;
+ this._popThreadPause();
+
+ // Tell anyone who cares of the resume (as of now, that's the xpcshell harness and
+ // devtools-startup.js when handling the --wait-for-jsdebugger flag)
+ this.emit("resumed");
+ this.hideOverlay();
+ },
+
+ /**
+ * Spin up a nested event loop so we can synchronously resolve a promise.
+ *
+ * DON'T USE THIS UNLESS YOU ABSOLUTELY MUST! Nested event loops suck: the
+ * world's state can change out from underneath your feet because JS is no
+ * longer run-to-completion.
+ *
+ * @param p
+ * The promise we want to resolve.
+ * @returns The promise's resolution.
+ */
+ unsafeSynchronize(p) {
+ let needNest = true;
+ let eventLoop;
+ let returnVal;
+
+ p.then(resolvedVal => {
+ needNest = false;
+ returnVal = resolvedVal;
+ })
+ .catch(e => reportException("unsafeSynchronize", e))
+ .then(() => {
+ if (eventLoop) {
+ eventLoop.resolve();
+ }
+ });
+
+ if (needNest) {
+ eventLoop = this._nestedEventLoops.push();
+ eventLoop.enter();
+ }
+
+ return returnVal;
+ },
+
+ /**
+ * Set the debugging hook to pause on exceptions if configured to do so.
+ */
+ maybePauseOnExceptions() {
+ if (this._options.pauseOnExceptions) {
+ this.dbg.onExceptionUnwind = this._onExceptionUnwind;
+ } else {
+ this.dbg.onExceptionUnwind = undefined;
+ }
+ },
+
+ /**
+ * Helper method that returns the next frame when stepping.
+ */
+ _getNextStepFrame(frame) {
+ const endOfFrame = frame.reportedPop;
+ const stepFrame = endOfFrame
+ ? frame.older || getAsyncParentFrame(frame)
+ : frame;
+ if (!stepFrame || !stepFrame.script) {
+ return null;
+ }
+
+ // Skips a frame that has been restarted.
+ if (RESTARTED_FRAMES.has(stepFrame)) {
+ return this._getNextStepFrame(stepFrame.older);
+ }
+
+ return stepFrame;
+ },
+
+ frames(start, count) {
+ if (this.state !== STATES.PAUSED) {
+ return {
+ error: "wrongState",
+ message:
+ "Stack frames are only available while the debuggee is paused.",
+ };
+ }
+
+ // Find the starting frame...
+ let frame = this.youngestFrame;
+
+ const walkToParentFrame = () => {
+ if (!frame) {
+ return;
+ }
+
+ const currentFrame = frame;
+ frame = null;
+
+ if (!(currentFrame instanceof Debugger.Frame)) {
+ frame = getSavedFrameParent(this, currentFrame);
+ } else if (currentFrame.older) {
+ frame = currentFrame.older;
+ } else if (
+ this._options.shouldIncludeSavedFrames &&
+ currentFrame.olderSavedFrame
+ ) {
+ frame = currentFrame.olderSavedFrame;
+ if (frame && !isValidSavedFrame(this, frame)) {
+ frame = null;
+ }
+ } else if (
+ this._options.shouldIncludeAsyncLiveFrames &&
+ currentFrame.asyncPromise
+ ) {
+ const asyncFrame = getAsyncParentFrame(currentFrame);
+ if (asyncFrame) {
+ frame = asyncFrame;
+ }
+ }
+ };
+
+ let i = 0;
+ while (frame && i < start) {
+ walkToParentFrame();
+ i++;
+ }
+
+ // Return count frames, or all remaining frames if count is not defined.
+ const frames = [];
+ for (; frame && (!count || i < start + count); i++, walkToParentFrame()) {
+ // SavedFrame instances don't have direct Debugger.Source object. If
+ // there is an active Debugger.Source that represents the SaveFrame's
+ // source, it will have already been created in the server.
+ if (frame instanceof Debugger.Frame) {
+ const sourceActor = this.sourcesManager.createSourceActor(
+ frame.script.source
+ );
+ if (!sourceActor) {
+ continue;
+ }
+ }
+
+ if (RESTARTED_FRAMES.has(frame)) {
+ continue;
+ }
+
+ const frameActor = this._createFrameActor(frame, i);
+ frames.push(frameActor);
+ }
+
+ return { frames };
+ },
+
+ addAllSources() {
+ // Compare the sources we find with the source URLs which have been loaded
+ // in debuggee realms. Count the number of sources associated with each
+ // URL so that we can detect if an HTML file has had some inline sources
+ // collected but not all.
+ const urlMap = {};
+ for (const url of this.dbg.findSourceURLs()) {
+ if (url !== "self-hosted") {
+ urlMap[url] = 1 + (urlMap[url] || 0);
+ }
+ }
+
+ const sources = this.dbg.findSources();
+
+ for (const source of sources) {
+ this._addSource(source);
+
+ const url = getDebuggerSourceURL(source);
+ if (url) {
+ urlMap[url]--;
+ }
+ }
+
+ // Resurrect any URLs for which not all sources are accounted for.
+ for (const [url, count] of Object.entries(urlMap)) {
+ if (count > 0) {
+ this._resurrectSource(url);
+ }
+ }
+ },
+
+ sources(request) {
+ this.addAllSources();
+
+ // No need to flush the new source packets here, as we are sending the
+ // list of sources out immediately and we don't need to invoke the
+ // overhead of an RDP packet for every source right now. Let the default
+ // timeout flush the buffered packets.
+
+ return this.sourcesManager.iter().map(s => s.form());
+ },
+
+ /**
+ * Disassociate all breakpoint actors from their scripts and clear the
+ * breakpoint handlers. This method can be used when the thread actor intends
+ * to keep the breakpoint store, but needs to clear any actual breakpoints,
+ * e.g. due to a page navigation. This way the breakpoint actors' script
+ * caches won't hold on to the Debugger.Script objects leaking memory.
+ */
+ disableAllBreakpoints() {
+ for (const bpActor of this.breakpointActorMap.findActors()) {
+ bpActor.removeScripts();
+ }
+ },
+
+ removeAllWatchpoints() {
+ for (const actor of this.threadLifetimePool.poolChildren()) {
+ if (actor.typeName == "obj") {
+ actor.removeWatchpoints();
+ }
+ }
+ },
+
+ addWatchpoint(objActor, data) {
+ this._watchpointsMap.add(objActor, data);
+ },
+
+ removeWatchpoint(objActor, property) {
+ this._watchpointsMap.remove(objActor, property);
+ },
+
+ getWatchpoint(obj, property) {
+ return this._watchpointsMap.get(obj, property);
+ },
+
+ /**
+ * Handle a protocol request to pause the debuggee.
+ */
+ interrupt(when) {
+ if (this.state == STATES.EXITED) {
+ return { type: "exited" };
+ } else if (this.state == STATES.PAUSED) {
+ // TODO: return the actual reason for the existing pause.
+ this.emit("paused", {
+ why: { type: "alreadyPaused" },
+ });
+ return {};
+ } else if (this.state != STATES.RUNNING) {
+ return {
+ error: "wrongState",
+ message: "Received interrupt request in " + this.state + " state.",
+ };
+ }
+ try {
+ // If execution should pause just before the next JavaScript bytecode is
+ // executed, just set an onEnterFrame handler.
+ if (when == "onNext") {
+ const onEnterFrame = frame => {
+ this._pauseAndRespond(frame, { type: "interrupted", onNext: true });
+ };
+ this.dbg.onEnterFrame = onEnterFrame;
+
+ this.emit("willInterrupt");
+ return {};
+ }
+
+ // If execution should pause immediately, just put ourselves in the paused
+ // state.
+ const packet = this._paused();
+ if (!packet) {
+ return { error: "notInterrupted" };
+ }
+ packet.why = { type: "interrupted", onNext: false };
+
+ // Send the response to the interrupt request now (rather than
+ // returning it), because we're going to start a nested event loop
+ // here.
+ this.conn.send({ from: this.actorID, type: "interrupt" });
+ this.emit("paused", packet);
+
+ // Start a nested event loop.
+ this._pushThreadPause();
+
+ // We already sent a response to this request, don't send one
+ // now.
+ return null;
+ } catch (e) {
+ reportException("DBG-SERVER", e);
+ return { error: "notInterrupted", message: e.toString() };
+ }
+ },
+
+ _paused(frame) {
+ // We don't handle nested pauses correctly. Don't try - if we're
+ // paused, just continue running whatever code triggered the pause.
+ // We don't want to actually have nested pauses (although we
+ // have nested event loops). If code runs in the debuggee during
+ // a pause, it should cause the actor to resume (dropping
+ // pause-lifetime actors etc) and then repause when complete.
+
+ if (this.state === STATES.PAUSED) {
+ return undefined;
+ }
+
+ this._state = STATES.PAUSED;
+
+ // Clear stepping hooks.
+ this.dbg.onEnterFrame = undefined;
+ this._requestedFrameRestart = null;
+ this._clearSteppingHooks();
+
+ // Create the actor pool that will hold the pause actor and its
+ // children.
+ assert(!this._pausePool, "No pause pool should exist yet");
+ this._pausePool = new Pool(this.conn, "pause");
+
+ // Give children of the pause pool a quick link back to the
+ // thread...
+ this._pausePool.threadActor = this;
+
+ // Create the pause actor itself...
+ assert(!this._pauseActor, "No pause actor should exist yet");
+ this._pauseActor = new PauseActor(this._pausePool);
+ this._pausePool.manage(this._pauseActor);
+
+ // Update the list of frames.
+ const poppedFrames = this._updateFrames();
+
+ // Send off the paused packet and spin an event loop.
+ const packet = {
+ actor: this._pauseActor.actorID,
+ };
+
+ if (frame) {
+ packet.frame = this._createFrameActor(frame);
+ }
+
+ if (poppedFrames) {
+ packet.poppedFrames = poppedFrames;
+ }
+
+ return packet;
+ },
+
+ /**
+ * Expire frame actors for frames that have been popped.
+ *
+ * @returns A list of actor IDs whose frames have been popped.
+ */
+ _updateFrames() {
+ const popped = [];
+
+ // Create the actor pool that will hold the still-living frames.
+ const framesPool = new Pool(this.conn, "frames");
+ const frameList = [];
+
+ for (const frameActor of this._frameActors) {
+ if (frameActor.frame.onStack) {
+ framesPool.manage(frameActor);
+ frameList.push(frameActor);
+ } else {
+ popped.push(frameActor.actorID);
+ }
+ }
+
+ // Remove the old frame actor pool, this will expire
+ // any actors that weren't added to the new pool.
+ if (this._framesPool) {
+ this._framesPool.destroy();
+ }
+
+ this._frameActors = frameList;
+ this._framesPool = framesPool;
+
+ return popped;
+ },
+
+ _createFrameActor(frame, depth) {
+ let actor = this._frameActorMap.get(frame);
+ if (!actor) {
+ actor = new FrameActor(frame, this, depth);
+ this._frameActors.push(actor);
+ this._framesPool.manage(actor);
+
+ this._frameActorMap.set(frame, actor);
+ }
+ return actor;
+ },
+
+ /**
+ * Create and return an environment actor that corresponds to the provided
+ * Debugger.Environment.
+ * @param Debugger.Environment environment
+ * The lexical environment we want to extract.
+ * @param object pool
+ * The pool where the newly-created actor will be placed.
+ * @return The EnvironmentActor for environment or undefined for host
+ * functions or functions scoped to a non-debuggee global.
+ */
+ createEnvironmentActor(environment, pool) {
+ if (!environment) {
+ return undefined;
+ }
+
+ if (environment.actor) {
+ return environment.actor;
+ }
+
+ const actor = new EnvironmentActor(environment, this);
+ pool.manage(actor);
+ environment.actor = actor;
+
+ return actor;
+ },
+
+ /**
+ * Create a grip for the given debuggee object.
+ *
+ * @param value Debugger.Object
+ * The debuggee object value.
+ * @param pool Pool
+ * The actor pool where the new object actor will be added.
+ */
+ objectGrip(value, pool) {
+ if (!pool.objectActors) {
+ pool.objectActors = new WeakMap();
+ }
+
+ if (pool.objectActors.has(value)) {
+ return pool.objectActors.get(value).form();
+ }
+
+ if (this.threadLifetimePool.objectActors.has(value)) {
+ return this.threadLifetimePool.objectActors.get(value).form();
+ }
+
+ const actor = new PauseScopedObjectActor(
+ value,
+ {
+ thread: this,
+ getGripDepth: () => this._gripDepth,
+ incrementGripDepth: () => this._gripDepth++,
+ decrementGripDepth: () => this._gripDepth--,
+ createValueGrip: v => {
+ if (this._pausePool) {
+ return createValueGrip(v, this._pausePool, this.pauseObjectGrip);
+ }
+
+ return createValueGrip(v, this.threadLifetimePool, this.objectGrip);
+ },
+ createEnvironmentActor: (e, p) => this.createEnvironmentActor(e, p),
+ promote: () => this.threadObjectGrip(actor),
+ isThreadLifetimePool: () =>
+ actor.getParent() !== this.threadLifetimePool,
+ },
+ this.conn
+ );
+ pool.manage(actor);
+ pool.objectActors.set(value, actor);
+ return actor.form();
+ },
+
+ /**
+ * Create a grip for the given debuggee object with a pause lifetime.
+ *
+ * @param value Debugger.Object
+ * The debuggee object value.
+ */
+ pauseObjectGrip(value) {
+ if (!this._pausePool) {
+ throw new Error("Object grip requested while not paused.");
+ }
+
+ return this.objectGrip(value, this._pausePool);
+ },
+
+ /**
+ * Extend the lifetime of the provided object actor to thread lifetime.
+ *
+ * @param actor object
+ * The object actor.
+ */
+ threadObjectGrip(actor) {
+ this.threadLifetimePool.manage(actor);
+ this.threadLifetimePool.objectActors.set(actor.obj, actor);
+ },
+
+ _onWindowReady({ isTopLevel, isBFCache, window }) {
+ if (isTopLevel && this.state != STATES.DETACHED) {
+ this.sourcesManager.reset();
+ this.clearDebuggees();
+ this.dbg.enable();
+ // Update the global no matter if the debugger is on or off,
+ // otherwise the global will be wrong when enabled later.
+ this.global = window;
+ }
+
+ // Refresh the debuggee list when a new window object appears (top window or
+ // iframe).
+ if (this.attached) {
+ this.dbg.addDebuggees();
+ }
+
+ // BFCache navigations reuse old sources, so send existing sources to the
+ // client instead of waiting for onNewScript debugger notifications.
+ if (isBFCache) {
+ this.addAllSources();
+ }
+ },
+
+ _onWillNavigate({ isTopLevel }) {
+ if (!isTopLevel) {
+ return;
+ }
+
+ // Proceed normally only if the debuggee is not paused.
+ if (this.state == STATES.PAUSED) {
+ this.unsafeSynchronize(Promise.resolve(this.doResume()));
+ this.dbg.disable();
+ }
+
+ this.removeAllWatchpoints();
+ this.disableAllBreakpoints();
+ this.dbg.onEnterFrame = undefined;
+ },
+
+ _onNavigate() {
+ if (this.state == STATES.RUNNING) {
+ this.dbg.enable();
+ }
+ },
+
+ // JS Debugger API hooks.
+ pauseForMutationBreakpoint(
+ mutationType,
+ targetNode,
+ ancestorNode,
+ action = "" // "add" or "remove"
+ ) {
+ if (
+ !["subtreeModified", "nodeRemoved", "attributeModified"].includes(
+ mutationType
+ )
+ ) {
+ throw new Error("Unexpected mutation breakpoint type");
+ }
+
+ const frame = this.dbg.getNewestFrame();
+ if (!frame) {
+ return undefined;
+ }
+
+ if (
+ this.skipBreakpointsOption ||
+ this.sourcesManager.isFrameBlackBoxed(frame)
+ ) {
+ return undefined;
+ }
+
+ const global = (targetNode.ownerDocument || targetNode).defaultView;
+ assert(global && this.dbg.hasDebuggee(global));
+
+ const targetObj = this.dbg
+ .makeGlobalObjectReference(global)
+ .makeDebuggeeValue(targetNode);
+
+ let ancestorObj = null;
+ if (ancestorNode) {
+ ancestorObj = this.dbg
+ .makeGlobalObjectReference(global)
+ .makeDebuggeeValue(ancestorNode);
+ }
+
+ return this._pauseAndRespond(
+ frame,
+ {
+ type: "mutationBreakpoint",
+ mutationType,
+ message: `DOM Mutation: '${mutationType}'`,
+ },
+ pkt => {
+ // We have to add this here because `_pausePool` is `null` beforehand.
+ pkt.why.nodeGrip = this.objectGrip(targetObj, this._pausePool);
+ pkt.why.ancestorGrip = ancestorObj
+ ? this.objectGrip(ancestorObj, this._pausePool)
+ : null;
+ pkt.why.action = action;
+ return pkt;
+ }
+ );
+ },
+
+ /**
+ * A function that the engine calls when a debugger statement has been
+ * executed in the specified frame.
+ *
+ * @param frame Debugger.Frame
+ * The stack frame that contained the debugger statement.
+ */
+ onDebuggerStatement(frame) {
+ // Don't pause if
+ // 1. we have not moved since the last pause
+ // 2. breakpoints are disabled
+ // 3. the source is blackboxed
+ // 4. there is a breakpoint at the same location
+ if (
+ !this.hasMoved(frame, "debuggerStatement") ||
+ this.skipBreakpointsOption ||
+ this.sourcesManager.isFrameBlackBoxed(frame) ||
+ this.atBreakpointLocation(frame)
+ ) {
+ return undefined;
+ }
+
+ return this._pauseAndRespond(frame, { type: "debuggerStatement" });
+ },
+
+ skipBreakpoints(skip) {
+ this._options.skipBreakpoints = skip;
+ return { skip };
+ },
+
+ // Bug 1686485 is meant to remove usages of this request
+ // in favor direct call to `reconfigure`
+ pauseOnExceptions(pauseOnExceptions, ignoreCaughtExceptions) {
+ this.reconfigure({
+ pauseOnExceptions,
+ ignoreCaughtExceptions,
+ });
+ return {};
+ },
+
+ /**
+ * A function that the engine calls when an exception has been thrown and has
+ * propagated to the specified frame.
+ *
+ * @param youngestFrame Debugger.Frame
+ * The youngest remaining stack frame.
+ * @param value object
+ * The exception that was thrown.
+ */
+ _onExceptionUnwind(youngestFrame, value) {
+ // Ignore any reported exception if we are already paused
+ if (this.isPaused()) {
+ return undefined;
+ }
+
+ let willBeCaught = false;
+ for (let frame = youngestFrame; frame != null; frame = frame.older) {
+ if (frame.script.isInCatchScope(frame.offset)) {
+ willBeCaught = true;
+ break;
+ }
+ }
+
+ if (willBeCaught && this._options.ignoreCaughtExceptions) {
+ return undefined;
+ }
+
+ if (
+ this._handledFrameExceptions.has(youngestFrame) &&
+ this._handledFrameExceptions.get(youngestFrame) === value
+ ) {
+ return undefined;
+ }
+
+ // NS_ERROR_NO_INTERFACE exceptions are a special case in browser code,
+ // since they're almost always thrown by QueryInterface functions, and
+ // handled cleanly by native code.
+ if (!isWorker && value == Cr.NS_ERROR_NO_INTERFACE) {
+ return undefined;
+ }
+
+ // Don't pause on exceptions thrown while inside an evaluation being done on
+ // behalf of the client.
+ if (this.insideClientEvaluation) {
+ return undefined;
+ }
+
+ if (
+ this.skipBreakpointsOption ||
+ this.sourcesManager.isFrameBlackBoxed(youngestFrame)
+ ) {
+ return undefined;
+ }
+
+ // Now that we've decided to pause, ignore this exception if it's thrown by
+ // any older frames.
+ for (let frame = youngestFrame.older; frame != null; frame = frame.older) {
+ this._handledFrameExceptions.set(frame, value);
+ }
+
+ try {
+ const packet = this._paused(youngestFrame);
+ if (!packet) {
+ return undefined;
+ }
+
+ packet.why = {
+ type: "exception",
+ exception: createValueGrip(value, this._pausePool, this.objectGrip),
+ };
+ this.emit("paused", packet);
+
+ this._pushThreadPause();
+ } catch (e) {
+ reportException("TA_onExceptionUnwind", e);
+ }
+
+ return undefined;
+ },
+
+ /**
+ * A function that the engine calls when a new script has been loaded.
+ *
+ * @param script Debugger.Script
+ * The source script that has been loaded into a debuggee compartment.
+ */
+ onNewScript(script) {
+ this._addSource(script.source);
+
+ this._maybeTrackFirstStatementBreakpoint(script);
+ },
+
+ /**
+ * A function called when there's a new source from a thread actor's sources.
+ * Emits `newSource` on the thread actor.
+ *
+ * @param {SourceActor} source
+ */
+ onNewSourceEvent(source) {
+ // When this target is supported by the Watcher Actor,
+ // and we listen to SOURCE, we avoid emitting the newSource RDP event
+ // as it would be duplicated with the Resource/watchResources API.
+ // Could probably be removed once bug 1680280 is fixed.
+ if (!this._shouldEmitNewSource) {
+ return;
+ }
+
+ // Bug 1516197: New sources are likely detected due to either user
+ // interaction on the page, or devtools requests sent to the server.
+ // We use executeSoon because we don't want to block those operations
+ // by sending packets in the middle of them.
+ DevToolsUtils.executeSoon(() => {
+ if (this.isDestroyed()) {
+ return;
+ }
+ this.emit("newSource", {
+ source: source.form(),
+ });
+ });
+ },
+
+ // API used by the Watcher Actor to disable the newSource events
+ // Could probably be removed once bug 1680280 is fixed.
+ _shouldEmitNewSource: true,
+ disableNewSourceEvents() {
+ this._shouldEmitNewSource = false;
+ },
+
+ /**
+ * Add the provided source to the server cache.
+ *
+ * @param aSource Debugger.Source
+ * The source that will be stored.
+ * @returns true, if the source was added; false otherwise.
+ */
+ _addSource(source) {
+ if (!this.sourcesManager.allowSource(source)) {
+ return false;
+ }
+
+ // Preloaded WebExtension content scripts may be cached internally by
+ // ExtensionContent.jsm and ThreadActor would ignore them on a page reload
+ // because it finds them in the _debuggerSourcesSeen WeakSet,
+ // and so we also need to be sure that there is still a source actor for the source.
+ let sourceActor;
+ if (
+ this._debuggerSourcesSeen.has(source) &&
+ this.sourcesManager.hasSourceActor(source)
+ ) {
+ sourceActor = this.sourcesManager.getSourceActor(source);
+ sourceActor.resetDebuggeeScripts();
+ } else {
+ sourceActor = this.sourcesManager.createSourceActor(source);
+ }
+
+ const sourceUrl = sourceActor.url;
+ if (this._onLoadBreakpointURLs.has(sourceUrl)) {
+ // Immediately set a breakpoint on first line
+ // (note that this is only used by `./mach xpcshell-test --jsdebugger`)
+ this.setBreakpoint({ sourceUrl, line: 1 }, {});
+ // But also query asynchronously the first really breakable line
+ // as the first may not be valid and won't break.
+ (async () => {
+ const [firstLine] = await sourceActor.getBreakableLines();
+ if (firstLine != 1) {
+ this.setBreakpoint({ sourceUrl, line: firstLine }, {});
+ }
+ })();
+ }
+
+ const bpActors = this.breakpointActorMap
+ .findActors()
+ .filter(
+ actor =>
+ actor.location.sourceUrl && actor.location.sourceUrl == sourceUrl
+ );
+
+ for (const actor of bpActors) {
+ sourceActor.applyBreakpoint(actor);
+ }
+
+ this._debuggerSourcesSeen.add(source);
+ return true;
+ },
+
+ /**
+ * Create a new source by refetching the specified URL and instantiating all
+ * sources that were found in the result.
+ *
+ * @param url The URL string to fetch.
+ */
+ async _resurrectSource(url) {
+ let {
+ content,
+ contentType,
+ sourceMapURL,
+ } = await this.sourcesManager.urlContents(
+ url,
+ /* partial */ false,
+ /* canUseCache */ true
+ );
+
+ // Newlines in all sources should be normalized. Do this with HTML content
+ // to simplify the comparisons below.
+ content = content.replace(/\r\n?|\u2028|\u2029/g, "\n");
+
+ if (contentType == "text/html") {
+ // HTML files can contain any number of inline sources. We have to find
+ // all the inline sources and their start line without running any of the
+ // scripts on the page. The approach used here is approximate.
+ if (!this._parent.window) {
+ return;
+ }
+
+ // Find the offsets in the HTML at which inline scripts might start.
+ const scriptTagMatches = content.matchAll(/<script[^>]*>/gi);
+ const scriptStartOffsets = [...scriptTagMatches].map(
+ rv => rv.index + rv[0].length
+ );
+
+ // Find the script tags in this HTML page by parsing a new document from
+ // the contentand looking for its script elements.
+ const document = new DOMParser().parseFromString(content, "text/html");
+
+ // For each inline source found, see if there is a start offset for what
+ // appears to be a script tag, whose contents match the inline source.
+ const scripts = document.querySelectorAll("script");
+ for (const script of scripts) {
+ if (script.src) {
+ continue;
+ }
+
+ const text = script.innerText;
+ for (const offset of scriptStartOffsets) {
+ if (content.substring(offset, offset + text.length) == text) {
+ const allLineBreaks = content.substring(0, offset).matchAll("\n");
+ const startLine = 1 + [...allLineBreaks].length;
+ try {
+ const global = this.dbg.getDebuggees()[0];
+ this._addSource(
+ global.createSource({
+ text,
+ url,
+ startLine,
+ isScriptElement: true,
+ })
+ );
+ } catch (e) {
+ // Ignore parse errors.
+ }
+ break;
+ }
+ }
+ }
+
+ // If no scripts were found, we might have an inaccurate content type and
+ // the file is actually JavaScript. Fall through and add the entire file
+ // as the source.
+ if (scripts.length) {
+ return;
+ }
+ }
+
+ // Other files should only contain javascript, so add the file contents as
+ // the source itself.
+ try {
+ const global = this.dbg.getDebuggees()[0];
+ this._addSource(
+ global.createSource({
+ text: content,
+ url,
+ startLine: 1,
+ sourceMapURL,
+ })
+ );
+ } catch (e) {
+ // Ignore parse errors.
+ }
+ },
+
+ dumpThread() {
+ return {
+ pauseOnExceptions: this._options.pauseOnExceptions,
+ ignoreCaughtExceptions: this._options.ignoreCaughtExceptions,
+ logEventBreakpoints: this._options.logEventBreakpoints,
+ skipBreakpoints: this.skipBreakpointsOption,
+ breakpoints: this.breakpointActorMap.listKeys(),
+ };
+ },
+
+ // NOTE: dumpPools is defined in the Thread actor to avoid
+ // adding it to multiple target specs and actors.
+ dumpPools() {
+ return this.conn.dumpPools();
+ },
+
+ logLocation(prefix, frame) {
+ const loc = this.sourcesManager.getFrameLocation(frame);
+ dump(`${prefix} (${loc.line}, ${loc.column})\n`);
+ },
+});
+
+exports.ThreadActor = ThreadActor;
+
+/**
+ * Creates a PauseActor.
+ *
+ * PauseActors exist for the lifetime of a given debuggee pause. Used to
+ * scope pause-lifetime grips.
+ *
+ * @param {Pool} pool: The actor pool created for this pause.
+ */
+function PauseActor(pool) {
+ this.pool = pool;
+}
+
+PauseActor.prototype = {
+ typeName: "pause",
+};
+
+// Utility functions.
+
+/**
+ * Unwrap a global that is wrapped in a |Debugger.Object|, or if the global has
+ * become a dead object, return |undefined|.
+ *
+ * @param Debugger.Object wrappedGlobal
+ * The |Debugger.Object| which wraps a global.
+ *
+ * @returns {Object|undefined}
+ * Returns the unwrapped global object or |undefined| if unwrapping
+ * failed.
+ */
+exports.unwrapDebuggerObjectGlobal = wrappedGlobal => {
+ try {
+ // Because of bug 991399 we sometimes get nuked window references here. We
+ // just bail out in that case.
+ //
+ // Note that addon sandboxes have a DOMWindow as their prototype. So make
+ // sure that we can touch the prototype too (whatever it is), in case _it_
+ // is it a nuked window reference. We force stringification to make sure
+ // that any dead object proxies make themselves known.
+ const global = wrappedGlobal.unsafeDereference();
+ Object.getPrototypeOf(global) + "";
+ return global;
+ } catch (e) {
+ return undefined;
+ }
+};
diff --git a/devtools/server/actors/utils/accessibility.js b/devtools/server/actors/utils/accessibility.js
new file mode 100644
index 0000000000..b246988c25
--- /dev/null
+++ b/devtools/server/actors/utils/accessibility.js
@@ -0,0 +1,125 @@
+/* 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";
+
+loader.lazyRequireGetter(this, "Ci", "chrome", true);
+loader.lazyRequireGetter(this, "Services");
+loader.lazyRequireGetter(
+ this,
+ ["loadSheet", "removeSheet"],
+ "devtools/shared/layout/utils",
+ true
+);
+
+// Highlighter style used for preventing transitions and applying transparency
+// when calculating colour contrast.
+const HIGHLIGHTER_STYLES_SHEET = `data:text/css;charset=utf-8,
+* {
+ transition: none !important;
+}
+
+:-moz-devtools-highlighted {
+ color: transparent !important;
+ text-shadow: none !important;
+}`;
+
+/**
+ * Helper function that determines if nsIAccessible object is in defunct state.
+ *
+ * @param {nsIAccessible} accessible
+ * object to be tested.
+ * @return {Boolean}
+ * True if accessible object is defunct, false otherwise.
+ */
+function isDefunct(accessible) {
+ // If accessibility is disabled, safely assume that the accessible object is
+ // now dead.
+ if (!Services.appinfo.accessibilityEnabled) {
+ return true;
+ }
+
+ let defunct = false;
+
+ try {
+ const extraState = {};
+ accessible.getState({}, extraState);
+ // extraState.value is a bitmask. We are applying bitwise AND to mask out
+ // irrelevant states.
+ defunct = !!(extraState.value & Ci.nsIAccessibleStates.EXT_STATE_DEFUNCT);
+ } catch (e) {
+ defunct = true;
+ }
+
+ return defunct;
+}
+
+/**
+ * Load highlighter style sheet used for preventing transitions and
+ * applying transparency when calculating colour contrast.
+ *
+ * @param {Window} win
+ * Window where highlighting happens.
+ */
+function loadSheetForBackgroundCalculation(win) {
+ loadSheet(win, HIGHLIGHTER_STYLES_SHEET);
+}
+
+/**
+ * Unload highlighter style sheet used for preventing transitions
+ * and applying transparency when calculating colour contrast.
+ *
+ * @param {Window} win
+ * Window where highlighting was happenning.
+ */
+function removeSheetForBackgroundCalculation(win) {
+ removeSheet(win, HIGHLIGHTER_STYLES_SHEET);
+}
+
+/**
+ * Helper function that determines if web render is enabled.
+ *
+ * @param {Window} win
+ * Window to be tested.
+ * @return {Boolean}
+ * True if web render is enabled, false otherwise.
+ */
+function isWebRenderEnabled(win) {
+ try {
+ return win.windowUtils && win.windowUtils.layerManagerType === "WebRender";
+ } catch (e) {
+ // Sometimes nsIDOMWindowUtils::layerManagerType fails unexpectedly (see bug
+ // 1596428).
+ console.warn(e);
+ }
+
+ return false;
+}
+
+/**
+ * Get role attribute for an accessible object if specified for its
+ * corresponding DOMNode.
+ *
+ * @param {nsIAccessible} accessible
+ * Accessible for which to determine its role attribute value.
+ *
+ * @returns {null|String}
+ * Role attribute value if specified.
+ */
+function getAriaRoles(accessible) {
+ try {
+ return accessible.attributes.getStringProperty("xml-roles");
+ } catch (e) {
+ // No xml-roles. nsPersistentProperties throws if the attribute for a key
+ // is not found.
+ }
+
+ return null;
+}
+
+exports.getAriaRoles = getAriaRoles;
+exports.isDefunct = isDefunct;
+exports.isWebRenderEnabled = isWebRenderEnabled;
+exports.loadSheetForBackgroundCalculation = loadSheetForBackgroundCalculation;
+exports.removeSheetForBackgroundCalculation = removeSheetForBackgroundCalculation;
diff --git a/devtools/server/actors/utils/actor-registry.js b/devtools/server/actors/utils/actor-registry.js
new file mode 100644
index 0000000000..3b4a228f31
--- /dev/null
+++ b/devtools/server/actors/utils/actor-registry.js
@@ -0,0 +1,441 @@
+/* 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 { Ci } = require("chrome");
+var gRegisteredModules = Object.create(null);
+
+const ActorRegistry = {
+ // Map of global actor names to actor constructors.
+ globalActorFactories: {},
+ // Map of target-scoped actor names to actor constructors.
+ targetScopedActorFactories: {},
+ init(connections) {
+ this._connections = connections;
+ },
+
+ /**
+ * Register a CommonJS module with the devtools server.
+ * @param id string
+ * The ID of a CommonJS module.
+ * The actor is going to be registered immediately, but loaded only
+ * when a client starts sending packets to an actor with the same id.
+ *
+ * @param options object
+ * An object with 3 mandatory attributes:
+ * - prefix (string):
+ * The prefix of an actor is used to compute:
+ * - the `actorID` of each new actor instance (ex: prefix1). (See Pool.manage)
+ * - the actor name in the listTabs request. Sending a listTabs
+ * request to the root actor returns actor IDs. IDs are in
+ * dictionaries, with actor names as keys and actor IDs as values.
+ * The actor name is the prefix to which the "Actor" string is
+ * appended. So for an actor with the `console` prefix, the actor
+ * name will be `consoleActor`.
+ * - constructor (string):
+ * the name of the exported symbol to be used as the actor
+ * constructor.
+ * - type (a dictionary of booleans with following attribute names):
+ * - "global"
+ * registers a global actor instance, if true.
+ * A global actor has the root actor as its parent.
+ * - "target"
+ * registers a target-scoped actor instance, if true.
+ * A new actor will be created for each target, such as a tab.
+ */
+ registerModule(id, options) {
+ if (id in gRegisteredModules) {
+ return;
+ }
+
+ if (!options) {
+ throw new Error(
+ "ActorRegistry.registerModule requires an options argument"
+ );
+ }
+ const { prefix, constructor, type } = options;
+ if (typeof prefix !== "string") {
+ throw new Error(
+ `Lazy actor definition for '${id}' requires a string ` +
+ `'prefix' option.`
+ );
+ }
+ if (typeof constructor !== "string") {
+ throw new Error(
+ `Lazy actor definition for '${id}' requires a string ` +
+ `'constructor' option.`
+ );
+ }
+ if (!("global" in type) && !("target" in type)) {
+ throw new Error(
+ `Lazy actor definition for '${id}' requires a dictionary ` +
+ `'type' option whose attributes can be 'global' or 'target'.`
+ );
+ }
+ const name = prefix + "Actor";
+ const mod = {
+ id,
+ prefix,
+ constructorName: constructor,
+ type,
+ globalActor: type.global,
+ targetScopedActor: type.target,
+ };
+ gRegisteredModules[id] = mod;
+ if (mod.targetScopedActor) {
+ this.addTargetScopedActor(mod, name);
+ }
+ if (mod.globalActor) {
+ this.addGlobalActor(mod, name);
+ }
+ },
+
+ /**
+ * Unregister a previously-loaded CommonJS module from the devtools server.
+ */
+ unregisterModule(id) {
+ const mod = gRegisteredModules[id];
+ if (!mod) {
+ throw new Error(
+ "Tried to unregister a module that was not previously registered."
+ );
+ }
+
+ // Lazy actors
+ if (mod.targetScopedActor) {
+ this.removeTargetScopedActor(mod);
+ }
+ if (mod.globalActor) {
+ this.removeGlobalActor(mod);
+ }
+
+ delete gRegisteredModules[id];
+ },
+
+ /**
+ * Install Firefox-specific actors.
+ *
+ * /!\ Be careful when adding a new actor, especially global actors.
+ * Any new global actor will be exposed and returned by the root actor.
+ */
+ addBrowserActors() {
+ this.registerModule("devtools/server/actors/preference", {
+ prefix: "preference",
+ constructor: "PreferenceActor",
+ type: { global: true },
+ });
+ this.registerModule("devtools/server/actors/addon/addons", {
+ prefix: "addons",
+ constructor: "AddonsActor",
+ type: { global: true },
+ });
+ this.registerModule("devtools/server/actors/device", {
+ prefix: "device",
+ constructor: "DeviceActor",
+ type: { global: true },
+ });
+ this.registerModule("devtools/server/actors/heap-snapshot-file", {
+ prefix: "heapSnapshotFile",
+ constructor: "HeapSnapshotFileActor",
+ type: { global: true },
+ });
+ // Always register this as a global module, even while there is a pref turning
+ // on and off the other performance actor. This actor shouldn't conflict with
+ // the other one. These are also lazily loaded so there shouldn't be a performance
+ // impact.
+ this.registerModule("devtools/server/actors/perf", {
+ prefix: "perf",
+ constructor: "PerfActor",
+ type: { global: true },
+ });
+ /**
+ * Always register parent accessibility actor as a global module. This
+ * actor is responsible for all top level accessibility actor functionality
+ * that relies on the parent process.
+ */
+ this.registerModule(
+ "devtools/server/actors/accessibility/parent-accessibility",
+ {
+ prefix: "parentAccessibility",
+ constructor: "ParentAccessibilityActor",
+ type: { global: true },
+ }
+ );
+ },
+
+ /**
+ * Install target-scoped actors.
+ */
+ addTargetScopedActors() {
+ this.registerModule("devtools/server/actors/webconsole", {
+ prefix: "console",
+ constructor: "WebConsoleActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/inspector/inspector", {
+ prefix: "inspector",
+ constructor: "InspectorActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/style-sheets", {
+ prefix: "styleSheets",
+ constructor: "StyleSheetsActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/storage", {
+ prefix: "storage",
+ constructor: "StorageActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/memory", {
+ prefix: "memory",
+ constructor: "MemoryActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/framerate", {
+ prefix: "framerate",
+ constructor: "FramerateActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/reflow", {
+ prefix: "reflow",
+ constructor: "ReflowActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/css-properties", {
+ prefix: "cssProperties",
+ constructor: "CssPropertiesActor",
+ type: { target: true },
+ });
+ if ("nsIProfiler" in Ci) {
+ this.registerModule("devtools/server/actors/performance", {
+ prefix: "performance",
+ constructor: "PerformanceActor",
+ type: { target: true },
+ });
+ }
+ this.registerModule("devtools/server/actors/animation", {
+ prefix: "animations",
+ constructor: "AnimationsActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/emulation/responsive", {
+ prefix: "responsive",
+ constructor: "ResponsiveActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/emulation/content-viewer", {
+ prefix: "contentViewer",
+ constructor: "ContentViewerActor",
+ type: { target: true },
+ });
+ this.registerModule(
+ "devtools/server/actors/addon/webextension-inspected-window",
+ {
+ prefix: "webExtensionInspectedWindow",
+ constructor: "WebExtensionInspectedWindowActor",
+ type: { target: true },
+ }
+ );
+ this.registerModule("devtools/server/actors/accessibility/accessibility", {
+ prefix: "accessibility",
+ constructor: "AccessibilityActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/screenshot", {
+ prefix: "screenshot",
+ constructor: "ScreenshotActor",
+ type: { target: true },
+ });
+ this.registerModule("devtools/server/actors/changes", {
+ prefix: "changes",
+ constructor: "ChangesActor",
+ type: { target: true },
+ });
+ this.registerModule(
+ "devtools/server/actors/network-monitor/websocket-actor",
+ {
+ prefix: "webSocket",
+ constructor: "WebSocketActor",
+ type: { target: true },
+ }
+ );
+ this.registerModule(
+ "devtools/server/actors/network-monitor/eventsource-actor",
+ {
+ prefix: "eventSource",
+ constructor: "EventSourceActor",
+ type: { target: true },
+ }
+ );
+ this.registerModule("devtools/server/actors/manifest", {
+ prefix: "manifest",
+ constructor: "ManifestActor",
+ type: { target: true },
+ });
+ this.registerModule(
+ "devtools/server/actors/network-monitor/network-content",
+ {
+ prefix: "networkContent",
+ constructor: "NetworkContentActor",
+ type: { target: true },
+ }
+ );
+ },
+
+ /**
+ * Registers handlers for new target-scoped request types defined dynamically.
+ *
+ * Note that the name of the request type is not allowed to clash with existing protocol
+ * packet properties, like 'title', 'url' or 'actor', since that would break the protocol.
+ *
+ * @param options object
+ * - constructorName: (required)
+ * name of actor constructor, which is also used when removing the actor.
+ * One of the following:
+ * - id:
+ * module ID that contains the actor
+ * - constructorFun:
+ * a function to construct the actor
+ * @param name string
+ * The name of the new request type.
+ */
+ addTargetScopedActor(options, name) {
+ if (!name) {
+ throw Error("addTargetScopedActor requires the `name` argument");
+ }
+ if (["title", "url", "actor"].includes(name)) {
+ throw Error(name + " is not allowed");
+ }
+ if (this.targetScopedActorFactories.hasOwnProperty(name)) {
+ throw Error(name + " already exists");
+ }
+ this.targetScopedActorFactories[name] = { options, name };
+ },
+
+ /**
+ * Unregisters the handler for the specified target-scoped request type.
+ *
+ * When unregistering an existing target-scoped actor, we remove the actor factory as
+ * well as all existing instances of the actor.
+ *
+ * @param actor object, string
+ * In case of object:
+ * The `actor` object being given to related addTargetScopedActor call.
+ * In case of string:
+ * The `name` string being given to related addTargetScopedActor call.
+ */
+ removeTargetScopedActor(actorOrName) {
+ let name;
+ if (typeof actorOrName == "string") {
+ name = actorOrName;
+ } else {
+ const actor = actorOrName;
+ for (const factoryName in this.targetScopedActorFactories) {
+ const handler = this.targetScopedActorFactories[factoryName];
+ if (
+ handler.options.constructorName == actor.name ||
+ handler.options.id == actor.id
+ ) {
+ name = factoryName;
+ break;
+ }
+ }
+ }
+ if (!name) {
+ return;
+ }
+ delete this.targetScopedActorFactories[name];
+ for (const connID of Object.getOwnPropertyNames(this._connections)) {
+ // DevToolsServerConnection in child process don't have rootActor
+ if (this._connections[connID].rootActor) {
+ this._connections[connID].rootActor.removeActorByName(name);
+ }
+ }
+ },
+
+ /**
+ * Registers handlers for new browser-scoped request types defined dynamically.
+ *
+ * Note that the name of the request type is not allowed to clash with existing protocol
+ * packet properties, like 'from', 'tabs' or 'selected', since that would break the protocol.
+ *
+ * @param options object
+ * - constructorName: (required)
+ * name of actor constructor, which is also used when removing the actor.
+ * One of the following:
+ * - id:
+ * module ID that contains the actor
+ * - constructorFun:
+ * a function to construct the actor
+ * @param name string
+ * The name of the new request type.
+ */
+ addGlobalActor(options, name) {
+ if (!name) {
+ throw Error("addGlobalActor requires the `name` argument");
+ }
+ if (["from", "tabs", "selected"].includes(name)) {
+ throw Error(name + " is not allowed");
+ }
+ if (this.globalActorFactories.hasOwnProperty(name)) {
+ throw Error(name + " already exists");
+ }
+ this.globalActorFactories[name] = { options, name };
+ },
+
+ /**
+ * Unregisters the handler for the specified browser-scoped request type.
+ *
+ * When unregistering an existing global actor, we remove the actor factory as well as
+ * all existing instances of the actor.
+ *
+ * @param actor object, string
+ * In case of object:
+ * The `actor` object being given to related addGlobalActor call.
+ * In case of string:
+ * The `name` string being given to related addGlobalActor call.
+ */
+ removeGlobalActor(actorOrName) {
+ let name;
+ if (typeof actorOrName == "string") {
+ name = actorOrName;
+ } else {
+ const actor = actorOrName;
+ for (const factoryName in this.globalActorFactories) {
+ const handler = this.globalActorFactories[factoryName];
+ if (
+ handler.options.constructorName == actor.name ||
+ handler.options.id == actor.id
+ ) {
+ name = factoryName;
+ break;
+ }
+ }
+ }
+ if (!name) {
+ return;
+ }
+ delete this.globalActorFactories[name];
+ for (const connID of Object.getOwnPropertyNames(this._connections)) {
+ // DevToolsServerConnection in child process don't have rootActor
+ if (this._connections[connID].rootActor) {
+ this._connections[connID].rootActor.removeActorByName(name);
+ }
+ }
+ },
+
+ destroy() {
+ for (const id of Object.getOwnPropertyNames(gRegisteredModules)) {
+ this.unregisterModule(id);
+ }
+ gRegisteredModules = Object.create(null);
+
+ this.globalActorFactories = {};
+ this.targetScopedActorFactories = {};
+ },
+};
+
+exports.ActorRegistry = ActorRegistry;
diff --git a/devtools/server/actors/utils/breakpoint-actor-map.js b/devtools/server/actors/utils/breakpoint-actor-map.js
new file mode 100644
index 0000000000..acf8d5bf98
--- /dev/null
+++ b/devtools/server/actors/utils/breakpoint-actor-map.js
@@ -0,0 +1,72 @@
+/* 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";
+
+const { BreakpointActor } = require("devtools/server/actors/breakpoint");
+
+/**
+ * A BreakpointActorMap is a map from locations to instances of BreakpointActor.
+ */
+function BreakpointActorMap(threadActor) {
+ this._threadActor = threadActor;
+ this._actors = {};
+}
+
+BreakpointActorMap.prototype = {
+ // Get the key in the _actors table for a given breakpoint location.
+ // See also duplicate code in commands.js :(
+ _locationKey(location) {
+ const { sourceUrl, sourceId, line, column } = location;
+ return `${sourceUrl}:${sourceId}:${line}:${column}`;
+ },
+
+ /**
+ * Return all BreakpointActors in this BreakpointActorMap.
+ */
+ findActors() {
+ return Object.values(this._actors);
+ },
+
+ listKeys() {
+ return Object.keys(this._actors);
+ },
+
+ /**
+ * Return the BreakpointActor at the given location in this
+ * BreakpointActorMap.
+ *
+ * @param BreakpointLocation location
+ * The location for which the BreakpointActor should be returned.
+ *
+ * @returns BreakpointActor actor
+ * The BreakpointActor at the given location.
+ */
+ getOrCreateBreakpointActor(location) {
+ const key = this._locationKey(location);
+ if (!this._actors[key]) {
+ this._actors[key] = new BreakpointActor(this._threadActor, location);
+ }
+ return this._actors[key];
+ },
+
+ get(location) {
+ const key = this._locationKey(location);
+ return this._actors[key];
+ },
+
+ /**
+ * Delete the BreakpointActor from the given location in this
+ * BreakpointActorMap.
+ *
+ * @param BreakpointLocation location
+ * The location from which the BreakpointActor should be deleted.
+ */
+ deleteActor(location) {
+ const key = this._locationKey(location);
+ delete this._actors[key];
+ },
+};
+
+exports.BreakpointActorMap = BreakpointActorMap;
diff --git a/devtools/server/actors/utils/capture-screenshot.js b/devtools/server/actors/utils/capture-screenshot.js
new file mode 100644
index 0000000000..11deebc4d5
--- /dev/null
+++ b/devtools/server/actors/utils/capture-screenshot.js
@@ -0,0 +1,212 @@
+/* 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";
+const { Cu, Cc, Ci } = require("chrome");
+const Services = require("Services");
+const { LocalizationHelper } = require("devtools/shared/l10n");
+
+loader.lazyRequireGetter(this, "getRect", "devtools/shared/layout/utils", true);
+
+const CONTAINER_FLASHING_DURATION = 500;
+const STRINGS_URI = "devtools/shared/locales/screenshot.properties";
+const L10N = new LocalizationHelper(STRINGS_URI);
+
+// These values are used to truncate the resulting image if the captured area is bigger.
+// This is to avoid failing to produce a screenshot at all.
+// It is recommended to keep these values in sync with the corresponding screenshots addon
+// values in /browser/extensions/screenshots/build/buildSettings.js
+const MAX_IMAGE_WIDTH = 10000;
+const MAX_IMAGE_HEIGHT = 10000;
+
+/**
+ * This function is called to simulate camera effects
+ * @param object document
+ * The target document.
+ */
+function simulateCameraFlash(document) {
+ const window = document.defaultView;
+ const frames = Cu.cloneInto({ opacity: [0, 1] }, window);
+ document.documentElement.animate(frames, CONTAINER_FLASHING_DURATION);
+}
+
+/**
+ * This function simply handles the --delay argument before calling
+ * createScreenshotData
+ */
+function captureScreenshot(args, document) {
+ if (args.help) {
+ return null;
+ }
+ if (args.delay > 0) {
+ return new Promise((resolve, reject) => {
+ document.defaultView.setTimeout(() => {
+ createScreenshotDataURL(document, args).then(resolve, reject);
+ }, args.delay * 1000);
+ });
+ }
+ return createScreenshotDataURL(document, args);
+}
+
+exports.captureScreenshot = captureScreenshot;
+
+/**
+ * This does the dirty work of creating a base64 string out of an
+ * area of the browser window
+ */
+function createScreenshotDataURL(document, args) {
+ let window = document.defaultView;
+ let left = 0;
+ let top = 0;
+ let width;
+ let height;
+ const currentX = window.scrollX;
+ const currentY = window.scrollY;
+
+ let filename = getFilename(args.filename);
+
+ if (args.fullpage) {
+ // Bug 961832: Screenshot shows fixed position element in wrong
+ // position if we don't scroll to top
+ window.scrollTo(0, 0);
+ width = window.innerWidth + window.scrollMaxX - window.scrollMinX;
+ height = window.innerHeight + window.scrollMaxY - window.scrollMinY;
+ filename = filename.replace(".png", "-fullpage.png");
+ } else if (args.rawNode) {
+ window = args.rawNode.ownerGlobal;
+ ({ top, left, width, height } = getRect(window, args.rawNode, window));
+ } else if (args.selector) {
+ const node = window.document.querySelector(args.selector);
+ ({ top, left, width, height } = getRect(window, node, window));
+ } else {
+ left = window.scrollX;
+ top = window.scrollY;
+ width = window.innerWidth;
+ height = window.innerHeight;
+ }
+
+ // Only adjust for scrollbars when considering the full window
+ if (args.fullpage) {
+ const winUtils = window.windowUtils;
+ const scrollbarHeight = {};
+ const scrollbarWidth = {};
+ winUtils.getScrollbarSize(false, scrollbarWidth, scrollbarHeight);
+ width -= scrollbarWidth.value;
+ height -= scrollbarHeight.value;
+ }
+
+ // Truncate the width and height if necessary.
+ if (width > MAX_IMAGE_WIDTH || height > MAX_IMAGE_HEIGHT) {
+ width = Math.min(width, MAX_IMAGE_WIDTH);
+ height = Math.min(height, MAX_IMAGE_HEIGHT);
+ logWarningInPage(
+ L10N.getFormatStr("screenshotTruncationWarning", width, height),
+ window
+ );
+ }
+
+ const ratio = args.dpr ? args.dpr : window.devicePixelRatio;
+
+ const canvas = document.createElementNS(
+ "http://www.w3.org/1999/xhtml",
+ "canvas"
+ );
+ const ctx = canvas.getContext("2d");
+
+ const drawToCanvas = actualRatio => {
+ // Even after decreasing width, height and ratio, there may still be cases where the
+ // hardware fails at creating the image. Let's catch this so we can at least show an
+ // error message to the user.
+ try {
+ canvas.width = width * actualRatio;
+ canvas.height = height * actualRatio;
+ ctx.scale(actualRatio, actualRatio);
+ ctx.drawWindow(window, left, top, width, height, "#fff");
+ return canvas.toDataURL("image/png", "");
+ } catch (e) {
+ return null;
+ }
+ };
+
+ let data = drawToCanvas(ratio);
+ if (!data && ratio > 1.0) {
+ // If the user provided DPR or the window.devicePixelRatio was higher than 1,
+ // try again with a reduced ratio.
+ logWarningInPage(L10N.getStr("screenshotDPRDecreasedWarning"), window);
+ data = drawToCanvas(1.0);
+ }
+ if (!data) {
+ logErrorInPage(L10N.getStr("screenshotRenderingError"), window);
+ }
+
+ // See comment above on bug 961832
+ if (args.fullpage) {
+ window.scrollTo(currentX, currentY);
+ }
+
+ if (data) {
+ simulateCameraFlash(document);
+ }
+
+ return Promise.resolve({
+ destinations: [],
+ data,
+ height,
+ width,
+ filename,
+ });
+}
+
+/**
+ * We may have a filename specified in args, or we might have to generate
+ * one.
+ */
+function getFilename(defaultName) {
+ // Create a name for the file if not present
+ if (defaultName) {
+ return defaultName;
+ }
+
+ const date = new Date();
+ let dateString =
+ date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
+ dateString = dateString
+ .split("-")
+ .map(function(part) {
+ if (part.length == 1) {
+ part = "0" + part;
+ }
+ return part;
+ })
+ .join("-");
+
+ const timeString = date
+ .toTimeString()
+ .replace(/:/g, ".")
+ .split(" ")[0];
+ return (
+ L10N.getFormatStr("screenshotGeneratedFilename", dateString, timeString) +
+ ".png"
+ );
+}
+
+function logInPage(text, flags, window) {
+ const scriptError = Cc["@mozilla.org/scripterror;1"].createInstance(
+ Ci.nsIScriptError
+ );
+ scriptError.initWithWindowID(
+ text,
+ null,
+ null,
+ 0,
+ 0,
+ flags,
+ "screenshot",
+ window.windowGlobalChild.innerWindowId
+ );
+ Services.console.logMessage(scriptError);
+}
+
+const logErrorInPage = (text, window) => logInPage(text, 0, window);
+const logWarningInPage = (text, window) => logInPage(text, 1, window);
diff --git a/devtools/server/actors/utils/css-grid-utils.js b/devtools/server/actors/utils/css-grid-utils.js
new file mode 100644
index 0000000000..0211963708
--- /dev/null
+++ b/devtools/server/actors/utils/css-grid-utils.js
@@ -0,0 +1,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";
+
+const { Cu } = require("chrome");
+
+/**
+ * Returns the grid fragment array with all the grid fragment data stringifiable.
+ *
+ * @param {Object} fragments
+ * Grid fragment object.
+ * @return {Array} representation with the grid fragment data stringifiable.
+ */
+function getStringifiableFragments(fragments = []) {
+ if (fragments[0] && Cu.isDeadWrapper(fragments[0])) {
+ return {};
+ }
+
+ return fragments.map(getStringifiableFragment);
+}
+
+/**
+ * Returns a string representation of the CSS Grid data as returned by
+ * node.getGridFragments. This is useful to compare grid state at each update and redraw
+ * the highlighter if needed. It also seralizes the grid fragment data so it can be used
+ * by protocol.js.
+ *
+ * @param {Object} fragments
+ * Grid fragment object.
+ * @return {String} representation of the CSS grid fragment data.
+ */
+function stringifyGridFragments(fragments) {
+ return JSON.stringify(getStringifiableFragments(fragments));
+}
+
+function getStringifiableFragment(fragment) {
+ return {
+ areas: getStringifiableAreas(fragment.areas),
+ cols: getStringifiableDimension(fragment.cols),
+ rows: getStringifiableDimension(fragment.rows),
+ };
+}
+
+function getStringifiableAreas(areas) {
+ return [...areas].map(getStringifiableArea);
+}
+
+function getStringifiableDimension(dimension) {
+ return {
+ lines: [...dimension.lines].map(getStringifiableLine),
+ tracks: [...dimension.tracks].map(getStringifiableTrack),
+ };
+}
+
+function getStringifiableArea({
+ columnEnd,
+ columnStart,
+ name,
+ rowEnd,
+ rowStart,
+ type,
+}) {
+ return { columnEnd, columnStart, name, rowEnd, rowStart, type };
+}
+
+function getStringifiableLine({ breadth, names, number, start, type }) {
+ return { breadth, names, number, start, type };
+}
+
+function getStringifiableTrack({ breadth, start, state, type }) {
+ return { breadth, start, state, type };
+}
+
+exports.getStringifiableFragments = getStringifiableFragments;
+exports.stringifyGridFragments = stringifyGridFragments;
diff --git a/devtools/server/actors/utils/dbg-source.js b/devtools/server/actors/utils/dbg-source.js
new file mode 100644
index 0000000000..9c4111dfaa
--- /dev/null
+++ b/devtools/server/actors/utils/dbg-source.js
@@ -0,0 +1,97 @@
+/* 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";
+
+/**
+ * Get the source text offset equivalent to a given line/column pair.
+ *
+ * @param {Debugger.Source} source
+ * @param {number} line The 1-based line number.
+ * @param {number} column The 0-based column number.
+ * @returns {number} The codepoint offset into the source's text.
+ */
+function findSourceOffset(source, line, column) {
+ const offsets = getSourceLineOffsets(source);
+ const offset = offsets[line - 1];
+
+ if (offset) {
+ // Make sure that columns that technically don't exist in the line text
+ // don't cause the offset to wrap to the next line.
+ return Math.min(offset.start + column, offset.textEnd);
+ }
+
+ return line < 0 ? 0 : offsets[offsets.length - 1].end;
+}
+exports.findSourceOffset = findSourceOffset;
+
+const NEWLINE = /(\r?\n|\r|\u2028|\u2029)/g;
+const SOURCE_OFFSETS = new WeakMap();
+/**
+ * Generate and cache line information for a given source to track what
+ * text offsets mark the start and end of lines. Each entry in the array
+ * represents a line in the source text.
+ *
+ * @param {Debugger.Source} source
+ * @returns {Array<{ start, textEnd, end }>}
+ * - start - The codepoint offset of the start of the line.
+ * - textEnd - The codepoint offset just after the last non-newline character.
+ * - end - The codepoint offset of the end of the line. This will be
+ * be the same as the 'start' value of the next offset object,
+ * and this includes the newlines for the line itself, where
+ * 'textEnd' excludes newline characters.
+ */
+function getSourceLineOffsets(source) {
+ const cached = SOURCE_OFFSETS.get(source);
+ if (cached) {
+ return cached;
+ }
+
+ const { text } = source;
+
+ const lines = text.split(NEWLINE);
+
+ const offsets = [];
+ let offset = 0;
+ for (let i = 0; i < lines.length; i += 2) {
+ const line = lines[i];
+ const start = offset;
+
+ // Calculate the end codepoint offset.
+ let end = offset;
+ // eslint-disable-next-line no-unused-vars
+ for (const c of line) {
+ end++;
+ }
+ const textEnd = end;
+
+ if (i + 1 < lines.length) {
+ end += lines[i + 1].length;
+ }
+
+ offsets.push(Object.freeze({ start, textEnd, end }));
+ offset = end;
+ }
+ Object.freeze(offsets);
+
+ SOURCE_OFFSETS.set(source, offsets);
+ return offsets;
+}
+
+/**
+ * Given a target actor and a source platform internal ID,
+ * return the related SourceActor ID.
+
+ * @param TargetActor targetActor
+ * The Target Actor from which this source originates.
+ * @param String id
+ * Platform Source ID
+ * @return String
+ * The SourceActor ID
+ */
+function getActorIdForInternalSourceId(targetActor, id) {
+ const actor = targetActor.sourcesManager.getSourceActorByInternalSourceId(id);
+ return actor ? actor.actorID : null;
+}
+exports.getActorIdForInternalSourceId = getActorIdForInternalSourceId;
diff --git a/devtools/server/actors/utils/event-breakpoints.js b/devtools/server/actors/utils/event-breakpoints.js
new file mode 100644
index 0000000000..5f15eda956
--- /dev/null
+++ b/devtools/server/actors/utils/event-breakpoints.js
@@ -0,0 +1,478 @@
+/* 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";
+
+const Services = require("Services");
+
+function generalEvent(groupID, eventType) {
+ return {
+ id: `event.${groupID}.${eventType}`,
+ type: "event",
+ name: eventType,
+ message: `DOM '${eventType}' event`,
+ eventType,
+ filter: "general",
+ };
+}
+function nodeEvent(groupID, eventType) {
+ return {
+ ...generalEvent(groupID, eventType),
+ filter: "node",
+ };
+}
+function mediaNodeEvent(groupID, eventType) {
+ return {
+ ...generalEvent(groupID, eventType),
+ filter: "media",
+ };
+}
+function globalEvent(groupID, eventType) {
+ return {
+ ...generalEvent(groupID, eventType),
+ message: `Global '${eventType}' event`,
+ filter: "global",
+ };
+}
+function xhrEvent(groupID, eventType) {
+ return {
+ ...generalEvent(groupID, eventType),
+ message: `XHR '${eventType}' event`,
+ filter: "xhr",
+ };
+}
+
+function webSocketEvent(groupID, eventType) {
+ return {
+ ...generalEvent(groupID, eventType),
+ message: `WebSocket '${eventType}' event`,
+ filter: "websocket",
+ };
+}
+
+function workerEvent(eventType) {
+ return {
+ ...generalEvent("worker", eventType),
+ message: `Worker '${eventType}' event`,
+ filter: "worker",
+ };
+}
+
+function timerEvent(type, operation, name, notificationType) {
+ return {
+ id: `timer.${type}.${operation}`,
+ type: "simple",
+ name,
+ message: name,
+ notificationType,
+ };
+}
+
+function animationEvent(operation, name, notificationType) {
+ return {
+ id: `animationframe.${operation}`,
+ type: "simple",
+ name,
+ message: name,
+ notificationType,
+ };
+}
+
+const SCRIPT_FIRST_STATEMENT_BREAKPOINT = {
+ id: "script.source.firstStatement",
+ type: "script",
+ name: "Script First Statement",
+ message: "Script First Statement",
+};
+
+const AVAILABLE_BREAKPOINTS = [
+ {
+ name: "Animation",
+ items: [
+ animationEvent(
+ "request",
+ "Request Animation Frame",
+ "requestAnimationFrame"
+ ),
+ animationEvent(
+ "cancel",
+ "Cancel Animation Frame",
+ "cancelAnimationFrame"
+ ),
+ animationEvent(
+ "fire",
+ "Animation Frame fired",
+ "requestAnimationFrameCallback"
+ ),
+ ],
+ },
+ {
+ name: "Clipboard",
+ items: [
+ generalEvent("clipboard", "copy"),
+ generalEvent("clipboard", "cut"),
+ generalEvent("clipboard", "paste"),
+ generalEvent("clipboard", "beforecopy"),
+ generalEvent("clipboard", "beforecut"),
+ generalEvent("clipboard", "beforepaste"),
+ ],
+ },
+ {
+ name: "Control",
+ items: [
+ generalEvent("control", "resize"),
+ generalEvent("control", "scroll"),
+ generalEvent("control", "zoom"),
+ generalEvent("control", "focus"),
+ generalEvent("control", "blur"),
+ generalEvent("control", "select"),
+ generalEvent("control", "change"),
+ generalEvent("control", "submit"),
+ generalEvent("control", "reset"),
+ ],
+ },
+ {
+ name: "DOM Mutation",
+ items: [
+ // Deprecated DOM events.
+ nodeEvent("dom-mutation", "DOMActivate"),
+ nodeEvent("dom-mutation", "DOMFocusIn"),
+ nodeEvent("dom-mutation", "DOMFocusOut"),
+
+ // Standard DOM mutation events.
+ nodeEvent("dom-mutation", "DOMAttrModified"),
+ nodeEvent("dom-mutation", "DOMCharacterDataModified"),
+ nodeEvent("dom-mutation", "DOMNodeInserted"),
+ nodeEvent("dom-mutation", "DOMNodeInsertedIntoDocument"),
+ nodeEvent("dom-mutation", "DOMNodeRemoved"),
+ nodeEvent("dom-mutation", "DOMNodeRemovedIntoDocument"),
+ nodeEvent("dom-mutation", "DOMSubtreeModified"),
+
+ // DOM load events.
+ nodeEvent("dom-mutation", "DOMContentLoaded"),
+ ],
+ },
+ {
+ name: "Device",
+ items: [
+ globalEvent("device", "deviceorientation"),
+ globalEvent("device", "devicemotion"),
+ ],
+ },
+ {
+ name: "Drag and Drop",
+ items: [
+ generalEvent("drag-and-drop", "drag"),
+ generalEvent("drag-and-drop", "dragstart"),
+ generalEvent("drag-and-drop", "dragend"),
+ generalEvent("drag-and-drop", "dragenter"),
+ generalEvent("drag-and-drop", "dragover"),
+ generalEvent("drag-and-drop", "dragleave"),
+ generalEvent("drag-and-drop", "drop"),
+ ],
+ },
+ {
+ name: "Keyboard",
+ items: [
+ Services.prefs &&
+ Services.prefs.getBoolPref("dom.input_events.beforeinput.enabled")
+ ? generalEvent("keyboard", "beforeinput")
+ : null,
+ generalEvent("keyboard", "input"),
+ generalEvent("keyboard", "keydown"),
+ generalEvent("keyboard", "keyup"),
+ generalEvent("keyboard", "keypress"),
+ ].filter(Boolean),
+ },
+ {
+ name: "Load",
+ items: [
+ globalEvent("load", "load"),
+ // TODO: Disabled pending fixes for bug 1569775.
+ // globalEvent("load", "beforeunload"),
+ // globalEvent("load", "unload"),
+ globalEvent("load", "abort"),
+ globalEvent("load", "error"),
+ globalEvent("load", "hashchange"),
+ globalEvent("load", "popstate"),
+ ],
+ },
+ {
+ name: "Media",
+ items: [
+ mediaNodeEvent("media", "play"),
+ mediaNodeEvent("media", "pause"),
+ mediaNodeEvent("media", "playing"),
+ mediaNodeEvent("media", "canplay"),
+ mediaNodeEvent("media", "canplaythrough"),
+ mediaNodeEvent("media", "seeking"),
+ mediaNodeEvent("media", "seeked"),
+ mediaNodeEvent("media", "timeupdate"),
+ mediaNodeEvent("media", "ended"),
+ mediaNodeEvent("media", "ratechange"),
+ mediaNodeEvent("media", "durationchange"),
+ mediaNodeEvent("media", "volumechange"),
+ mediaNodeEvent("media", "loadstart"),
+ mediaNodeEvent("media", "progress"),
+ mediaNodeEvent("media", "suspend"),
+ mediaNodeEvent("media", "abort"),
+ mediaNodeEvent("media", "error"),
+ mediaNodeEvent("media", "emptied"),
+ mediaNodeEvent("media", "stalled"),
+ mediaNodeEvent("media", "loadedmetadata"),
+ mediaNodeEvent("media", "loadeddata"),
+ mediaNodeEvent("media", "waiting"),
+ ],
+ },
+ {
+ name: "Mouse",
+ items: [
+ generalEvent("mouse", "auxclick"),
+ generalEvent("mouse", "click"),
+ generalEvent("mouse", "dblclick"),
+ generalEvent("mouse", "mousedown"),
+ generalEvent("mouse", "mouseup"),
+ generalEvent("mouse", "mouseover"),
+ generalEvent("mouse", "mousemove"),
+ generalEvent("mouse", "mouseout"),
+ generalEvent("mouse", "mouseenter"),
+ generalEvent("mouse", "mouseleave"),
+ generalEvent("mouse", "mousewheel"),
+ generalEvent("mouse", "wheel"),
+ generalEvent("mouse", "contextmenu"),
+ ],
+ },
+ {
+ name: "Pointer",
+ items: [
+ generalEvent("pointer", "pointerover"),
+ generalEvent("pointer", "pointerout"),
+ generalEvent("pointer", "pointerenter"),
+ generalEvent("pointer", "pointerleave"),
+ generalEvent("pointer", "pointerdown"),
+ generalEvent("pointer", "pointerup"),
+ generalEvent("pointer", "pointermove"),
+ generalEvent("pointer", "pointercancel"),
+ generalEvent("pointer", "gotpointercapture"),
+ generalEvent("pointer", "lostpointercapture"),
+ ],
+ },
+ {
+ name: "Script",
+ items: [SCRIPT_FIRST_STATEMENT_BREAKPOINT],
+ },
+ {
+ name: "Timer",
+ items: [
+ timerEvent("timeout", "set", "setTimeout", "setTimeout"),
+ timerEvent("timeout", "clear", "clearTimeout", "clearTimeout"),
+ timerEvent("timeout", "fire", "setTimeout fired", "setTimeoutCallback"),
+ timerEvent("interval", "set", "setInterval", "setInterval"),
+ timerEvent("interval", "clear", "clearInterval", "clearInterval"),
+ timerEvent(
+ "interval",
+ "fire",
+ "setInterval fired",
+ "setIntervalCallback"
+ ),
+ ],
+ },
+ {
+ name: "Touch",
+ items: [
+ generalEvent("touch", "touchstart"),
+ generalEvent("touch", "touchmove"),
+ generalEvent("touch", "touchend"),
+ generalEvent("touch", "touchcancel"),
+ ],
+ },
+ {
+ name: "WebSocket",
+ items: [
+ webSocketEvent("websocket", "open"),
+ webSocketEvent("websocket", "message"),
+ webSocketEvent("websocket", "error"),
+ webSocketEvent("websocket", "close"),
+ ],
+ },
+ {
+ name: "Worker",
+ items: [
+ workerEvent("message"),
+ workerEvent("messageerror"),
+
+ // Service Worker events.
+ globalEvent("serviceworker", "fetch"),
+ ],
+ },
+ {
+ name: "XHR",
+ items: [
+ xhrEvent("xhr", "readystatechange"),
+ xhrEvent("xhr", "load"),
+ xhrEvent("xhr", "loadstart"),
+ xhrEvent("xhr", "loadend"),
+ xhrEvent("xhr", "abort"),
+ xhrEvent("xhr", "error"),
+ xhrEvent("xhr", "progress"),
+ xhrEvent("xhr", "timeout"),
+ ],
+ },
+];
+
+const FLAT_EVENTS = [];
+for (const category of AVAILABLE_BREAKPOINTS) {
+ for (const event of category.items) {
+ FLAT_EVENTS.push(event);
+ }
+}
+const EVENTS_BY_ID = {};
+for (const event of FLAT_EVENTS) {
+ if (EVENTS_BY_ID[event.id]) {
+ throw new Error("Duplicate event ID detected: " + event.id);
+ }
+ EVENTS_BY_ID[event.id] = event;
+}
+
+const SIMPLE_EVENTS = {};
+const DOM_EVENTS = {};
+for (const eventBP of FLAT_EVENTS) {
+ if (eventBP.type === "simple") {
+ const { notificationType } = eventBP;
+ if (SIMPLE_EVENTS[notificationType]) {
+ throw new Error("Duplicate simple event");
+ }
+ SIMPLE_EVENTS[notificationType] = eventBP.id;
+ } else if (eventBP.type === "event") {
+ const { eventType, filter } = eventBP;
+
+ let targetTypes;
+ if (filter === "global") {
+ targetTypes = ["global"];
+ } else if (filter === "xhr") {
+ targetTypes = ["xhr"];
+ } else if (filter === "websocket") {
+ targetTypes = ["websocket"];
+ } else if (filter === "worker") {
+ targetTypes = ["worker"];
+ } else if (filter === "general") {
+ targetTypes = ["global", "node"];
+ } else if (filter === "node" || filter === "media") {
+ targetTypes = ["node"];
+ } else {
+ throw new Error("Unexpected filter type");
+ }
+
+ for (const targetType of targetTypes) {
+ let byEventType = DOM_EVENTS[targetType];
+ if (!byEventType) {
+ byEventType = {};
+ DOM_EVENTS[targetType] = byEventType;
+ }
+
+ if (byEventType[eventType]) {
+ throw new Error("Duplicate dom event: " + eventType);
+ }
+ byEventType[eventType] = eventBP.id;
+ }
+ } else if (eventBP.type === "script") {
+ // Nothing to do.
+ } else {
+ throw new Error("Unknown type: " + eventBP.type);
+ }
+}
+
+exports.eventBreakpointForNotification = eventBreakpointForNotification;
+function eventBreakpointForNotification(dbg, notification) {
+ const notificationType = notification.type;
+
+ if (notification.type === "domEvent") {
+ const domEventNotification = DOM_EVENTS[notification.targetType];
+ if (!domEventNotification) {
+ return null;
+ }
+
+ // The 'event' value is a cross-compartment wrapper for the DOM Event object.
+ // While we could use that directly in the main thread as an Xray wrapper,
+ // when debugging workers we can't, because it is an opaque wrapper.
+ // To make things work, we have to always interact with the Event object via
+ // the Debugger.Object interface.
+ const evt = dbg
+ .makeGlobalObjectReference(notification.global)
+ .makeDebuggeeValue(notification.event);
+
+ const eventType = evt.getProperty("type").return;
+ const id = domEventNotification[eventType];
+ if (!id) {
+ return null;
+ }
+ const eventBreakpoint = EVENTS_BY_ID[id];
+
+ if (eventBreakpoint.filter === "media") {
+ const currentTarget = evt.getProperty("currentTarget").return;
+ if (!currentTarget) {
+ return null;
+ }
+
+ const nodeType = currentTarget.getProperty("nodeType").return;
+ const namespaceURI = currentTarget.getProperty("namespaceURI").return;
+ if (
+ nodeType !== 1 /* ELEMENT_NODE */ ||
+ namespaceURI !== "http://www.w3.org/1999/xhtml"
+ ) {
+ return null;
+ }
+
+ const nodeName = currentTarget
+ .getProperty("nodeName")
+ .return.toLowerCase();
+ if (nodeName !== "audio" && nodeName !== "video") {
+ return null;
+ }
+ }
+
+ return id;
+ }
+
+ return SIMPLE_EVENTS[notificationType] || null;
+}
+
+exports.makeEventBreakpointMessage = makeEventBreakpointMessage;
+function makeEventBreakpointMessage(id) {
+ return EVENTS_BY_ID[id].message;
+}
+
+exports.firstStatementBreakpointId = firstStatementBreakpointId;
+function firstStatementBreakpointId() {
+ return SCRIPT_FIRST_STATEMENT_BREAKPOINT.id;
+}
+
+exports.eventsRequireNotifications = eventsRequireNotifications;
+function eventsRequireNotifications(ids) {
+ for (const id of ids) {
+ const eventBreakpoint = EVENTS_BY_ID[id];
+
+ // Script events are implemented directly in the server and do not require
+ // notifications from Gecko, so there is no need to watch for them.
+ if (eventBreakpoint && eventBreakpoint.type !== "script") {
+ return true;
+ }
+ }
+ return false;
+}
+
+exports.getAvailableEventBreakpoints = getAvailableEventBreakpoints;
+function getAvailableEventBreakpoints() {
+ const available = [];
+ for (const { name, items } of AVAILABLE_BREAKPOINTS) {
+ available.push({
+ name,
+ events: items.map(item => ({
+ id: item.id,
+ name: item.name,
+ })),
+ });
+ }
+ return available;
+}
diff --git a/devtools/server/actors/utils/event-loop.js b/devtools/server/actors/utils/event-loop.js
new file mode 100644
index 0000000000..2224361e36
--- /dev/null
+++ b/devtools/server/actors/utils/event-loop.js
@@ -0,0 +1,201 @@
+/* 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";
+
+const xpcInspector = require("xpcInspector");
+const { Cu } = require("chrome");
+
+/**
+ * Manages pushing event loops and automatically pops and exits them in the
+ * correct order as they are resolved.
+ *
+ * @param ThreadActor thread
+ * The thread actor instance that owns this EventLoopStack.
+ */
+function EventLoopStack({ thread }) {
+ this._thread = thread;
+}
+
+EventLoopStack.prototype = {
+ /**
+ * The number of nested event loops on the stack.
+ */
+ get size() {
+ return xpcInspector.eventLoopNestLevel;
+ },
+
+ /**
+ * The thread actor of the debuggee who pushed the event loop on top of the stack.
+ */
+ get lastPausedThreadActor() {
+ if (this.size > 0) {
+ return xpcInspector.lastNestRequestor.thread;
+ }
+ return null;
+ },
+
+ /**
+ * Push a new nested event loop onto the stack.
+ *
+ * @returns EventLoop
+ */
+ push: function() {
+ return new EventLoop({
+ thread: this._thread,
+ });
+ },
+};
+
+/**
+ * An object that represents a nested event loop. It is used as the nest
+ * requestor with nsIJSInspector instances.
+ *
+ * @param ThreadActor thread
+ * The thread actor that is creating this nested event loop.
+ */
+function EventLoop({ thread }) {
+ this._thread = thread;
+
+ this.enter = this.enter.bind(this);
+ this.resolve = this.resolve.bind(this);
+}
+
+EventLoop.prototype = {
+ entered: false,
+ resolved: false,
+ get thread() {
+ return this._thread;
+ },
+
+ /**
+ * Enter this nested event loop.
+ */
+ enter: function() {
+ const preNestData = this.preNest();
+
+ this.entered = true;
+ xpcInspector.enterNestedEventLoop(this);
+
+ // Keep exiting nested event loops while the last requestor is resolved.
+ if (xpcInspector.eventLoopNestLevel > 0) {
+ const { resolved } = xpcInspector.lastNestRequestor;
+ if (resolved) {
+ xpcInspector.exitNestedEventLoop();
+ }
+ }
+
+ this.postNest(preNestData);
+ },
+
+ /**
+ * Resolve this nested event loop.
+ *
+ * @returns boolean
+ * True if we exited this nested event loop because it was on top of
+ * the stack, false if there is another nested event loop above this
+ * one that hasn't resolved yet.
+ */
+ resolve: function() {
+ if (!this.entered) {
+ throw new Error(
+ "Can't resolve an event loop before it has been entered!"
+ );
+ }
+ if (this.resolved) {
+ throw new Error("Already resolved this nested event loop!");
+ }
+ this.resolved = true;
+ if (this === xpcInspector.lastNestRequestor) {
+ xpcInspector.exitNestedEventLoop();
+ return true;
+ }
+ return false;
+ },
+
+ /**
+ * Retrieve the list of all DOM Windows debugged by the current thread actor.
+ */
+ getAllWindowDebuggees() {
+ return this._thread.dbg
+ .getDebuggees()
+ .filter(debuggee => {
+ // Select only debuggee that relates to windows
+ // e.g. ignore sandboxes, jsm and such
+ return debuggee.class == "Window";
+ })
+ .map(debuggee => {
+ // Retrieve the JS reference for these windows
+ return debuggee.unsafeDereference();
+ })
+
+ .filter(window => {
+ // Ignore document which have already been nuked,
+ // so navigated to another location and removed from memory completely.
+ if (Cu.isDeadWrapper(window)) {
+ return false;
+ }
+ // Also ignore document which are closed, as trying to access window.parent or top would throw NS_ERROR_NOT_INITIALIZED
+ if (window.closed) {
+ return false;
+ }
+ // Ignore remote iframes, which will be debugged by another thread actor,
+ // running in the remote process
+ if (Cu.isRemoteProxy(window)) {
+ return false;
+ }
+ // Accept "top remote iframe document":
+ // document of iframe whose immediate parent is in another process.
+ if (Cu.isRemoteProxy(window.parent) && !Cu.isRemoteProxy(window)) {
+ return true;
+ }
+ try {
+ // Ignore iframes running in the same process as their parent document,
+ // as they will be paused automatically when pausing their owner top level document
+ return window.top === window;
+ } catch (e) {
+ // Warn if this is throwing for an unknown reason, but suppress the
+ // exception regardless so that we can enter the nested event loop.
+ if (!/not initialized/.test(e)) {
+ console.warn(`Exception in getAllWindowDebuggees: ${e}`);
+ }
+ return false;
+ }
+ });
+ },
+
+ /**
+ * Prepare to enter a nested event loop by disabling debuggee events.
+ */
+ preNest() {
+ const docShells = [];
+ // Disable events in all open windows.
+ for (const window of this.getAllWindowDebuggees()) {
+ const { windowUtils } = window;
+ windowUtils.suppressEventHandling(true);
+ windowUtils.suspendTimeouts();
+ docShells.push(window.docShell);
+ }
+ return docShells;
+ },
+
+ /**
+ * Prepare to exit a nested event loop by enabling debuggee events.
+ */
+ postNest(pausedDocShells) {
+ // Enable events in all window paused in preNest
+ for (const docShell of pausedDocShells) {
+ // Do not try to resume documents which are in destruction
+ // as resume methods would throw
+ if (docShell.isBeingDestroyed()) {
+ continue;
+ }
+ const { windowUtils } = docShell.domWindow;
+ windowUtils.resumeTimeouts();
+ windowUtils.suppressEventHandling(false);
+ }
+ },
+};
+
+exports.EventLoopStack = EventLoopStack;
diff --git a/devtools/server/actors/utils/inactive-property-helper.js b/devtools/server/actors/utils/inactive-property-helper.js
new file mode 100644
index 0000000000..75b289002c
--- /dev/null
+++ b/devtools/server/actors/utils/inactive-property-helper.js
@@ -0,0 +1,1072 @@
+/* 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";
+
+const Services = require("Services");
+const InspectorUtils = require("InspectorUtils");
+
+loader.lazyRequireGetter(
+ this,
+ "CssLogic",
+ "devtools/server/actors/inspector/css-logic",
+ true
+);
+
+const INACTIVE_CSS_ENABLED = Services.prefs.getBoolPref(
+ "devtools.inspector.inactive.css.enabled",
+ false
+);
+
+const VISITED_MDN_LINK = "https://developer.mozilla.org/docs/Web/CSS/:visited";
+const VISITED_INVALID_PROPERTIES = allCssPropertiesExcept([
+ "all",
+ "color",
+ "background",
+ "background-color",
+ "border",
+ "border-color",
+ "border-bottom-color",
+ "border-left-color",
+ "border-right-color",
+ "border-top-color",
+ "border-block",
+ "border-block-color",
+ "border-block-start-color",
+ "border-block-end-color",
+ "border-inline",
+ "border-inline-color",
+ "border-inline-start-color",
+ "border-inline-end-color",
+ "column-rule",
+ "column-rule-color",
+ "outline",
+ "outline-color",
+ "text-decoration-color",
+ "text-emphasis-color",
+]);
+
+class InactivePropertyHelper {
+ /**
+ * A list of rules for when CSS properties have no effect.
+ *
+ * In certain situations, CSS properties do not have any effect. A common
+ * example is trying to set a width on an inline element like a <span>.
+ *
+ * There are so many properties in CSS that it's difficult to remember which
+ * ones do and don't apply in certain situations. Some are straight-forward
+ * like `flex-wrap` only applying to an element that has `display:flex`.
+ * Others are less trivial like setting something other than a color on a
+ * `:visited` pseudo-class.
+ *
+ * This file contains "rules" in the form of objects with the following
+ * properties:
+ * {
+ * invalidProperties:
+ * Array of CSS property names that are inactive if the rule matches.
+ * when:
+ * The rule itself, a JS function used to identify the conditions
+ * indicating whether a property is valid or not.
+ * fixId:
+ * A Fluent id containing a suggested solution to the problem that is
+ * causing a property to be inactive.
+ * msgId:
+ * A Fluent id containing an error message explaining why a property is
+ * inactive in this situation.
+ * numFixProps:
+ * The number of properties we suggest in the fixId string.
+ * }
+ *
+ * If you add a new rule, also add a test for it in:
+ * server/tests/chrome/test_inspector-inactive-property-helper.html
+ *
+ * The main export is `isPropertyUsed()`, which can be used to check if a
+ * property is used or not, and why.
+ */
+ get VALIDATORS() {
+ return [
+ // Flex container property used on non-flex container.
+ {
+ invalidProperties: ["flex-direction", "flex-flow", "flex-wrap"],
+ when: () => !this.flexContainer,
+ fixId: "inactive-css-not-flex-container-fix",
+ msgId: "inactive-css-not-flex-container",
+ numFixProps: 2,
+ },
+ // Flex item property used on non-flex item.
+ {
+ invalidProperties: ["flex", "flex-basis", "flex-grow", "flex-shrink"],
+ when: () => !this.flexItem,
+ fixId: "inactive-css-not-flex-item-fix-2",
+ msgId: "inactive-css-not-flex-item",
+ numFixProps: 2,
+ },
+ // Grid container property used on non-grid container.
+ {
+ invalidProperties: [
+ "grid-auto-columns",
+ "grid-auto-flow",
+ "grid-auto-rows",
+ "grid-template",
+ "justify-items",
+ ],
+ when: () => !this.gridContainer,
+ fixId: "inactive-css-not-grid-container-fix",
+ msgId: "inactive-css-not-grid-container",
+ numFixProps: 2,
+ },
+ // Grid item property used on non-grid item.
+ {
+ invalidProperties: [
+ "grid-area",
+ "grid-column",
+ "grid-column-end",
+ "grid-column-start",
+ "grid-row",
+ "grid-row-end",
+ "grid-row-start",
+ "justify-self",
+ ],
+ when: () => !this.gridItem && !this.isAbsPosGridElement(),
+ fixId: "inactive-css-not-grid-item-fix-2",
+ msgId: "inactive-css-not-grid-item",
+ numFixProps: 2,
+ },
+ // Grid and flex item properties used on non-grid or non-flex item.
+ {
+ invalidProperties: ["align-self", "place-self", "order"],
+ when: () =>
+ !this.gridItem && !this.flexItem && !this.isAbsPosGridElement(),
+ fixId: "inactive-css-not-grid-or-flex-item-fix-2",
+ msgId: "inactive-css-not-grid-or-flex-item",
+ numFixProps: 4,
+ },
+ // Grid and flex container properties used on non-grid or non-flex container.
+ {
+ invalidProperties: [
+ "align-items",
+ "justify-content",
+ "place-content",
+ "place-items",
+ "row-gap",
+ // grid-*-gap are supported legacy shorthands for the corresponding *-gap properties.
+ // See https://drafts.csswg.org/css-align-3/#gap-legacy for more information.
+ "grid-gap",
+ "grid-row-gap",
+ ],
+ when: () => !this.gridContainer && !this.flexContainer,
+ fixId: "inactive-css-not-grid-or-flex-container-fix",
+ msgId: "inactive-css-not-grid-or-flex-container",
+ numFixProps: 2,
+ },
+ // align-content is special as align-content:baseline does have an effect on all
+ // grid items, flex items and table cells, regardless of what type of box they are.
+ // See https://bugzilla.mozilla.org/show_bug.cgi?id=1598730
+ {
+ invalidProperties: ["align-content"],
+ when: () =>
+ !this.style["align-content"].includes("baseline") &&
+ !this.gridContainer &&
+ !this.flexContainer,
+ fixId: "inactive-css-not-grid-or-flex-container-fix",
+ msgId: "inactive-css-not-grid-or-flex-container",
+ numFixProps: 2,
+ },
+ // column-gap and shorthands used on non-grid or non-flex or non-multi-col container.
+ {
+ invalidProperties: [
+ "column-gap",
+ "gap",
+ // grid-*-gap are supported legacy shorthands for the corresponding *-gap properties.
+ // See https://drafts.csswg.org/css-align-3/#gap-legacy for more information.
+ "grid-column-gap",
+ ],
+ when: () =>
+ !this.gridContainer && !this.flexContainer && !this.multiColContainer,
+ fixId:
+ "inactive-css-not-grid-or-flex-container-or-multicol-container-fix",
+ msgId: "inactive-css-not-grid-or-flex-container-or-multicol-container",
+ numFixProps: 3,
+ },
+ // Inline properties used on non-inline-level elements.
+ {
+ invalidProperties: ["vertical-align"],
+ when: () => {
+ const { selectorText } = this.cssRule;
+
+ const isFirstLetter =
+ selectorText && selectorText.includes("::first-letter");
+ const isFirstLine =
+ selectorText && selectorText.includes("::first-line");
+
+ return !this.isInlineLevel() && !isFirstLetter && !isFirstLine;
+ },
+ fixId: "inactive-css-not-inline-or-tablecell-fix",
+ msgId: "inactive-css-not-inline-or-tablecell",
+ numFixProps: 2,
+ },
+ // (max-|min-)width used on inline elements, table rows, or row groups.
+ {
+ invalidProperties: ["max-width", "min-width", "width"],
+ when: () =>
+ this.nonReplacedInlineBox ||
+ this.horizontalTableTrack ||
+ this.horizontalTableTrackGroup,
+ fixId: "inactive-css-non-replaced-inline-or-table-row-or-row-group-fix",
+ msgId: "inactive-css-property-because-of-display",
+ numFixProps: 2,
+ },
+ // (max-|min-)height used on inline elements, table columns, or column groups.
+ {
+ invalidProperties: ["max-height", "min-height", "height"],
+ when: () =>
+ this.nonReplacedInlineBox ||
+ this.verticalTableTrack ||
+ this.verticalTableTrackGroup,
+ fixId:
+ "inactive-css-non-replaced-inline-or-table-column-or-column-group-fix",
+ msgId: "inactive-css-property-because-of-display",
+ numFixProps: 1,
+ },
+ {
+ invalidProperties: ["display"],
+ when: () =>
+ this.isFloated &&
+ this.checkResolvedStyle("display", [
+ "inline",
+ "inline-block",
+ "inline-table",
+ "inline-flex",
+ "inline-grid",
+ "table-cell",
+ "table-row",
+ "table-row-group",
+ "table-header-group",
+ "table-footer-group",
+ "table-column",
+ "table-column-group",
+ "table-caption",
+ ]),
+ fixId: "inactive-css-not-display-block-on-floated-fix",
+ msgId: "inactive-css-not-display-block-on-floated",
+ numFixProps: 2,
+ },
+ // The property is impossible to override due to :visited restriction.
+ {
+ invalidProperties: VISITED_INVALID_PROPERTIES,
+ when: () => this.isVisitedRule(),
+ fixId: "learn-more",
+ msgId: "inactive-css-property-is-impossible-to-override-in-visited",
+ numFixProps: 1,
+ learnMoreURL: VISITED_MDN_LINK,
+ },
+ // top, right, bottom, left properties used on non positioned boxes.
+ {
+ invalidProperties: ["top", "right", "bottom", "left"],
+ when: () => !this.isPositioned,
+ fixId: "inactive-css-position-property-on-unpositioned-box-fix",
+ msgId: "inactive-css-position-property-on-unpositioned-box",
+ numFixProps: 1,
+ },
+ // z-index property used on non positioned boxes that are not grid/flex items.
+ {
+ invalidProperties: ["z-index"],
+ when: () => !this.isPositioned && !this.gridItem && !this.flexItem,
+ fixId: "inactive-css-position-property-on-unpositioned-box-fix",
+ msgId: "inactive-css-position-property-on-unpositioned-box",
+ numFixProps: 1,
+ },
+ // text-overflow property used on elements for which overflow is not set to hidden.
+ // Note that this validator only checks if overflow:hidden is set on the element.
+ // In theory, we should also be checking if the element is a block as this doesn't
+ // normally work on inline element. However there are many edge cases that made it
+ // impossible for the JS code to determine whether the type of box would support
+ // text-overflow. So, rather than risking to show invalid warnings, we decided to
+ // only warn when overflow:hidden wasn't set. There is more information about this
+ // in this discussion https://phabricator.services.mozilla.com/D62407 and on the bug
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=1551578
+ {
+ invalidProperties: ["text-overflow"],
+ when: () => !this.checkComputedStyle("overflow", ["hidden"]),
+ fixId: "inactive-text-overflow-when-no-overflow-fix",
+ msgId: "inactive-text-overflow-when-no-overflow",
+ numFixProps: 1,
+ },
+ // -moz-outline-radius doesn't apply when outline-style is auto or none.
+ {
+ invalidProperties: [
+ "-moz-outline-radius",
+ "-moz-outline-radius-topleft",
+ "-moz-outline-radius-topright",
+ "-moz-outline-radius-bottomleft",
+ "-moz-outline-radius-bottomright",
+ ],
+ when: () => this.checkComputedStyle("outline-style", ["auto", "none"]),
+ fixId: "inactive-outline-radius-when-outline-style-auto-or-none-fix",
+ msgId: "inactive-outline-radius-when-outline-style-auto-or-none",
+ numFixProps: 1,
+ },
+ // margin properties used on table internal elements.
+ {
+ invalidProperties: [
+ "margin",
+ "margin-block",
+ "margin-block-end",
+ "margin-block-start",
+ "margin-bottom",
+ "margin-inline",
+ "margin-inline-end",
+ "margin-inline-start",
+ "margin-left",
+ "margin-right",
+ "margin-top",
+ ],
+ when: () => this.internalTableElement,
+ fixId: "inactive-css-not-for-internal-table-elements-fix",
+ msgId: "inactive-css-not-for-internal-table-elements",
+ numFixProps: 1,
+ },
+ // padding properties used on table internal elements except table cells.
+ {
+ invalidProperties: [
+ "padding",
+ "padding-block",
+ "padding-block-end",
+ "padding-block-start",
+ "padding-bottom",
+ "padding-inline",
+ "padding-inline-end",
+ "padding-inline-start",
+ "padding-left",
+ "padding-right",
+ "padding-top",
+ ],
+ when: () =>
+ this.internalTableElement &&
+ !this.checkComputedStyle("display", ["table-cell"]),
+ fixId:
+ "inactive-css-not-for-internal-table-elements-except-table-cells-fix",
+ msgId:
+ "inactive-css-not-for-internal-table-elements-except-table-cells",
+ numFixProps: 1,
+ },
+ ];
+ }
+
+ /**
+ * Get a list of unique CSS property names for which there are checks
+ * for used/unused state.
+ *
+ * @return {Set}
+ * List of CSS properties
+ */
+ get invalidProperties() {
+ if (!this._invalidProperties) {
+ const allProps = this.VALIDATORS.map(v => v.invalidProperties).flat();
+ this._invalidProperties = new Set(allProps);
+ }
+
+ return this._invalidProperties;
+ }
+
+ /**
+ * Is this CSS property having any effect on this element?
+ *
+ * @param {DOMNode} el
+ * The DOM element.
+ * @param {Style} elStyle
+ * The computed style for this DOMNode.
+ * @param {DOMRule} cssRule
+ * The CSS rule the property is defined in.
+ * @param {String} property
+ * The CSS property name.
+ *
+ * @return {Object} object
+ * @return {String} object.display
+ * The element computed display value.
+ * @return {String} object.fixId
+ * A Fluent id containing a suggested solution to the problem that is
+ * causing a property to be inactive.
+ * @return {String} object.msgId
+ * A Fluent id containing an error message explaining why a property
+ * is inactive in this situation.
+ * @return {Integer} object.numFixProps
+ * The number of properties we suggest in the fixId string.
+ * @return {String} object.property
+ * The inactive property name.
+ * @return {String} object.learnMoreURL
+ * An optional link if we need to open an other link than
+ * the default MDN property one.
+ * @return {Boolean} object.used
+ * true if the property is used.
+ */
+ isPropertyUsed(el, elStyle, cssRule, property) {
+ // Assume the property is used when:
+ // - the Inactive CSS pref is not enabled
+ // - the property is not in the list of properties to check
+ if (!INACTIVE_CSS_ENABLED || !this.invalidProperties.has(property)) {
+ return { used: true };
+ }
+
+ let fixId = "";
+ let msgId = "";
+ let numFixProps = 0;
+ let learnMoreURL = null;
+ let used = true;
+
+ this.VALIDATORS.some(validator => {
+ // First check if this rule cares about this property.
+ let isRuleConcerned = false;
+
+ if (validator.invalidProperties) {
+ isRuleConcerned = validator.invalidProperties.includes(property);
+ }
+
+ if (!isRuleConcerned) {
+ return false;
+ }
+
+ this.select(el, elStyle, cssRule, property);
+
+ // And then run the validator, gathering the error message if the
+ // validator passes.
+ if (validator.when()) {
+ fixId = validator.fixId;
+ msgId = validator.msgId;
+ numFixProps = validator.numFixProps;
+ learnMoreURL = validator.learnMoreURL;
+ used = false;
+
+ return true;
+ }
+
+ return false;
+ });
+
+ this.unselect();
+
+ // Accessing elStyle might throws, we wrap it in a try/catch block to avoid test
+ // failures.
+ let display;
+ try {
+ display = elStyle ? elStyle.display : null;
+ } catch (e) {}
+
+ return {
+ display,
+ fixId,
+ msgId,
+ numFixProps,
+ property,
+ learnMoreURL,
+ used,
+ };
+ }
+
+ /**
+ * Focus on a node.
+ *
+ * @param {DOMNode} node
+ * Node to focus on.
+ */
+ select(node, style, cssRule, property) {
+ this._node = node;
+ this._cssRule = cssRule;
+ this._property = property;
+ this._style = style;
+ }
+
+ /**
+ * Clear references to avoid leaks.
+ */
+ unselect() {
+ this._node = null;
+ this._cssRule = null;
+ this._property = null;
+ this._style = null;
+ }
+
+ /**
+ * Provide a public reference to node.
+ */
+ get node() {
+ return this._node;
+ }
+
+ /**
+ * Cache and provide node's computed style.
+ */
+ get style() {
+ return this._style;
+ }
+
+ /**
+ * Provide a public reference to the css rule.
+ */
+ get cssRule() {
+ return this._cssRule;
+ }
+
+ /**
+ * Check if the current node's propName is set to one of the values passed in
+ * the values array.
+ *
+ * @param {String} propName
+ * Property name to check.
+ * @param {Array} values
+ * Values to compare against.
+ */
+ checkComputedStyle(propName, values) {
+ if (!this.style) {
+ return false;
+ }
+ return values.some(value => this.style[propName] === value);
+ }
+
+ /**
+ * Check if a rule's propName is set to one of the values passed in the values
+ * array.
+ *
+ * @param {String} propName
+ * Property name to check.
+ * @param {Array} values
+ * Values to compare against.
+ */
+ checkResolvedStyle(propName, values) {
+ if (!(this.cssRule && this.cssRule.style)) {
+ return false;
+ }
+ const { style } = this.cssRule;
+
+ return values.some(value => style[propName] === value);
+ }
+
+ /**
+ * Check if the current node is an inline-level box.
+ */
+ isInlineLevel() {
+ return this.checkComputedStyle("display", [
+ "inline",
+ "inline-block",
+ "inline-table",
+ "inline-flex",
+ "inline-grid",
+ "table-cell",
+ "table-row",
+ "table-row-group",
+ "table-header-group",
+ "table-footer-group",
+ ]);
+ }
+
+ /**
+ * Check if the current node is a flex container i.e. a node that has a style
+ * of `display:flex` or `display:inline-flex`.
+ */
+ get flexContainer() {
+ return this.checkComputedStyle("display", ["flex", "inline-flex"]);
+ }
+
+ /**
+ * Check if the current node is a flex item.
+ */
+ get flexItem() {
+ return this.isFlexItem(this.node);
+ }
+
+ /**
+ * Check if the current node is a grid container i.e. a node that has a style
+ * of `display:grid` or `display:inline-grid`.
+ */
+ get gridContainer() {
+ return this.checkComputedStyle("display", ["grid", "inline-grid"]);
+ }
+
+ /**
+ * Check if the current node is a grid item.
+ */
+ get gridItem() {
+ return this.isGridItem(this.node);
+ }
+
+ /**
+ * Check if the current node is a multi-column container, i.e. a node element whose
+ * `column-width` or `column-count` property is not `auto`.
+ */
+ get multiColContainer() {
+ const autoColumnWidth = this.checkComputedStyle("column-width", ["auto"]);
+ const autoColumnCount = this.checkComputedStyle("column-count", ["auto"]);
+
+ return !autoColumnWidth || !autoColumnCount;
+ }
+
+ /**
+ * Check if the current node is a table row.
+ */
+ get tableRow() {
+ return this.style && this.style.display === "table-row";
+ }
+
+ /**
+ * Check if the current node is a table column.
+ */
+ get tableColumn() {
+ return this.style && this.style.display === "table-column";
+ }
+
+ /**
+ * Check if the current node is an internal table element.
+ */
+ get internalTableElement() {
+ return this.checkComputedStyle("display", [
+ "table-cell",
+ "table-row",
+ "table-row-group",
+ "table-header-group",
+ "table-footer-group",
+ "table-column",
+ "table-column-group",
+ ]);
+ }
+
+ /**
+ * Check if the current node is a horizontal table track. That is: either a table row
+ * displayed in horizontal writing mode, or a table column displayed in vertical writing
+ * mode.
+ */
+ get horizontalTableTrack() {
+ if (!this.tableRow && !this.tableColumn) {
+ return false;
+ }
+
+ const wm = this.getTableTrackParentWritingMode();
+ const isVertical = wm.includes("vertical") || wm.includes("sideways");
+
+ return isVertical ? this.tableColumn : this.tableRow;
+ }
+
+ /**
+ * Check if the current node is a vertical table track. That is: either a table row
+ * displayed in vertical writing mode, or a table column displayed in horizontal writing
+ * mode.
+ */
+ get verticalTableTrack() {
+ if (!this.tableRow && !this.tableColumn) {
+ return false;
+ }
+
+ const wm = this.getTableTrackParentWritingMode();
+ const isVertical = wm.includes("vertical") || wm.includes("sideways");
+
+ return isVertical ? this.tableRow : this.tableColumn;
+ }
+
+ /**
+ * Check if the current node is a row group.
+ */
+ get rowGroup() {
+ return this.isRowGroup(this.node);
+ }
+
+ /**
+ * Check if the current node is a table column group.
+ */
+ get columnGroup() {
+ return this.isColumnGroup(this.node);
+ }
+
+ /**
+ * Check if the current node is a horizontal table track group. That is: either a table
+ * row group displayed in horizontal writing mode, or a table column group displayed in
+ * vertical writing mode.
+ */
+ get horizontalTableTrackGroup() {
+ if (!this.rowGroup && !this.columnGroup) {
+ return false;
+ }
+
+ const wm = this.getTableTrackParentWritingMode(true);
+ const isVertical = wm.includes("vertical") || wm.includes("sideways");
+
+ const isHorizontalRowGroup = this.rowGroup && !isVertical;
+ const isHorizontalColumnGroup = this.columnGroup && isVertical;
+
+ return isHorizontalRowGroup || isHorizontalColumnGroup;
+ }
+
+ /**
+ * Check if the current node is a vertical table track group. That is: either a table row
+ * group displayed in vertical writing mode, or a table column group displayed in
+ * horizontal writing mode.
+ */
+ get verticalTableTrackGroup() {
+ if (!this.rowGroup && !this.columnGroup) {
+ return false;
+ }
+
+ const wm = this.getTableTrackParentWritingMode(true);
+ const isVertical = wm.includes("vertical") || wm.includes("sideways");
+
+ const isVerticalRowGroup = this.rowGroup && isVertical;
+ const isVerticalColumnGroup = this.columnGroup && !isVertical;
+
+ return isVerticalRowGroup || isVerticalColumnGroup;
+ }
+
+ /**
+ * Returns whether this element uses CSS layout.
+ */
+ get hasCssLayout() {
+ return !this.isSvg && !this.isMathMl;
+ }
+
+ /**
+ * Check if the current node is a non-replaced CSS inline box.
+ */
+ get nonReplacedInlineBox() {
+ return (
+ this.hasCssLayout &&
+ this.nonReplaced &&
+ this.style &&
+ this.style.display === "inline"
+ );
+ }
+
+ /**
+ * Check if the current node is a non-replaced element. See `replaced()` for
+ * a description of what a replaced element is.
+ */
+ get nonReplaced() {
+ return !this.replaced;
+ }
+
+ /**
+ * Check if the current node is an absolutely-positioned element.
+ */
+ get isAbsolutelyPositioned() {
+ return this.checkComputedStyle("position", ["absolute", "fixed"]);
+ }
+
+ /**
+ * Check if the current node is positioned (i.e. its position property has a value other
+ * than static).
+ */
+ get isPositioned() {
+ return this.checkComputedStyle("position", [
+ "relative",
+ "absolute",
+ "fixed",
+ "sticky",
+ ]);
+ }
+
+ /**
+ * Check if the current node is floated
+ */
+ get isFloated() {
+ return this.style && this.style.cssFloat !== "none";
+ }
+
+ /**
+ * Check if the current node is a replaced element i.e. an element with
+ * content that will be replaced e.g. <img>, <audio>, <video> or <object>
+ * elements.
+ */
+ get replaced() {
+ // The <applet> element was removed in Gecko 56 so we can ignore them.
+ // These are always treated as replaced elements:
+ if (
+ this.nodeNameOneOf([
+ "audio",
+ "br",
+ "button",
+ "canvas",
+ "embed",
+ "hr",
+ "iframe",
+ // Inputs are generally replaced elements. E.g. checkboxes and radios are replaced
+ // unless they have `appearance: none`. However unconditionally treating them
+ // as replaced is enough for our purpose here, and avoids extra complexity that
+ // will likely not be necessary in most cases.
+ "input",
+ "math",
+ "object",
+ "picture",
+ // Select is a replaced element if it has `size<=1` or no size specified, but
+ // unconditionally treating it as replaced is enough for our purpose here, and
+ // avoids extra complexity that will likely not be necessary in most cases.
+ "select",
+ "svg",
+ "textarea",
+ "video",
+ ])
+ ) {
+ return true;
+ }
+
+ // img tags are replaced elements only when the image has finished loading.
+ if (this.nodeName === "img" && this.node.complete) {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Return the current node's nodeName.
+ *
+ * @returns {String}
+ */
+ get nodeName() {
+ return this.node.nodeName ? this.node.nodeName.toLowerCase() : null;
+ }
+
+ /**
+ * Return whether the node is a MathML element.
+ */
+ get isMathMl() {
+ return this.node.namespaceURI === "http://www.w3.org/1998/Math/MathML";
+ }
+
+ /**
+ * Return whether the node is an SVG element.
+ */
+ get isSvg() {
+ return this.node.namespaceURI === "http://www.w3.org/2000/svg";
+ }
+
+ /**
+ * Check if the current node's nodeName matches a value inside the value array.
+ *
+ * @param {Array} values
+ * Array of values to compare against.
+ * @returns {Boolean}
+ */
+ nodeNameOneOf(values) {
+ return values.includes(this.nodeName);
+ }
+
+ /**
+ * Check if the current node is an absolutely-positioned grid element.
+ * See: https://drafts.csswg.org/css-grid/#abspos-items
+ *
+ * @return {Boolean} whether or not the current node is absolutely-positioned by a
+ * grid container.
+ */
+ isAbsPosGridElement() {
+ if (!this.isAbsolutelyPositioned) {
+ return false;
+ }
+
+ const containingBlock = this.getContainingBlock();
+
+ return containingBlock !== null && this.isGridContainer(containingBlock);
+ }
+
+ /**
+ * Check if a node is a flex item.
+ *
+ * @param {DOMNode} node
+ * The node to check.
+ */
+ isFlexItem(node) {
+ return !!node.parentFlexElement;
+ }
+
+ /**
+ * Check if a node is a flex container.
+ *
+ * @param {DOMNode} node
+ * The node to check.
+ */
+ isFlexContainer(node) {
+ return !!node.getAsFlexContainer();
+ }
+
+ /**
+ * Check if a node is a grid container.
+ *
+ * @param {DOMNode} node
+ * The node to check.
+ */
+ isGridContainer(node) {
+ return node.hasGridFragments();
+ }
+
+ /**
+ * Check if a node is a grid item.
+ *
+ * @param {DOMNode} node
+ * The node to check.
+ */
+ isGridItem(node) {
+ return !!this.getParentGridElement(this.node);
+ }
+
+ isVisitedRule() {
+ if (!CssLogic.hasVisitedState(this.node)) {
+ return false;
+ }
+
+ const selectors = CssLogic.getSelectors(this.cssRule);
+ if (!selectors.some(s => s.endsWith(":visited"))) {
+ return false;
+ }
+
+ const { bindingElement, pseudo } = CssLogic.getBindingElementAndPseudo(
+ this.node
+ );
+
+ for (let i = 0; i < selectors.length; i++) {
+ if (
+ !selectors[i].endsWith(":visited") &&
+ InspectorUtils.selectorMatchesElement(
+ bindingElement,
+ this.cssRule,
+ i,
+ pseudo,
+ true
+ )
+ ) {
+ // Match non :visited selector.
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Return the current node's ancestor that generates its containing block.
+ */
+ getContainingBlock() {
+ return this.node ? InspectorUtils.containingBlockOf(this.node) : null;
+ }
+
+ getParentGridElement(node) {
+ // The documentElement can't be a grid item, only a container, so bail out.
+ if (node.flattenedTreeParentNode === node.ownerDocument) {
+ return null;
+ }
+
+ if (node.nodeType === node.ELEMENT_NODE) {
+ const display = this.style ? this.style.display : null;
+
+ if (!display || display === "none" || display === "contents") {
+ // Doesn't generate a box, not a grid item.
+ return null;
+ }
+ if (this.isAbsolutelyPositioned) {
+ // Out of flow, not a grid item.
+ return null;
+ }
+ } else if (node.nodeType !== node.TEXT_NODE) {
+ return null;
+ }
+
+ for (
+ let p = node.flattenedTreeParentNode;
+ p;
+ p = p.flattenedTreeParentNode
+ ) {
+ if (this.isGridContainer(p)) {
+ // It's a grid item!
+ return p;
+ }
+
+ const style = computedStyle(p, node.ownerGlobal);
+ const display = style.display;
+
+ if (display !== "contents") {
+ return null; // Not a grid item, for sure.
+ }
+ // display: contents, walk to the parent
+ }
+ return null;
+ }
+
+ isRowGroup(node) {
+ const style = node === this.node ? this.style : computedStyle(node);
+
+ return (
+ style &&
+ (style.display === "table-row-group" ||
+ style.display === "table-header-group" ||
+ style.display === "table-footer-group")
+ );
+ }
+
+ isColumnGroup(node) {
+ const style = node === this.node ? this.style : computedStyle(node);
+
+ return style && style.display === "table-column-group";
+ }
+
+ /**
+ * Assuming the current element is a table track (row or column) or table track group,
+ * get the parent table writing mode.
+ * This is either going to be the table element if there is one, or the parent element.
+ * If the current element is not a table track, this returns its own writing mode.
+ *
+ * @param {Boolean} isGroup
+ * Whether the element is a table track group, instead of a table track.
+ * @return {String}
+ * The writing-mode value
+ */
+ getTableTrackParentWritingMode(isGroup) {
+ let current = this.node.parentNode;
+
+ // Skip over unrendered elements.
+ while (computedStyle(current).display === "contents") {
+ current = current.parentNode;
+ }
+
+ // Skip over groups if the initial element wasn't already one.
+ if (!isGroup && (this.isRowGroup(current) || this.isColumnGroup(current))) {
+ current = current.parentNode;
+ }
+
+ // Once more over unrendered elements above the group.
+ while (computedStyle(current).display === "contents") {
+ current = current.parentNode;
+ }
+
+ return computedStyle(current).writingMode;
+ }
+}
+
+exports.inactivePropertyHelper = new InactivePropertyHelper();
+
+/**
+ * Returns all CSS property names except given properties.
+ *
+ * @param {Array} - propertiesToIgnore
+ * Array of property ignored.
+ * @return {Array}
+ * Array of all CSS property name except propertiesToIgnore.
+ */
+function allCssPropertiesExcept(propertiesToIgnore) {
+ const properties = new Set(
+ InspectorUtils.getCSSPropertyNames({ includeAliases: true })
+ );
+
+ for (const name of propertiesToIgnore) {
+ properties.delete(name);
+ }
+
+ return [...properties];
+}
+
+/**
+ * Helper for getting an element's computed styles.
+ *
+ * @param {DOMNode} node
+ * The node to get the styles for.
+ * @param {Window} window
+ * Optional window object. If omitted, will get the node's window.
+ * @return {Object}
+ */
+function computedStyle(node, window = node.ownerGlobal) {
+ return window.getComputedStyle(node);
+}
diff --git a/devtools/server/actors/utils/logEvent.js b/devtools/server/actors/utils/logEvent.js
new file mode 100644
index 0000000000..052acb6ec4
--- /dev/null
+++ b/devtools/server/actors/utils/logEvent.js
@@ -0,0 +1,97 @@
+/* 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";
+
+const { formatDisplayName } = require("devtools/server/actors/frame");
+const {
+ TYPES,
+ getResourceWatcher,
+} = require("devtools/server/actors/resources/index");
+
+// Get a string message to display when a frame evaluation throws.
+function getThrownMessage(completion) {
+ try {
+ if (completion.throw.getOwnPropertyDescriptor) {
+ return completion.throw.getOwnPropertyDescriptor("message").value;
+ } else if (completion.toString) {
+ return completion.toString();
+ }
+ } catch (ex) {
+ // ignore
+ }
+ return "Unknown exception";
+}
+module.exports.getThrownMessage = getThrownMessage;
+
+function logEvent({ threadActor, frame, level, expression, bindings }) {
+ const {
+ sourceActor,
+ line,
+ column,
+ } = threadActor.sourcesManager.getFrameLocation(frame);
+ const displayName = formatDisplayName(frame);
+
+ // TODO remove this branch when (#1592584) lands (#1609540)
+ if (isWorker) {
+ threadActor._parent._consoleActor.evaluateJS({
+ text: `console.log(...${expression})`,
+ bindings: { displayName, ...bindings },
+ url: sourceActor.url,
+ lineNumber: line,
+ });
+
+ return undefined;
+ }
+
+ const completion = frame.evalWithBindings(expression, {
+ displayName,
+ ...bindings,
+ });
+
+ let value;
+ if (!completion) {
+ // The evaluation was killed (possibly by the slow script dialog).
+ value = ["Evaluation failed"];
+ } else if ("return" in completion) {
+ value = completion.return;
+ } else {
+ value = [getThrownMessage(completion)];
+ level = `${level}Error`;
+ }
+
+ if (value && typeof value.unsafeDereference === "function") {
+ value = value.unsafeDereference();
+ }
+
+ const message = {
+ filename: sourceActor.url,
+ lineNumber: line,
+ columnNumber: column,
+ arguments: value,
+ level,
+ // The 'prepareConsoleMessageForRemote' method in webconsoleActor expects internal source ID,
+ // thus we can't set sourceId directly to sourceActorID.
+ sourceId: sourceActor.internalSourceId,
+ };
+
+ const targetActor = threadActor._parent;
+ // Note that only BrowsingContextTarget actor support resource watcher
+ // This is still missing for worker and content processes
+ const consoleMessageWatcher = getResourceWatcher(
+ targetActor,
+ TYPES.CONSOLE_MESSAGE
+ );
+ if (consoleMessageWatcher) {
+ consoleMessageWatcher.onLogPoint(message);
+ } else {
+ // Bug 1642296: Once we enable ConsoleMessage resource on the server, we should remove onConsoleAPICall
+ // from the WebConsoleActor, and only support the ConsoleMessageWatcher codepath.
+ targetActor._consoleActor.onConsoleAPICall(message);
+ }
+
+ return undefined;
+}
+
+module.exports.logEvent = logEvent;
diff --git a/devtools/server/actors/utils/make-debugger.js b/devtools/server/actors/utils/make-debugger.js
new file mode 100644
index 0000000000..e916b0aae9
--- /dev/null
+++ b/devtools/server/actors/utils/make-debugger.js
@@ -0,0 +1,110 @@
+/* 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";
+
+const EventEmitter = require("devtools/shared/event-emitter");
+const Debugger = require("Debugger");
+
+const { reportException } = require("devtools/shared/DevToolsUtils");
+
+/**
+ * Multiple actors that use a |Debugger| instance come in a few versions, each
+ * with a different set of debuggees. One version for content tabs (globals
+ * within a tab), one version for chrome debugging (all globals), and sometimes
+ * a third version for addon debugging (chrome globals the addon is loaded in
+ * and content globals the addon injects scripts into). The |makeDebugger|
+ * function helps us avoid repeating the logic for finding and maintaining the
+ * correct set of globals for a given |Debugger| instance across each version of
+ * all of our actors.
+ *
+ * The |makeDebugger| function expects a single object parameter with the
+ * following properties:
+ *
+ * @param Function findDebuggees
+ * Called with one argument: a |Debugger| instance. This function should
+ * return an iterable of globals to be added to the |Debugger|
+ * instance. The globals may be wrapped in a |Debugger.Object|, or
+ * unwrapped.
+ *
+ * @param Function shouldAddNewGlobalAsDebuggee
+ * Called with one argument: a |Debugger.Object| wrapping a global
+ * object. This function must return |true| if the global object should
+ * be added as debuggee, and |false| otherwise.
+ *
+ * @returns Debugger
+ * Returns a |Debugger| instance that can manage its set of debuggee
+ * globals itself and is decorated with the |EventEmitter| class.
+ *
+ * Existing |Debugger| properties set on the returned |Debugger|
+ * instance:
+ *
+ * - onNewGlobalObject: The |Debugger| will automatically add new
+ * globals as debuggees if calling |shouldAddNewGlobalAsDebuggee|
+ * with the global returns true.
+ *
+ * - uncaughtExceptionHook: The |Debugger| already has an error
+ * reporter attached to |uncaughtExceptionHook|, so if any
+ * |Debugger| hooks fail, the error will be reported.
+ *
+ * New properties set on the returned |Debugger| instance:
+ *
+ * - addDebuggees: A function which takes no arguments. It adds all
+ * current globals that should be debuggees (as determined by
+ * |findDebuggees|) to the |Debugger| instance.
+ */
+module.exports = function makeDebugger({
+ findDebuggees,
+ shouldAddNewGlobalAsDebuggee,
+} = {}) {
+ const dbg = new Debugger();
+ EventEmitter.decorate(dbg);
+
+ dbg.allowUnobservedAsmJS = true;
+ dbg.uncaughtExceptionHook = reportDebuggerHookException;
+
+ const onNewGlobalObject = function(global) {
+ if (shouldAddNewGlobalAsDebuggee(global)) {
+ safeAddDebuggee(this, global);
+ }
+ };
+
+ dbg.onNewGlobalObject = onNewGlobalObject;
+ dbg.addDebuggees = function() {
+ for (const global of findDebuggees(this)) {
+ safeAddDebuggee(this, global);
+ }
+ };
+
+ dbg.disable = function() {
+ dbg.removeAllDebuggees();
+ dbg.onNewGlobalObject = undefined;
+ };
+
+ dbg.enable = function() {
+ dbg.addDebuggees();
+ dbg.onNewGlobalObject = onNewGlobalObject;
+ };
+
+ return dbg;
+};
+
+const reportDebuggerHookException = e => reportException("DBG-SERVER", e);
+
+/**
+ * Add |global| as a debuggee to |dbg|, handling error cases.
+ */
+function safeAddDebuggee(dbg, global) {
+ let globalDO;
+ try {
+ globalDO = dbg.addDebuggee(global);
+ } catch (e) {
+ // Ignoring attempt to add the debugger's compartment as a debuggee.
+ return;
+ }
+
+ if (dbg.onNewDebuggee) {
+ dbg.onNewDebuggee(globalDO);
+ }
+}
diff --git a/devtools/server/actors/utils/moz.build b/devtools/server/actors/utils/moz.build
new file mode 100644
index 0000000000..128ea1678e
--- /dev/null
+++ b/devtools/server/actors/utils/moz.build
@@ -0,0 +1,28 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "accessibility.js",
+ "actor-registry.js",
+ "breakpoint-actor-map.js",
+ "capture-screenshot.js",
+ "css-grid-utils.js",
+ "dbg-source.js",
+ "event-breakpoints.js",
+ "event-loop.js",
+ "inactive-property-helper.js",
+ "logEvent.js",
+ "make-debugger.js",
+ "shapes-utils.js",
+ "source-map-utils.js",
+ "source-url.js",
+ "sources-manager.js",
+ "stack.js",
+ "style-utils.js",
+ "track-change-emitter.js",
+ "walker-search.js",
+ "watchpoint-map.js",
+)
diff --git a/devtools/server/actors/utils/shapes-utils.js b/devtools/server/actors/utils/shapes-utils.js
new file mode 100644
index 0000000000..aab50bf952
--- /dev/null
+++ b/devtools/server/actors/utils/shapes-utils.js
@@ -0,0 +1,149 @@
+/* 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";
+
+/**
+ * Get the distance between two points on a plane.
+ * @param {Number} x1 the x coord of the first point
+ * @param {Number} y1 the y coord of the first point
+ * @param {Number} x2 the x coord of the second point
+ * @param {Number} y2 the y coord of the second point
+ * @returns {Number} the distance between the two points
+ */
+const getDistance = (x1, y1, x2, y2) => {
+ return Math.round(Math.hypot(x2 - x1, y2 - y1));
+};
+
+/**
+ * Determine if the given x/y coords are along the edge of the given ellipse.
+ * We allow for a small area around the edge that still counts as being on the edge.
+ * @param {Number} x the x coordinate of the click
+ * @param {Number} y the y coordinate of the click
+ * @param {Number} cx the x coordinate of the center of the ellipse
+ * @param {Number} cy the y coordinate of the center of the ellipse
+ * @param {Number} rx the x radius of the ellipse
+ * @param {Number} ry the y radius of the ellipse
+ * @param {Number} clickWidthX the width of the area that counts as being on the edge
+ * along the x radius.
+ * @param {Number} clickWidthY the width of the area that counts as being on the edge
+ * along the y radius.
+ * @returns {Boolean} whether the click counts as being on the edge of the ellipse.
+ */
+const clickedOnEllipseEdge = (
+ x,
+ y,
+ cx,
+ cy,
+ rx,
+ ry,
+ clickWidthX,
+ clickWidthY
+) => {
+ // The formula to determine if something is inside or on the edge of an ellipse is:
+ // (x - cx)^2/rx^2 + (y - cy)^2/ry^2 <= 1. If > 1, it's outside.
+ // We make two ellipses, adjusting rx and ry with clickWidthX and clickWidthY
+ // to allow for an area around the edge of the ellipse that can be clicked on.
+ // If the click was outside the inner ellipse and inside the outer ellipse, return true.
+ const inner =
+ (x - cx) ** 2 / (rx - clickWidthX) ** 2 +
+ (y - cy) ** 2 / (ry - clickWidthY) ** 2;
+ const outer =
+ (x - cx) ** 2 / (rx + clickWidthX) ** 2 +
+ (y - cy) ** 2 / (ry + clickWidthY) ** 2;
+ return inner >= 1 && outer <= 1;
+};
+
+/**
+ * Get the distance between a point and a line defined by two other points.
+ * @param {Number} x1 the x coordinate of the first point in the line
+ * @param {Number} y1 the y coordinate of the first point in the line
+ * @param {Number} x2 the x coordinate of the second point in the line
+ * @param {Number} y2 the y coordinate of the second point in the line
+ * @param {Number} x3 the x coordinate of the point for which the distance is found
+ * @param {Number} y3 the y coordinate of the point for which the distance is found
+ * @returns {Number} the distance between (x3,y3) and the line defined by
+ * (x1,y1) and (y1,y2)
+ */
+const distanceToLine = (x1, y1, x2, y2, x3, y3) => {
+ // https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line#Line_defined_by_two_points
+ const num = Math.abs((y2 - y1) * x3 - (x2 - x1) * y3 + x2 * y1 - y2 * x1);
+ const denom = getDistance(x1, y1, x2, y2);
+ return num / denom;
+};
+
+/**
+ * Get the point on the line defined by points a,b that is closest to point c
+ * @param {Number} ax the x coordinate of point a
+ * @param {Number} ay the y coordinate of point a
+ * @param {Number} bx the x coordinate of point b
+ * @param {Number} by the y coordinate of point b
+ * @param {Number} cx the x coordinate of point c
+ * @param {Number} cy the y coordinate of point c
+ * @returns {Array} a 2 element array that contains the x/y coords of the projected point
+ */
+const projection = (ax, ay, bx, by, cx, cy) => {
+ // https://en.wikipedia.org/wiki/Vector_projection#Vector_projection_2
+ const ab = [bx - ax, by - ay];
+ const ac = [cx - ax, cy - ay];
+ const scalar = dotProduct(ab, ac) / dotProduct(ab, ab);
+ return [ax + scalar * ab[0], ay + scalar * ab[1]];
+};
+
+/**
+ * Get the dot product of two vectors, represented by arrays of numbers.
+ * @param {Array} a the first vector
+ * @param {Array} b the second vector
+ * @returns {Number} the dot product of a and b
+ */
+const dotProduct = (a, b) => {
+ return a.reduce((prev, curr, i) => {
+ return prev + curr * b[i];
+ }, 0);
+};
+
+/**
+ * Determine if the given x/y coords are above the given point.
+ * @param {Number} x the x coordinate of the click
+ * @param {Number} y the y coordinate of the click
+ * @param {Number} pointX the x coordinate of the center of the point
+ * @param {Number} pointY the y coordinate of the center of the point
+ * @param {Number} radiusX the x radius of the point
+ * @param {Number} radiusY the y radius of the point
+ * @returns {Boolean} whether the click was on the point
+ */
+const clickedOnPoint = (x, y, pointX, pointY, radiusX, radiusY) => {
+ return (
+ x >= pointX - radiusX &&
+ x <= pointX + radiusX &&
+ y >= pointY - radiusY &&
+ y <= pointY + radiusY
+ );
+};
+
+const roundTo = (value, exp) => {
+ // If the exp is undefined or zero...
+ if (typeof exp === "undefined" || +exp === 0) {
+ return Math.round(value);
+ }
+ value = +value;
+ exp = +exp;
+ // If the value is not a number or the exp is not an integer...
+ if (isNaN(value) || !(typeof exp === "number" && exp % 1 === 0)) {
+ return NaN;
+ }
+ // Shift
+ value = value.toString().split("e");
+ value = Math.round(+(value[0] + "e" + (value[1] ? +value[1] - exp : -exp)));
+ // Shift back
+ value = value.toString().split("e");
+ return +(value[0] + "e" + (value[1] ? +value[1] + exp : exp));
+};
+
+exports.getDistance = getDistance;
+exports.clickedOnEllipseEdge = clickedOnEllipseEdge;
+exports.distanceToLine = distanceToLine;
+exports.projection = projection;
+exports.clickedOnPoint = clickedOnPoint;
+exports.roundTo = roundTo;
diff --git a/devtools/server/actors/utils/source-map-utils.js b/devtools/server/actors/utils/source-map-utils.js
new file mode 100644
index 0000000000..5df3bca0e5
--- /dev/null
+++ b/devtools/server/actors/utils/source-map-utils.js
@@ -0,0 +1,53 @@
+/* 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";
+
+exports.resolveSourceURL = resolveSourceURL;
+function resolveSourceURL(sourceURL, global) {
+ if (sourceURL) {
+ try {
+ return new URL(sourceURL, global?.location?.href || undefined).href;
+ } catch (err) {}
+ }
+
+ return null;
+}
+
+exports.getSourcemapBaseURL = getSourcemapBaseURL;
+function getSourcemapBaseURL(url, global) {
+ let sourceMapBaseURL = null;
+ if (url) {
+ // Sources that have explicit URLs can be used directly as the base.
+ sourceMapBaseURL = url;
+ } else if (global?.location?.href) {
+ // If there is no URL for the source, the map comment is relative to the
+ // page being viewed, so we use the document href.
+ sourceMapBaseURL = global?.location?.href;
+ } else {
+ // If there is no valid base, the sourcemap URL will need to be an absolute
+ // URL of some kind.
+ return null;
+ }
+
+ // A data URL is large and will never be a valid base, so we can just treat
+ // it as if there is no base at all to avoid a sending it to the client
+ // for no reason.
+ if (sourceMapBaseURL.startsWith("data:")) {
+ return null;
+ }
+
+ // If the base URL is a blob, we want to resolve relative to the origin
+ // that created the blob URL, if there is one.
+ if (sourceMapBaseURL.startsWith("blob:")) {
+ try {
+ const parsedBaseURL = new URL(sourceMapBaseURL);
+ return parsedBaseURL.origin === "null" ? null : parsedBaseURL.origin;
+ } catch (err) {
+ return null;
+ }
+ }
+
+ return sourceMapBaseURL;
+}
diff --git a/devtools/server/actors/utils/source-url.js b/devtools/server/actors/utils/source-url.js
new file mode 100644
index 0000000000..133853b978
--- /dev/null
+++ b/devtools/server/actors/utils/source-url.js
@@ -0,0 +1,38 @@
+/* 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";
+
+/**
+ * Debugger.Source objects have a `url` property that exposes the value
+ * that was passed to SpiderMonkey, but unfortunately often SpiderMonkey
+ * sets a URL even in cases where it doesn't make sense, so we have to
+ * explicitly ignore the URL value in these contexts to keep things a bit
+ * more consistent.
+ *
+ * @param {Debugger.Source} source
+ *
+ * @return {string | null}
+ */
+function getDebuggerSourceURL(source) {
+ const introType = source.introductionType;
+
+ // These are all the sources that are eval or eval-like, but may still have
+ // a URL set on the source, so we explicitly ignore the source URL for these.
+ if (
+ introType === "injectedScript" ||
+ introType === "eval" ||
+ introType === "debugger eval" ||
+ introType === "Function" ||
+ introType === "javascriptURL" ||
+ introType === "eventHandler" ||
+ introType === "domTimer"
+ ) {
+ return null;
+ }
+
+ return source.url;
+}
+
+exports.getDebuggerSourceURL = getDebuggerSourceURL;
diff --git a/devtools/server/actors/utils/sources-manager.js b/devtools/server/actors/utils/sources-manager.js
new file mode 100644
index 0000000000..0cefe17d89
--- /dev/null
+++ b/devtools/server/actors/utils/sources-manager.js
@@ -0,0 +1,503 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const { assert, fetch } = DevToolsUtils;
+const EventEmitter = require("devtools/shared/event-emitter");
+const { SourceLocation } = require("devtools/server/actors/common");
+const Services = require("Services");
+
+loader.lazyRequireGetter(
+ this,
+ "SourceActor",
+ "devtools/server/actors/source",
+ true
+);
+
+/**
+ * Matches strings of the form "foo.min.js" or "foo-min.js", etc. If the regular
+ * expression matches, we can be fairly sure that the source is minified, and
+ * treat it as such.
+ */
+const MINIFIED_SOURCE_REGEXP = /\bmin\.js$/;
+
+/**
+ * Manages the sources for a thread. Handles URL contents, locations in
+ * the sources, etc for ThreadActors.
+ */
+class SourcesManager extends EventEmitter {
+ constructor(threadActor, allowSourceFn = () => true) {
+ super();
+ this._thread = threadActor;
+ this.allowSource = source => {
+ return !isHiddenSource(source) && allowSourceFn(source);
+ };
+
+ this.blackBoxedSources = new Map();
+
+ // Debugger.Source -> SourceActor
+ this._sourceActors = new Map();
+
+ // URL -> content
+ //
+ // Any possibly incomplete content that has been loaded for each URL.
+ this._urlContents = new Map();
+
+ // URL -> Promise[]
+ //
+ // Any promises waiting on a URL to be completely loaded.
+ this._urlWaiters = new Map();
+
+ // Debugger.Source.id -> Debugger.Source
+ //
+ // The IDs associated with ScriptSources and available via DebuggerSource.id
+ // are internal to this process and should not be exposed to the client. This
+ // map associates these IDs with the corresponding source, provided the source
+ // has not been GC'ed and the actor has been created. This is lazily populated
+ // the first time it is needed.
+ this._sourcesByInternalSourceId = null;
+
+ if (!isWorker) {
+ Services.obs.addObserver(this, "devtools-html-content");
+ }
+ }
+
+ destroy() {
+ if (!isWorker) {
+ Services.obs.removeObserver(this, "devtools-html-content");
+ }
+ }
+
+ /**
+ * Clear existing sources so they are recreated on the next access.
+ */
+ reset() {
+ this._sourceActors = new Map();
+ this._urlContents = new Map();
+ this._urlWaiters = new Map();
+ this._sourcesByInternalSourceId = null;
+ }
+
+ /**
+ * Create a source actor representing this source.
+ *
+ * @param Debugger.Source source
+ * The source to make an actor for.
+ * @returns a SourceActor representing the source or null.
+ */
+ createSourceActor(source) {
+ assert(source, "SourcesManager.prototype.source needs a source");
+
+ if (!this.allowSource(source)) {
+ return null;
+ }
+
+ if (this._sourceActors.has(source)) {
+ return this._sourceActors.get(source);
+ }
+
+ const actor = new SourceActor({
+ thread: this._thread,
+ source,
+ });
+
+ this._thread.threadLifetimePool.manage(actor);
+
+ this._sourceActors.set(source, actor);
+ if (this._sourcesByInternalSourceId && source.id) {
+ this._sourcesByInternalSourceId.set(source.id, source);
+ }
+
+ this.emit("newSource", actor);
+ return actor;
+ }
+
+ _getSourceActor(source) {
+ if (this._sourceActors.has(source)) {
+ return this._sourceActors.get(source);
+ }
+
+ return null;
+ }
+
+ hasSourceActor(source) {
+ return !!this._getSourceActor(source);
+ }
+
+ getSourceActor(source) {
+ const sourceActor = this._getSourceActor(source);
+
+ if (!sourceActor) {
+ throw new Error(
+ "getSource: could not find source actor for " + (source.url || "source")
+ );
+ }
+
+ return sourceActor;
+ }
+
+ getOrCreateSourceActor(source) {
+ // Tolerate the source coming from a different Debugger than the one
+ // associated with the thread.
+ try {
+ source = this._thread.dbg.adoptSource(source);
+ } catch (e) {
+ // We can't create actors for sources in the same compartment as the
+ // thread's Debugger.
+ if (/is in the same compartment as this debugger/.test(e)) {
+ return null;
+ }
+ throw e;
+ }
+
+ if (this.hasSourceActor(source)) {
+ return this.getSourceActor(source);
+ }
+ return this.createSourceActor(source);
+ }
+
+ getSourceActorByInternalSourceId(id) {
+ if (!this._sourcesByInternalSourceId) {
+ this._sourcesByInternalSourceId = new Map();
+ for (const source of this._thread.dbg.findSources()) {
+ if (source.id) {
+ this._sourcesByInternalSourceId.set(source.id, source);
+ }
+ }
+ }
+ const source = this._sourcesByInternalSourceId.get(id);
+ if (source) {
+ return this.getOrCreateSourceActor(source);
+ }
+ return null;
+ }
+
+ getSourceActorsByURL(url) {
+ const rv = [];
+ if (url) {
+ for (const [, actor] of this._sourceActors) {
+ if (actor.url === url) {
+ rv.push(actor);
+ }
+ }
+ }
+ return rv;
+ }
+
+ getSourceActorById(actorId) {
+ for (const [, actor] of this._sourceActors) {
+ if (actor.actorID == actorId) {
+ return actor;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if the URL likely points to a minified resource, false
+ * otherwise.
+ *
+ * @param String uri
+ * The url to test.
+ * @returns Boolean
+ */
+ _isMinifiedURL(uri) {
+ if (!uri) {
+ return false;
+ }
+
+ try {
+ const url = new URL(uri);
+ const pathname = url.pathname;
+ return MINIFIED_SOURCE_REGEXP.test(
+ pathname.slice(pathname.lastIndexOf("/") + 1)
+ );
+ } catch (e) {
+ // Not a valid URL so don't try to parse out the filename, just test the
+ // whole thing with the minified source regexp.
+ return MINIFIED_SOURCE_REGEXP.test(uri);
+ }
+ }
+
+ /**
+ * Return the non-source-mapped location of an offset in a script.
+ *
+ * @param Debugger.Script script
+ * The script associated with the offset.
+ * @param Number offset
+ * Offset within the script of the location.
+ * @returns Object
+ * Returns an object of the form { source, line, column }
+ */
+ getScriptOffsetLocation(script, offset) {
+ const { lineNumber, columnNumber } = script.getOffsetMetadata(offset);
+ return new SourceLocation(
+ this.createSourceActor(script.source),
+ lineNumber,
+ columnNumber
+ );
+ }
+
+ /**
+ * Return the non-source-mapped location of the given Debugger.Frame. If the
+ * frame does not have a script, the location's properties are all null.
+ *
+ * @param Debugger.Frame frame
+ * The frame whose location we are getting.
+ * @returns Object
+ * Returns an object of the form { source, line, column }
+ */
+ getFrameLocation(frame) {
+ if (!frame || !frame.script) {
+ return new SourceLocation();
+ }
+ return this.getScriptOffsetLocation(frame.script, frame.offset);
+ }
+
+ /**
+ * Returns true if URL for the given source is black boxed.
+ *
+ * * @param url String
+ * The URL of the source which we are checking whether it is black
+ * boxed or not.
+ */
+ isBlackBoxed(url, line, column) {
+ const ranges = this.blackBoxedSources.get(url);
+ if (!ranges) {
+ return this.blackBoxedSources.has(url);
+ }
+
+ const range = ranges.find(r => isLocationInRange({ line, column }, r));
+ return !!range;
+ }
+
+ isFrameBlackBoxed(frame) {
+ const { url, line, column } = this.getFrameLocation(frame);
+ return this.isBlackBoxed(url, line, column);
+ }
+
+ /**
+ * Add the given source URL to the set of sources that are black boxed.
+ *
+ * @param url String
+ * The URL of the source which we are black boxing.
+ */
+ blackBox(url, range) {
+ if (!range) {
+ // blackbox the whole source
+ return this.blackBoxedSources.set(url, null);
+ }
+
+ const ranges = this.blackBoxedSources.get(url) || [];
+ // ranges are sorted in ascening order
+ const index = ranges.findIndex(
+ r => r.end.line <= range.start.line && r.end.column <= range.start.column
+ );
+
+ ranges.splice(index + 1, 0, range);
+ this.blackBoxedSources.set(url, ranges);
+ return true;
+ }
+
+ /**
+ * Remove the given source URL to the set of sources that are black boxed.
+ *
+ * @param url String
+ * The URL of the source which we are no longer black boxing.
+ */
+ unblackBox(url, range) {
+ if (!range) {
+ return this.blackBoxedSources.delete(url);
+ }
+
+ const ranges = this.blackBoxedSources.get(url);
+ const index = ranges.findIndex(
+ r =>
+ r.start.line === range.start.line &&
+ r.start.column === range.start.column &&
+ r.end.line === range.end.line &&
+ r.end.column === range.end.column
+ );
+
+ if (index !== -1) {
+ ranges.splice(index, 1);
+ }
+
+ if (ranges.length === 0) {
+ return this.blackBoxedSources.delete(url);
+ }
+
+ return this.blackBoxedSources.set(url, ranges);
+ }
+
+ iter() {
+ return [...this._sourceActors.values()];
+ }
+
+ /**
+ * Listener for new HTML content.
+ */
+ observe(subject, topic, data) {
+ if (topic == "devtools-html-content") {
+ const { parserID, uri, contents, complete } = JSON.parse(data);
+ if (this._urlContents.has(uri)) {
+ const existing = this._urlContents.get(uri);
+ if (existing.parserID == parserID) {
+ assert(!existing.complete);
+ existing.content = existing.content + contents;
+ existing.complete = complete;
+
+ // After the HTML has finished loading, resolve any promises
+ // waiting for the complete file contents. Waits will only
+ // occur when the URL was ever partially loaded.
+ if (complete) {
+ const waiters = this._urlWaiters.get(uri);
+ if (waiters) {
+ for (const waiter of waiters) {
+ waiter();
+ }
+ this._urlWaiters.delete(uri);
+ }
+ }
+ }
+ } else {
+ this._urlContents.set(uri, {
+ content: contents,
+ complete,
+ contentType: "text/html",
+ parserID,
+ });
+ }
+ }
+ }
+
+ /**
+ * Get the contents of a URL, fetching it if necessary. If partial is set and
+ * any content for the URL has been received, that partial content is returned
+ * synchronously.
+ */
+ urlContents(url, partial, canUseCache) {
+ if (this._urlContents.has(url)) {
+ const data = this._urlContents.get(url);
+ if (!partial && !data.complete) {
+ return new Promise(resolve => {
+ if (!this._urlWaiters.has(url)) {
+ this._urlWaiters.set(url, []);
+ }
+ this._urlWaiters.get(url).push(resolve);
+ }).then(() => {
+ assert(data.complete);
+ return {
+ content: data.content,
+ contentType: data.contentType,
+ };
+ });
+ }
+ return {
+ content: data.content,
+ contentType: data.contentType,
+ };
+ }
+
+ return this._fetchURLContents(url, partial, canUseCache);
+ }
+
+ async _fetchURLContents(url, partial, canUseCache) {
+ // Only try the cache if it is currently enabled for the document.
+ // Without this check, the cache may return stale data that doesn't match
+ // the document shown in the browser.
+ let loadFromCache = canUseCache;
+ if (canUseCache && this._thread._parent._getCacheDisabled) {
+ loadFromCache = !this._thread._parent._getCacheDisabled();
+ }
+
+ // Fetch the sources with the same principal as the original document
+ const win = this._thread._parent.window;
+ let principal, cacheKey;
+ // On xpcshell, we don't have a window but a Sandbox
+ if (!isWorker && win instanceof Ci.nsIDOMWindow) {
+ const docShell = win.docShell;
+ const channel = docShell.currentDocumentChannel;
+ principal = channel.loadInfo.loadingPrincipal;
+
+ // Retrieve the cacheKey in order to load POST requests from cache
+ // Note that chrome:// URLs don't support this interface.
+ if (
+ loadFromCache &&
+ docShell.currentDocumentChannel instanceof Ci.nsICacheInfoChannel
+ ) {
+ cacheKey = docShell.currentDocumentChannel.cacheKey;
+ }
+ }
+
+ let result;
+ try {
+ result = await fetch(url, {
+ principal,
+ cacheKey,
+ loadFromCache,
+ });
+ } catch (error) {
+ this._reportLoadSourceError(error);
+ throw error;
+ }
+
+ // When we fetch the contents, there is a risk that the contents we get
+ // do not match up with the actual text of the sources these contents will
+ // be associated with. We want to always show contents that include that
+ // actual text (otherwise it will be very confusing or unusable for users),
+ // so replace the contents with the actual text if there is a mismatch.
+ const actors = [...this._sourceActors.values()].filter(
+ actor => actor.url == url
+ );
+ if (!actors.every(actor => actor.contentMatches(result))) {
+ if (actors.length > 1) {
+ // When there are multiple actors we won't be able to show the source
+ // for all of them. Ask the user to reload so that we don't have to do
+ // any fetching.
+ result.content = "Error: Incorrect contents fetched, please reload.";
+ } else {
+ result.content = actors[0].actualText();
+ }
+ }
+
+ this._urlContents.set(url, { ...result, complete: true });
+
+ return result;
+ }
+
+ _reportLoadSourceError(error) {
+ try {
+ DevToolsUtils.reportException("SourceActor", error);
+
+ const lines = JSON.stringify(this.form(), null, 4).split(/\n/g);
+ lines.forEach(line => console.error("\t", line));
+ } catch (e) {
+ // ignore
+ }
+ }
+}
+
+/*
+ * Checks if a source should never be displayed to the user because
+ * it's either internal or we don't support in the UI yet.
+ */
+function isHiddenSource(source) {
+ return source.introductionType === "Function.prototype";
+}
+
+function isLocationInRange({ line, column }, range) {
+ return (
+ (range.start.line <= line ||
+ (range.start.line == line && range.start.column <= column)) &&
+ (range.end.line >= line ||
+ (range.end.line == line && range.end.column >= column))
+ );
+}
+
+exports.SourcesManager = SourcesManager;
+exports.isHiddenSource = isHiddenSource;
diff --git a/devtools/server/actors/utils/stack.js b/devtools/server/actors/utils/stack.js
new file mode 100644
index 0000000000..6a216b252c
--- /dev/null
+++ b/devtools/server/actors/utils/stack.js
@@ -0,0 +1,183 @@
+/* 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";
+
+/**
+ * A helper class that stores stack frame objects. Each frame is
+ * assigned an index, and if a frame is added more than once, the same
+ * index is used. Users of the class can get an array of all frames
+ * that have been added.
+ */
+class StackFrameCache {
+ /**
+ * Initialize this object.
+ */
+ constructor() {
+ this._framesToIndices = null;
+ this._framesToForms = null;
+ this._lastEventSize = 0;
+ }
+
+ /**
+ * Prepare to accept frames.
+ */
+ initFrames() {
+ if (this._framesToIndices) {
+ // The maps are already initialized.
+ return;
+ }
+
+ this._framesToIndices = new Map();
+ this._framesToForms = new Map();
+ this._lastEventSize = 0;
+ }
+
+ /**
+ * Forget all stored frames and reset to the initialized state.
+ */
+ clearFrames() {
+ this._framesToIndices.clear();
+ this._framesToIndices = null;
+ this._framesToForms.clear();
+ this._framesToForms = null;
+ this._lastEventSize = 0;
+ }
+
+ /**
+ * Add a frame to this stack frame cache, and return the index of
+ * the frame.
+ */
+ addFrame(frame) {
+ this._assignFrameIndices(frame);
+ this._createFrameForms(frame);
+ return this._framesToIndices.get(frame);
+ }
+
+ /**
+ * A helper method for the memory actor. This populates the packet
+ * object with "frames" property. Each of these
+ * properties will be an array indexed by frame ID. "frames" will
+ * contain frame objects (see makeEvent).
+ *
+ * @param packet
+ * The packet to update.
+ *
+ * @returns packet
+ */
+ updateFramePacket(packet) {
+ // Now that we are guaranteed to have a form for every frame, we know the
+ // size the "frames" property's array must be. We use that information to
+ // create dense arrays even though we populate them out of order.
+ const size = this._framesToForms.size;
+ packet.frames = Array(size).fill(null);
+
+ // Populate the "frames" properties.
+ for (const [stack, index] of this._framesToIndices) {
+ packet.frames[index] = this._framesToForms.get(stack);
+ }
+
+ return packet;
+ }
+
+ /**
+ * If any new stack frames have been added to this cache since the
+ * last call to makeEvent (clearing the cache also resets the "last
+ * call"), then return a new array describing the new frames. If no
+ * new frames are available, return null.
+ *
+ * The frame cache assumes that the user of the cache keeps track of
+ * all previously-returned arrays and, in theory, concatenates them
+ * all to form a single array holding all frames added to the cache
+ * since the last reset. This concatenated array can be indexed by
+ * the frame ID. The array returned by this function, though, is
+ * dense and starts at 0.
+ *
+ * Each element in the array is an object of the form:
+ * {
+ * line: <line number for this frame>,
+ * column: <column number for this frame>,
+ * source: <filename string for this frame>,
+ * functionDisplayName: <this frame's inferred function name function or null>,
+ * parent: <frame ID -- an index into the concatenated array mentioned above>
+ * asyncCause: the async cause, or null
+ * asyncParent: <frame ID -- an index into the concatenated array mentioned above>
+ * }
+ *
+ * The intent of this approach is to make it simpler to efficiently
+ * send frame information over the debugging protocol, by only
+ * sending new frames.
+ *
+ * @returns array or null
+ */
+ makeEvent() {
+ const size = this._framesToForms.size;
+ if (!size || size <= this._lastEventSize) {
+ return null;
+ }
+
+ const packet = Array(size - this._lastEventSize).fill(null);
+ for (const [stack, index] of this._framesToIndices) {
+ if (index >= this._lastEventSize) {
+ packet[index - this._lastEventSize] = this._framesToForms.get(stack);
+ }
+ }
+
+ this._lastEventSize = size;
+
+ return packet;
+ }
+
+ /**
+ * Assigns an index to the given frame and its parents, if an index is not
+ * already assigned.
+ *
+ * @param SavedFrame frame
+ * A frame to assign an index to.
+ */
+ _assignFrameIndices(frame) {
+ if (this._framesToIndices.has(frame)) {
+ return;
+ }
+
+ if (frame) {
+ this._assignFrameIndices(frame.parent);
+ this._assignFrameIndices(frame.asyncParent);
+ }
+
+ const index = this._framesToIndices.size;
+ this._framesToIndices.set(frame, index);
+ }
+
+ /**
+ * Create the form for the given frame, if one doesn't already exist.
+ *
+ * @param SavedFrame frame
+ * A frame to create a form for.
+ */
+ _createFrameForms(frame) {
+ if (this._framesToForms.has(frame)) {
+ return;
+ }
+
+ let form = null;
+ if (frame) {
+ form = {
+ line: frame.line,
+ column: frame.column,
+ source: frame.source,
+ functionDisplayName: frame.functionDisplayName,
+ parent: this._framesToIndices.get(frame.parent),
+ asyncParent: this._framesToIndices.get(frame.asyncParent),
+ asyncCause: frame.asyncCause,
+ };
+ this._createFrameForms(frame.parent);
+ this._createFrameForms(frame.asyncParent);
+ }
+
+ this._framesToForms.set(frame, form);
+ }
+}
+
+exports.StackFrameCache = StackFrameCache;
diff --git a/devtools/server/actors/utils/style-utils.js b/devtools/server/actors/utils/style-utils.js
new file mode 100644
index 0000000000..bd7520ed15
--- /dev/null
+++ b/devtools/server/actors/utils/style-utils.js
@@ -0,0 +1,185 @@
+/* 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";
+
+const { getCSSLexer } = require("devtools/shared/css/lexer");
+
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+const FONT_PREVIEW_TEXT = "Abc";
+const FONT_PREVIEW_FONT_SIZE = 40;
+const FONT_PREVIEW_FILLSTYLE = "black";
+// Offset (in px) to avoid cutting off text edges of italic fonts.
+const FONT_PREVIEW_OFFSET = 4;
+
+/**
+ * Helper function for getting an image preview of the given font.
+ *
+ * @param font {string}
+ * Name of font to preview
+ * @param doc {Document}
+ * Document to use to render font
+ * @param options {object}
+ * Object with options 'previewText' and 'previewFontSize'
+ *
+ * @return dataUrl
+ * The data URI of the font preview image
+ */
+function getFontPreviewData(font, doc, options) {
+ options = options || {};
+ const previewText = options.previewText || FONT_PREVIEW_TEXT;
+ const previewFontSize = options.previewFontSize || FONT_PREVIEW_FONT_SIZE;
+ const fillStyle = options.fillStyle || FONT_PREVIEW_FILLSTYLE;
+ const fontStyle = options.fontStyle || "";
+
+ const canvas = doc.createElementNS(XHTML_NS, "canvas");
+ const ctx = canvas.getContext("2d");
+ const fontValue =
+ fontStyle + " " + previewFontSize + "px " + font + ", serif";
+
+ // Get the correct preview text measurements and set the canvas dimensions
+ ctx.font = fontValue;
+ ctx.fillStyle = fillStyle;
+ const textWidth = Math.round(ctx.measureText(previewText).width);
+
+ canvas.width = textWidth * 2 + FONT_PREVIEW_OFFSET * 4;
+ canvas.height = previewFontSize * 3;
+
+ // we have to reset these after changing the canvas size
+ ctx.font = fontValue;
+ ctx.fillStyle = fillStyle;
+
+ // Oversample the canvas for better text quality
+ ctx.textBaseline = "top";
+ ctx.scale(2, 2);
+ ctx.fillText(
+ previewText,
+ FONT_PREVIEW_OFFSET,
+ Math.round(previewFontSize / 3)
+ );
+
+ const dataURL = canvas.toDataURL("image/png");
+
+ return {
+ dataURL: dataURL,
+ size: textWidth + FONT_PREVIEW_OFFSET * 2,
+ };
+}
+
+exports.getFontPreviewData = getFontPreviewData;
+
+/**
+ * Get the text content of a rule given some CSS text, a line and a column
+ * Consider the following example:
+ * body {
+ * color: red;
+ * }
+ * p {
+ * line-height: 2em;
+ * color: blue;
+ * }
+ * Calling the function with the whole text above and line=4 and column=1 would
+ * return "line-height: 2em; color: blue;"
+ * @param {String} initialText
+ * @param {Number} line (1-indexed)
+ * @param {Number} column (1-indexed)
+ * @return {object} An object of the form {offset: number, text: string}
+ * The offset is the index into the input string where
+ * the rule text started. The text is the content of
+ * the rule.
+ */
+function getRuleText(initialText, line, column) {
+ if (typeof line === "undefined" || typeof column === "undefined") {
+ throw new Error("Location information is missing");
+ }
+
+ const { offset: textOffset, text } = getTextAtLineColumn(
+ initialText,
+ line,
+ column
+ );
+ const lexer = getCSSLexer(text);
+
+ // Search forward for the opening brace.
+ while (true) {
+ const token = lexer.nextToken();
+ if (!token) {
+ throw new Error("couldn't find start of the rule");
+ }
+ if (token.tokenType === "symbol" && token.text === "{") {
+ break;
+ }
+ }
+
+ // Now collect text until we see the matching close brace.
+ let braceDepth = 1;
+ let startOffset, endOffset;
+ while (true) {
+ const token = lexer.nextToken();
+ if (!token) {
+ break;
+ }
+ if (startOffset === undefined) {
+ startOffset = token.startOffset;
+ }
+ if (token.tokenType === "symbol") {
+ if (token.text === "{") {
+ ++braceDepth;
+ } else if (token.text === "}") {
+ --braceDepth;
+ if (braceDepth == 0) {
+ break;
+ }
+ }
+ }
+ endOffset = token.endOffset;
+ }
+
+ // If the rule was of the form "selector {" with no closing brace
+ // and no properties, just return an empty string.
+ if (startOffset === undefined) {
+ return { offset: 0, text: "" };
+ }
+ // If the input didn't have any tokens between the braces (e.g.,
+ // "div {}"), then the endOffset won't have been set yet; so account
+ // for that here.
+ if (endOffset === undefined) {
+ endOffset = startOffset;
+ }
+
+ // Note that this approach will preserve comments, despite the fact
+ // that cssTokenizer skips them.
+ return {
+ offset: textOffset + startOffset,
+ text: text.substring(startOffset, endOffset),
+ };
+}
+
+exports.getRuleText = getRuleText;
+
+/**
+ * Return the offset and substring of |text| that starts at the given
+ * line and column.
+ * @param {String} text
+ * @param {Number} line (1-indexed)
+ * @param {Number} column (1-indexed)
+ * @return {object} An object of the form {offset: number, text: string},
+ * where the offset is the offset into the input string
+ * where the text starts, and where text is the text.
+ */
+function getTextAtLineColumn(text, line, column) {
+ let offset;
+ if (line > 1) {
+ const rx = new RegExp(
+ "(?:[^\\r\\n\\f]*(?:\\r\\n|\\n|\\r|\\f)){" + (line - 1) + "}"
+ );
+ offset = rx.exec(text)[0].length;
+ } else {
+ offset = 0;
+ }
+ offset += column - 1;
+ return { offset: offset, text: text.substr(offset) };
+}
+
+exports.getTextAtLineColumn = getTextAtLineColumn;
diff --git a/devtools/server/actors/utils/track-change-emitter.js b/devtools/server/actors/utils/track-change-emitter.js
new file mode 100644
index 0000000000..e2b34c3b0c
--- /dev/null
+++ b/devtools/server/actors/utils/track-change-emitter.js
@@ -0,0 +1,26 @@
+/* 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";
+
+const EventEmitter = require("devtools/shared/event-emitter");
+
+/**
+ * A helper class that is listened to by the ChangesActor, and can be
+ * used to send changes to the ChangesActor.
+ */
+class TrackChangeEmitter {
+ /**
+ * Initialize this object.
+ */
+ constructor() {
+ EventEmitter.decorate(this);
+ }
+
+ trackChange(change) {
+ this.emit("track-change", change);
+ }
+}
+
+module.exports = new TrackChangeEmitter();
diff --git a/devtools/server/actors/utils/walker-search.js b/devtools/server/actors/utils/walker-search.js
new file mode 100644
index 0000000000..3e75524c12
--- /dev/null
+++ b/devtools/server/actors/utils/walker-search.js
@@ -0,0 +1,313 @@
+/* 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";
+
+loader.lazyRequireGetter(
+ this,
+ "isWhitespaceTextNode",
+ "devtools/server/actors/inspector/utils",
+ true
+);
+
+/**
+ * The walker-search module provides a simple API to index and search strings
+ * and elements inside a given document.
+ * It indexes tag names, attribute names and values, and text contents.
+ * It provides a simple search function that returns a list of nodes that
+ * matched.
+ */
+
+/**
+ * The WalkerIndex class indexes the document (and all subdocs) from
+ * a given walker.
+ *
+ * It is only indexed the first time the data is accessed and will be
+ * re-indexed if a mutation happens between requests.
+ *
+ * @param {Walker} walker The walker to be indexed
+ */
+function WalkerIndex(walker) {
+ this.walker = walker;
+ this.clearIndex = this.clearIndex.bind(this);
+
+ // Kill the index when mutations occur, the next data get will re-index.
+ this.walker.on("any-mutation", this.clearIndex);
+}
+
+WalkerIndex.prototype = {
+ /**
+ * Destroy this instance, releasing all data and references
+ */
+ destroy: function() {
+ this.walker.off("any-mutation", this.clearIndex);
+ },
+
+ clearIndex: function() {
+ if (!this.currentlyIndexing) {
+ this._data = null;
+ }
+ },
+
+ get doc() {
+ return this.walker.rootDoc;
+ },
+
+ /**
+ * Get the indexed data
+ * This getter also indexes if it hasn't been done yet or if the state is
+ * dirty
+ *
+ * @returns Map<String, Array<{type:String, node:DOMNode}>>
+ * A Map keyed on the searchable value, containing an array with
+ * objects containing the 'type' (one of ALL_RESULTS_TYPES), and
+ * the DOM Node.
+ */
+ get data() {
+ if (!this._data) {
+ this._data = new Map();
+ this.index();
+ }
+
+ return this._data;
+ },
+
+ _addToIndex: function(type, node, value) {
+ // Add an entry for this value if there isn't one
+ const entry = this._data.get(value);
+ if (!entry) {
+ this._data.set(value, []);
+ }
+
+ // Add the type/node to the list
+ this._data.get(value).push({
+ type: type,
+ node: node,
+ });
+ },
+
+ index: function() {
+ // Handle case where iterating nextNode() with the deepTreeWalker triggers
+ // a mutation (Bug 1222558)
+ this.currentlyIndexing = true;
+
+ const documentWalker = this.walker.getDocumentWalker(this.doc);
+ while (documentWalker.nextNode()) {
+ const node = documentWalker.currentNode;
+
+ if (node.nodeType === 1) {
+ // For each element node, we get the tagname and all attributes names
+ // and values
+ const localName = node.localName;
+ if (localName === "_moz_generated_content_marker") {
+ this._addToIndex("tag", node, "::marker");
+ this._addToIndex("text", node, node.textContent.trim());
+ } else if (localName === "_moz_generated_content_before") {
+ this._addToIndex("tag", node, "::before");
+ this._addToIndex("text", node, node.textContent.trim());
+ } else if (localName === "_moz_generated_content_after") {
+ this._addToIndex("tag", node, "::after");
+ this._addToIndex("text", node, node.textContent.trim());
+ } else {
+ this._addToIndex("tag", node, node.localName);
+ }
+
+ for (const { name, value } of node.attributes) {
+ this._addToIndex("attributeName", node, name);
+ this._addToIndex("attributeValue", node, value);
+ }
+ } else if (node.textContent && node.textContent.trim().length) {
+ // For comments and text nodes, we get the text
+ this._addToIndex("text", node, node.textContent.trim());
+ }
+ }
+
+ this.currentlyIndexing = false;
+ },
+};
+
+exports.WalkerIndex = WalkerIndex;
+
+/**
+ * The WalkerSearch class provides a way to search an indexed document as well
+ * as find elements that match a given css selector.
+ *
+ * Usage example:
+ * let s = new WalkerSearch(doc);
+ * let res = s.search("lang", index);
+ * for (let {matched, results} of res) {
+ * for (let {node, type} of results) {
+ * console.log("The query matched a node's " + type);
+ * console.log("Node that matched", node);
+ * }
+ * }
+ * s.destroy();
+ *
+ * @param {Walker} the walker to be searched
+ */
+function WalkerSearch(walker) {
+ this.walker = walker;
+ this.index = new WalkerIndex(this.walker);
+}
+
+WalkerSearch.prototype = {
+ destroy: function() {
+ this.index.destroy();
+ this.walker = null;
+ },
+
+ _addResult: function(node, type, results) {
+ if (!results.has(node)) {
+ results.set(node, []);
+ }
+
+ const matches = results.get(node);
+
+ // Do not add if the exact same result is already in the list
+ let isKnown = false;
+ for (const match of matches) {
+ if (match.type === type) {
+ isKnown = true;
+ break;
+ }
+ }
+
+ if (!isKnown) {
+ matches.push({ type });
+ }
+ },
+
+ _searchIndex: function(query, options, results) {
+ for (const [matched, res] of this.index.data) {
+ if (!options.searchMethod(query, matched)) {
+ continue;
+ }
+
+ // Add any relevant results (skipping non-requested options).
+ res
+ .filter(entry => {
+ return options.types.includes(entry.type);
+ })
+ .forEach(({ node, type }) => {
+ this._addResult(node, type, results);
+ });
+ }
+ },
+
+ _searchSelectors: function(query, options, results) {
+ // If the query is just one "word", no need to search because _searchIndex
+ // will lead the same results since it has access to tagnames anyway
+ const isSelector = query && query.match(/[ >~.#\[\]]/);
+ if (!options.types.includes("selector") || !isSelector) {
+ return;
+ }
+
+ const nodes = this.walker._multiFrameQuerySelectorAll(query);
+ for (const node of nodes) {
+ this._addResult(node, "selector", results);
+ }
+ },
+
+ _searchXPath: function(query, options, results) {
+ if (!options.types.includes("xpath")) {
+ return;
+ }
+
+ const nodes = this.walker._multiFrameXPath(query);
+ for (const node of nodes) {
+ // Exclude text nodes that only contain whitespace
+ // because they are not displayed in the Inspector.
+ if (!isWhitespaceTextNode(node)) {
+ this._addResult(node, "xpath", results);
+ }
+ }
+ },
+
+ /**
+ * Search the document
+ * @param {String} query What to search for
+ * @param {Object} options The following options are accepted:
+ * - searchMethod {String} one of WalkerSearch.SEARCH_METHOD_*
+ * defaults to WalkerSearch.SEARCH_METHOD_CONTAINS (does not apply to
+ * selector and XPath search types)
+ * - types {Array} a list of things to search for (tag, text, attributes, etc)
+ * defaults to WalkerSearch.ALL_RESULTS_TYPES
+ * @return {Array} An array is returned with each item being an object like:
+ * {
+ * node: <the dom node that matched>,
+ * type: <the type of match: one of WalkerSearch.ALL_RESULTS_TYPES>
+ * }
+ */
+ search: function(query, options = {}) {
+ options.searchMethod =
+ options.searchMethod || WalkerSearch.SEARCH_METHOD_CONTAINS;
+ options.types = options.types || WalkerSearch.ALL_RESULTS_TYPES;
+
+ // Empty strings will return no results, as will non-string input
+ if (typeof query !== "string") {
+ query = "";
+ }
+
+ // Store results in a map indexed by nodes to avoid duplicate results
+ const results = new Map();
+
+ // Search through the indexed data
+ this._searchIndex(query, options, results);
+
+ // Search with querySelectorAll
+ this._searchSelectors(query, options, results);
+
+ // Search with XPath
+ this._searchXPath(query, options, results);
+
+ // Concatenate all results into an Array to return
+ const resultList = [];
+ for (const [node, matches] of results) {
+ for (const { type } of matches) {
+ resultList.push({
+ node: node,
+ type: type,
+ });
+
+ // For now, just do one result per node since the frontend
+ // doesn't have a way to highlight each result individually
+ // yet.
+ break;
+ }
+ }
+
+ const documents = this.walker.targetActor.windows.map(win => win.document);
+
+ // Sort the resulting nodes by order of appearance in the DOM
+ resultList.sort((a, b) => {
+ // Disconnected nodes won't get good results from compareDocumentPosition
+ // so check the order of their document instead.
+ if (a.node.ownerDocument != b.node.ownerDocument) {
+ const indA = documents.indexOf(a.node.ownerDocument);
+ const indB = documents.indexOf(b.node.ownerDocument);
+ return indA - indB;
+ }
+ // If the same document, then sort on DOCUMENT_POSITION_FOLLOWING (4)
+ // which means B is after A.
+ return a.node.compareDocumentPosition(b.node) & 4 ? -1 : 1;
+ });
+
+ return resultList;
+ },
+};
+
+WalkerSearch.SEARCH_METHOD_CONTAINS = (query, candidate) => {
+ return query && candidate.toLowerCase().includes(query.toLowerCase());
+};
+
+WalkerSearch.ALL_RESULTS_TYPES = [
+ "tag",
+ "text",
+ "attributeName",
+ "attributeValue",
+ "selector",
+ "xpath",
+];
+
+exports.WalkerSearch = WalkerSearch;
diff --git a/devtools/server/actors/utils/watchpoint-map.js b/devtools/server/actors/utils/watchpoint-map.js
new file mode 100644
index 0000000000..d053fa3b71
--- /dev/null
+++ b/devtools/server/actors/utils/watchpoint-map.js
@@ -0,0 +1,163 @@
+/* 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";
+
+class WatchpointMap {
+ constructor(threadActor) {
+ this.threadActor = threadActor;
+ this._watchpoints = new Map();
+ }
+
+ _setWatchpoint(objActor, data) {
+ const { property, label, watchpointType } = data;
+ const obj = objActor.rawValue();
+
+ const desc = objActor.obj.getOwnPropertyDescriptor(property);
+
+ if (this.has(obj, property) || desc.set || desc.get || !desc.configurable) {
+ return null;
+ }
+
+ function getValue() {
+ return typeof desc.value === "object" && desc.value
+ ? desc.value.unsafeDereference()
+ : desc.value;
+ }
+
+ function setValue(v) {
+ desc.value = objActor.obj.makeDebuggeeValue(v);
+ }
+
+ const maybeHandlePause = type => {
+ const frame = this.threadActor.dbg.getNewestFrame();
+
+ if (
+ !this.threadActor.hasMoved(frame, type) ||
+ this.threadActor.skipBreakpointsOption ||
+ this.threadActor.sourcesManager.isFrameBlackBoxed(frame)
+ ) {
+ return;
+ }
+
+ this.threadActor._pauseAndRespond(frame, {
+ type: type,
+ message: label,
+ });
+ };
+
+ if (watchpointType === "get") {
+ objActor.obj.defineProperty(property, {
+ configurable: desc.configurable,
+ enumerable: desc.enumerable,
+ set: objActor.obj.makeDebuggeeValue(v => {
+ setValue(v);
+ }),
+ get: objActor.obj.makeDebuggeeValue(() => {
+ maybeHandlePause("getWatchpoint");
+ return getValue();
+ }),
+ });
+ }
+
+ if (watchpointType === "set") {
+ objActor.obj.defineProperty(property, {
+ configurable: desc.configurable,
+ enumerable: desc.enumerable,
+ set: objActor.obj.makeDebuggeeValue(v => {
+ maybeHandlePause("setWatchpoint");
+ setValue(v);
+ }),
+ get: objActor.obj.makeDebuggeeValue(() => {
+ return getValue();
+ }),
+ });
+ }
+
+ if (watchpointType === "getorset") {
+ objActor.obj.defineProperty(property, {
+ configurable: desc.configurable,
+ enumerable: desc.enumerable,
+ set: objActor.obj.makeDebuggeeValue(v => {
+ maybeHandlePause("setWatchpoint");
+ setValue(v);
+ }),
+ get: objActor.obj.makeDebuggeeValue(() => {
+ maybeHandlePause("getWatchpoint");
+ return getValue();
+ }),
+ });
+ }
+
+ return desc;
+ }
+
+ add(objActor, data) {
+ // Get the object's description before calling setWatchpoint,
+ // otherwise we'll get the modified property descriptor instead
+ const desc = this._setWatchpoint(objActor, data);
+ if (!desc) {
+ return;
+ }
+
+ const objWatchpoints =
+ this._watchpoints.get(objActor.rawValue()) || new Map();
+
+ objWatchpoints.set(data.property, { ...data, desc });
+ this._watchpoints.set(objActor.rawValue(), objWatchpoints);
+ }
+
+ has(obj, property) {
+ const objWatchpoints = this._watchpoints.get(obj);
+ return objWatchpoints && objWatchpoints.has(property);
+ }
+
+ get(obj, property) {
+ const objWatchpoints = this._watchpoints.get(obj);
+ return objWatchpoints && objWatchpoints.get(property);
+ }
+
+ remove(objActor, property) {
+ const obj = objActor.rawValue();
+
+ // This should remove watchpoints on all of the object's properties if
+ // a property isn't passed in as an argument
+ if (!property) {
+ for (const objProperty in obj) {
+ this.remove(objActor, objProperty);
+ }
+ }
+
+ if (!this.has(obj, property)) {
+ return;
+ }
+
+ const objWatchpoints = this._watchpoints.get(obj);
+ const { desc } = objWatchpoints.get(property);
+
+ objWatchpoints.delete(property);
+ this._watchpoints.set(obj, objWatchpoints);
+
+ // We should stop keeping track of an object if it no longer
+ // has a watchpoint
+ if (objWatchpoints.size == 0) {
+ this._watchpoints.delete(obj);
+ }
+
+ objActor.obj.defineProperty(property, desc);
+ }
+
+ removeAll(objActor) {
+ const objWatchpoints = this._watchpoints.get(objActor.rawValue());
+ if (!objWatchpoints) {
+ return;
+ }
+
+ for (const objProperty in objWatchpoints) {
+ this.remove(objActor, objProperty);
+ }
+ }
+}
+
+exports.WatchpointMap = WatchpointMap;
diff --git a/devtools/server/actors/watcher.js b/devtools/server/actors/watcher.js
new file mode 100644
index 0000000000..9ddc365c4d
--- /dev/null
+++ b/devtools/server/actors/watcher.js
@@ -0,0 +1,530 @@
+/* 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";
+const protocol = require("devtools/shared/protocol");
+const { watcherSpec } = require("devtools/shared/specs/watcher");
+const Services = require("Services");
+
+const Resources = require("devtools/server/actors/resources/index");
+const {
+ TargetActorRegistry,
+} = require("devtools/server/actors/targets/target-actor-registry.jsm");
+const {
+ WatcherRegistry,
+} = require("devtools/server/actors/watcher/WatcherRegistry.jsm");
+const Targets = require("devtools/server/actors/targets/index");
+
+const TARGET_HELPERS = {};
+loader.lazyRequireGetter(
+ TARGET_HELPERS,
+ Targets.TYPES.FRAME,
+ "devtools/server/actors/watcher/target-helpers/frame-helper"
+);
+loader.lazyRequireGetter(
+ TARGET_HELPERS,
+ Targets.TYPES.PROCESS,
+ "devtools/server/actors/watcher/target-helpers/process-helper"
+);
+loader.lazyRequireGetter(
+ TARGET_HELPERS,
+ Targets.TYPES.WORKER,
+ "devtools/server/actors/watcher/target-helpers/worker-helper"
+);
+
+loader.lazyRequireGetter(
+ this,
+ "NetworkParentActor",
+ "devtools/server/actors/network-monitor/network-parent",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "BreakpointListActor",
+ "devtools/server/actors/breakpoint-list",
+ true
+);
+
+exports.WatcherActor = protocol.ActorClassWithSpec(watcherSpec, {
+ /**
+ * Optionally pass a `browser` in the second argument
+ * in order to focus only on targets related to a given <browser> element.
+ */
+ initialize: function(conn, options) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this._browser = options && options.browser;
+
+ this.notifyResourceAvailable = this.notifyResourceAvailable.bind(this);
+ this.notifyResourceDestroyed = this.notifyResourceDestroyed.bind(this);
+ this.notifyResourceUpdated = this.notifyResourceUpdated.bind(this);
+ },
+
+ /**
+ * If we are debugging only one Tab or Document, returns its BrowserElement.
+ * For Tabs, it will be the <browser> element used to load the web page.
+ *
+ * This is typicaly used to fetch:
+ * - its `browserId` attribute, which uniquely defines it,
+ * - its `browsingContextID` or `browsingContext`, which helps inspecting its content.
+ */
+ get browserElement() {
+ return this._browser;
+ },
+
+ /**
+ * Unique identifier, which helps designates one precise browser element, the one
+ * we may debug. This is only set if we actually debug a browser element.
+ * So, that will be typically set when we debug a tab, but not when we debug
+ * a process, or a worker.
+ */
+ get browserId() {
+ return this._browser?.browserId;
+ },
+
+ destroy: function() {
+ // Force unwatching for all types, even if we weren't watching.
+ // This is fine as unwatchTarget is NOOP if we weren't already watching for this target type.
+ for (const targetType of Object.values(Targets.TYPES)) {
+ this.unwatchTargets(targetType);
+ }
+ this.unwatchResources(Object.values(Resources.TYPES));
+
+ WatcherRegistry.unregisterWatcher(this);
+
+ // Destroy the actor at the end so that its actorID keeps being defined.
+ protocol.Actor.prototype.destroy.call(this);
+ },
+
+ /*
+ * Get the list of the currently watched resources for this watcher.
+ *
+ * @return Array<String>
+ * Returns the list of currently watched resource types.
+ */
+ get watchedData() {
+ return WatcherRegistry.getWatchedData(this);
+ },
+
+ form() {
+ const enableServerWatcher = Services.prefs.getBoolPref(
+ "devtools.testing.enableServerWatcherSupport",
+ false
+ );
+
+ const hasBrowserElement = !!this.browserElement;
+
+ return {
+ actor: this.actorID,
+ // The resources and target traits should be removed all at the same time since the
+ // client has generic ways to deal with all of them (See Bug 1680280).
+ traits: {
+ [Targets.TYPES.FRAME]: true,
+ [Targets.TYPES.PROCESS]: true,
+ [Targets.TYPES.WORKER]: hasBrowserElement,
+ resources: {
+ // In Firefox 81 we added support for:
+ // - CONSOLE_MESSAGE
+ // - CSS_CHANGE
+ // - CSS_MESSAGE
+ // - DOCUMENT_EVENT
+ // - ERROR_MESSAGE
+ // - PLATFORM_MESSAGE
+ //
+ // We enabled them for content toolboxes only because we don't support
+ // content process targets yet. Bug 1620248 should help supporting
+ // them and enable this more broadly.
+ //
+ // New server-side resources can be gated behind
+ // `devtools.testing.enableServerWatcherSupport` if needed.
+ [Resources.TYPES.CONSOLE_MESSAGE]: hasBrowserElement,
+ [Resources.TYPES.CSS_CHANGE]: hasBrowserElement,
+ [Resources.TYPES.CSS_MESSAGE]: hasBrowserElement,
+ [Resources.TYPES.DOCUMENT_EVENT]: hasBrowserElement,
+ [Resources.TYPES.ERROR_MESSAGE]: hasBrowserElement,
+ [Resources.TYPES.LOCAL_STORAGE]: hasBrowserElement,
+ [Resources.TYPES.SESSION_STORAGE]: hasBrowserElement,
+ [Resources.TYPES.PLATFORM_MESSAGE]: true,
+ [Resources.TYPES.NETWORK_EVENT]: hasBrowserElement,
+ [Resources.TYPES.NETWORK_EVENT_STACKTRACE]: hasBrowserElement,
+ [Resources.TYPES.STYLESHEET]:
+ enableServerWatcher && hasBrowserElement,
+ [Resources.TYPES.SOURCE]: hasBrowserElement,
+ },
+ // @backward-compat { version 85 } When removing this trait, consumers using
+ // the TargetList to retrieve the Breakpoints front should still be careful to check
+ // that the Watcher is available
+ "set-breakpoints": true,
+ },
+ };
+ },
+
+ /**
+ * Start watching for a new target type.
+ *
+ * This will instantiate Target Actors for existing debugging context of this type,
+ * but will also create actors as context of this type get created.
+ * The actors are notified to the client via "target-available-form" RDP events.
+ * We also notify about target actors destruction via "target-destroyed-form".
+ * Note that we are guaranteed to receive all existing target actor by the time this method
+ * resolves.
+ *
+ * @param {string} targetType
+ * Type of context to observe. See Targets.TYPES object.
+ */
+ async watchTargets(targetType) {
+ WatcherRegistry.watchTargets(this, targetType);
+
+ const targetHelperModule = TARGET_HELPERS[targetType];
+ // Await the registration in order to ensure receiving the already existing targets
+ await targetHelperModule.createTargets(this);
+ },
+
+ /**
+ * Stop watching for a given target type.
+ *
+ * @param {string} targetType
+ * Type of context to observe. See Targets.TYPES object.
+ */
+ unwatchTargets(targetType) {
+ const isWatchingTargets = WatcherRegistry.unwatchTargets(this, targetType);
+ if (!isWatchingTargets) {
+ return;
+ }
+
+ const targetHelperModule = TARGET_HELPERS[targetType];
+ targetHelperModule.destroyTargets(this);
+
+ // Unregister the JS Window Actor if there is no more DevTools code observing any target/resource
+ WatcherRegistry.maybeUnregisteringJSWindowActor();
+ },
+
+ /**
+ * Called by a Watcher module, whenever a new target is available
+ */
+ notifyTargetAvailable(actor) {
+ this.emit("target-available-form", actor);
+ },
+
+ /**
+ * Called by a Watcher module, whenever a target has been destroyed
+ */
+ notifyTargetDestroyed(actor) {
+ this.emit("target-destroyed-form", actor);
+ },
+
+ /**
+ * Given a browsingContextID, returns its parent browsingContextID. Returns null if a
+ * parent browsing context couldn't be found. Throws if the browsing context
+ * corresponding to the passed browsingContextID couldn't be found.
+ *
+ * @param {Integer} browsingContextID
+ * @returns {Integer|null}
+ */
+ getParentBrowsingContextID(browsingContextID) {
+ const browsingContext = BrowsingContext.get(browsingContextID);
+ if (!browsingContext) {
+ throw new Error(
+ `BrowsingContext with ID=${browsingContextID} doesn't exist.`
+ );
+ }
+ // Top-level documents of tabs, loaded in a <browser> element expose a null `parent`.
+ // i.e. Their BrowsingContext has no parent and is considered top level.
+ // But... in the context of the Browser Toolbox, we still consider them as child of the browser window.
+ // So, for them, fallback on `embedderWindowGlobal`, which will typically be the WindowGlobal for browser.xhtml.
+ if (browsingContext.parent) {
+ return browsingContext.parent.id;
+ }
+ if (browsingContext.embedderWindowGlobal) {
+ return browsingContext.embedderWindowGlobal.browsingContext.id;
+ }
+ return null;
+ },
+
+ /**
+ * Called by Resource Watchers, when new resources are available.
+ *
+ * @param Array<json> resources
+ * List of all available resources. A resource is a JSON object piped over to the client.
+ * It may contain actor IDs, actor forms, to be manually marshalled by the client.
+ */
+ notifyResourceAvailable(resources) {
+ this._emitResourcesForm("resource-available-form", resources);
+ },
+
+ notifyResourceDestroyed(resources) {
+ this._emitResourcesForm("resource-destroyed-form", resources);
+ },
+
+ notifyResourceUpdated(resources) {
+ this._emitResourcesForm("resource-updated-form", resources);
+ },
+
+ /**
+ * Wrapper around emit for resource forms.
+ */
+ _emitResourcesForm(name, resources) {
+ if (resources.length === 0) {
+ // Don't try to emit if the resources array is empty.
+ return;
+ }
+ this.emit(name, resources);
+ },
+
+ /**
+ * Try to retrieve a parent process TargetActor:
+ * - either when debugging a parent process page (when browserElement is set to the page's tab),
+ * - or when debugging the main process (when browserElement is null).
+ *
+ * See comment in `watchResources`, this will handle targets which are ignored by Frame and Process
+ * target helpers. (and only those which are ignored)
+ */
+ _getTargetActorInParentProcess() {
+ return this.browserElement
+ ? // Note: if any, the BrowsingContextTargetActor returned here is created for a parent process
+ // page and lives in the parent process.
+ TargetActorRegistry.getTargetActor(this.browserId)
+ : TargetActorRegistry.getParentProcessTargetActor();
+ },
+
+ /**
+ * Start watching for a list of resource types.
+ * This should only resolve once all "already existing" resources of these types
+ * are notified to the client via resource-available-form event on related target actors.
+ *
+ * @param {Array<string>} resourceTypes
+ * List of all types to listen to.
+ */
+ async watchResources(resourceTypes) {
+ // First process resources which have to be listened from the parent process
+ // (the watcher actor always runs in the parent process)
+ await Resources.watchResources(
+ this,
+ Resources.getParentProcessResourceTypes(resourceTypes)
+ );
+
+ // Bail out early if all resources were watched from parent process.
+ // In this scenario, we do not need to update these resource types in the WatcherRegistry
+ // as targets do not care about them.
+ if (!Resources.hasResourceTypesForTargets(resourceTypes)) {
+ return;
+ }
+
+ WatcherRegistry.watchResources(this, resourceTypes);
+
+ // Fetch resources from all existing targets
+ for (const targetType in TARGET_HELPERS) {
+ // We process frame targets even if we aren't watching them,
+ // because frame target helper codepath handles the top level target, if it runs in the *content* process.
+ // It will do another check to `isWatchingTargets(FRAME)` internally.
+ // Note that the workaround at the end of this method, using TargetActorRegistry
+ // is specific to top level target running in the *parent* process.
+ if (
+ !WatcherRegistry.isWatchingTargets(this, targetType) &&
+ targetType != Targets.TYPES.FRAME
+ ) {
+ continue;
+ }
+ const targetResourceTypes = Resources.getResourceTypesForTargetType(
+ resourceTypes,
+ targetType
+ );
+ if (targetResourceTypes.length == 0) {
+ continue;
+ }
+ const targetHelperModule = TARGET_HELPERS[targetType];
+ await targetHelperModule.addWatcherDataEntry({
+ watcher: this,
+ type: "resources",
+ entries: targetResourceTypes,
+ });
+ }
+
+ /*
+ * The Watcher actor doesn't support watching the top level target
+ * (bug 1644397 and possibly some other followup).
+ *
+ * Because of that, we miss reaching these targets in the previous lines of this function.
+ * Since all BrowsingContext target actors register themselves to the TargetActorRegistry,
+ * we use it here in order to reach those missing targets, which are running in the
+ * parent process (where this WatcherActor lives as well):
+ * - the parent process target (which inherits from BrowsingContextTargetActor)
+ * - top level tab target for documents loaded in the parent process (e.g. about:robots).
+ * When the tab loads document in the content process, the FrameTargetHelper will
+ * reach it via the JSWindowActor API. Even if it uses MessageManager for anything
+ * else (RDP packet forwarding, creation and destruction).
+ *
+ * We will eventually get rid of this code once all targets are properly supported by
+ * the Watcher Actor and we have target helpers for all of them.
+ */
+ const frameResourceTypes = Resources.getResourceTypesForTargetType(
+ resourceTypes,
+ Targets.TYPES.FRAME
+ );
+ if (frameResourceTypes.length > 0) {
+ const targetActor = this._getTargetActorInParentProcess();
+ if (targetActor) {
+ await targetActor.addWatcherDataEntry("resources", frameResourceTypes);
+ }
+ }
+ },
+
+ /**
+ * Stop watching for a list of resource types.
+ *
+ * @param {Array<string>} resourceTypes
+ * List of all types to listen to.
+ */
+ unwatchResources(resourceTypes) {
+ // First process resources which are listened from the parent process
+ // (the watcher actor always runs in the parent process)
+ Resources.unwatchResources(
+ this,
+ Resources.getParentProcessResourceTypes(resourceTypes)
+ );
+
+ // Bail out early if all resources were all watched from parent process.
+ // In this scenario, we do not need to update these resource types in the WatcherRegistry
+ // as targets do not care about them.
+ if (!Resources.hasResourceTypesForTargets(resourceTypes)) {
+ return;
+ }
+
+ const isWatchingResources = WatcherRegistry.unwatchResources(
+ this,
+ resourceTypes
+ );
+ if (!isWatchingResources) {
+ return;
+ }
+
+ // Prevent trying to unwatch when the related BrowsingContext has already
+ // been destroyed
+ if (!this.browserElement || this.browserElement.browsingContext) {
+ for (const targetType in TARGET_HELPERS) {
+ // Frame target helper handles the top level target, if it runs in the content process
+ // so we should always process it. It does a second check to isWatchingTargets.
+ if (
+ !WatcherRegistry.isWatchingTargets(this, targetType) &&
+ targetType != Targets.TYPES.FRAME
+ ) {
+ continue;
+ }
+ const targetResourceTypes = Resources.getResourceTypesForTargetType(
+ resourceTypes,
+ targetType
+ );
+ if (targetResourceTypes.length == 0) {
+ continue;
+ }
+ const targetHelperModule = TARGET_HELPERS[targetType];
+ targetHelperModule.removeWatcherDataEntry({
+ watcher: this,
+ type: "resources",
+ entries: targetResourceTypes,
+ });
+ }
+ }
+
+ // See comment in watchResources.
+ const frameResourceTypes = Resources.getResourceTypesForTargetType(
+ resourceTypes,
+ Targets.TYPES.FRAME
+ );
+ if (frameResourceTypes.length > 0) {
+ const targetActor = this._getTargetActorInParentProcess();
+ if (targetActor) {
+ targetActor.removeWatcherDataEntry("resources", frameResourceTypes);
+ }
+ }
+
+ // Unregister the JS Window Actor if there is no more DevTools code observing any target/resource
+ WatcherRegistry.maybeUnregisteringJSWindowActor();
+ },
+
+ /**
+ * Returns the network actor.
+ *
+ * @return {Object} actor
+ * The network actor.
+ */
+ getNetworkParentActor() {
+ return new NetworkParentActor(this);
+ },
+
+ /**
+ * Returns the breakpoint list actor.
+ *
+ * @return {Object} actor
+ * The breakpoint list actor.
+ */
+ getBreakpointListActor() {
+ return new BreakpointListActor(this);
+ },
+
+ /**
+ * Server internal API, called by other actors, but not by the client.
+ * Used to agrement some new entries for a given data type (watchers target, resources,
+ * breakpoints,...)
+ *
+ * @param {String} type
+ * Data type to contribute to.
+ * @param {Array<*>} entries
+ * List of values to add for this data type.
+ */
+ async addDataEntry(type, entries) {
+ WatcherRegistry.addWatcherDataEntry(this, type, entries);
+
+ await Promise.all(
+ Object.values(Targets.TYPES)
+ .filter(targetType =>
+ WatcherRegistry.isWatchingTargets(this, targetType)
+ )
+ .map(async targetType => {
+ const targetHelperModule = TARGET_HELPERS[targetType];
+ await targetHelperModule.addWatcherDataEntry({
+ watcher: this,
+ type,
+ entries,
+ });
+ })
+ );
+
+ // See comment in watchResources
+ const targetActor = this._getTargetActorInParentProcess();
+ if (targetActor) {
+ await targetActor.addWatcherDataEntry(type, entries);
+ }
+ },
+
+ /**
+ * Server internal API, called by other actors, but not by the client.
+ * Used to remve some existing entries for a given data type (watchers target, resources,
+ * breakpoints,...)
+ *
+ * @param {String} type
+ * Data type to modify.
+ * @param {Array<*>} entries
+ * List of values to remove from this data type.
+ */
+ removeDataEntry(type, entries) {
+ WatcherRegistry.removeWatcherDataEntry(this, type, entries);
+
+ Object.values(Targets.TYPES)
+ .filter(targetType => WatcherRegistry.isWatchingTargets(this, targetType))
+ .forEach(targetType => {
+ const targetHelperModule = TARGET_HELPERS[targetType];
+ targetHelperModule.removeWatcherDataEntry({
+ watcher: this,
+ type,
+ entries,
+ });
+ });
+
+ // See comment in watchResources
+ const targetActor = this._getTargetActorInParentProcess();
+ if (targetActor) {
+ targetActor.removeWatcherDataEntry(type, entries);
+ }
+ },
+});
diff --git a/devtools/server/actors/watcher/WatchedDataHelpers.jsm b/devtools/server/actors/watcher/WatchedDataHelpers.jsm
new file mode 100644
index 0000000000..9acd5a612c
--- /dev/null
+++ b/devtools/server/actors/watcher/WatchedDataHelpers.jsm
@@ -0,0 +1,124 @@
+/* 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";
+
+/**
+ * Helper module alongside WatcherRegistry, which focus on updating the "watchedData" object.
+ * This object is shared across processes and threads and have to be maintained in all these runtimes.
+ */
+
+var EXPORTED_SYMBOLS = ["WatchedDataHelpers"];
+
+// List of all arrays stored in `watchedData`, which are replicated across processes and threads
+const SUPPORTED_DATA = {
+ BREAKPOINTS: "breakpoints",
+ RESOURCES: "resources",
+ TARGETS: "targets",
+};
+
+// Optional function, if data isn't a primitive data type in order to produce a key
+// for the given data entry
+const DATA_KEY_FUNCTION = {
+ [SUPPORTED_DATA.BREAKPOINTS]: function({
+ location: { sourceUrl, sourceId, line, column },
+ }) {
+ if (!sourceUrl && !sourceId) {
+ throw new Error(
+ `Breakpoints expect to have either a sourceUrl or a sourceId.`
+ );
+ }
+ if (sourceUrl && typeof sourceUrl != "string") {
+ throw new Error(
+ `Breakpoints expect to have sourceUrl string, got ${typeof sourceUrl} instead.`
+ );
+ }
+ // sourceId may be undefined for some sources keyed by URL
+ if (sourceId && typeof sourceId != "string") {
+ throw new Error(
+ `Breakpoints expect to have sourceId string, got ${typeof sourceId} instead.`
+ );
+ }
+ if (typeof line != "number") {
+ throw new Error(
+ `Breakpoints expect to have line number, got ${typeof line} instead.`
+ );
+ }
+ if (typeof column != "number") {
+ throw new Error(
+ `Breakpoints expect to have column number, got ${typeof column} instead.`
+ );
+ }
+ return `${sourceUrl}:${sourceId}:${line}:${column}`;
+ },
+};
+
+function idFunction(v) {
+ if (typeof v != "string") {
+ throw new Error(
+ `Expect data entry values to be string, or be using custom data key functions. Got ${typeof v} type instead.`
+ );
+ }
+ return v;
+}
+
+const WatchedDataHelpers = {
+ SUPPORTED_DATA,
+
+ /**
+ * Add new values to the shared "watchedData" object.
+ *
+ * @param Object watchedData
+ * The data object to update.
+ * @param string type
+ * The type of data to be added
+ * @param Array<Object> entries
+ * The values to be added to this type of data
+ */
+ addWatchedDataEntry(watchedData, type, entries) {
+ const toBeAdded = [];
+ const keyFunction = DATA_KEY_FUNCTION[type] || idFunction;
+ for (const entry of entries) {
+ const alreadyExists = watchedData[type].some(existingEntry => {
+ return keyFunction(existingEntry) === keyFunction(entry);
+ });
+ if (!alreadyExists) {
+ toBeAdded.push(entry);
+ }
+ }
+ watchedData[type].push(...toBeAdded);
+ },
+
+ /**
+ * Remove values from the shared "watchedData" object.
+ *
+ * @param Object watchedData
+ * The data object to update.
+ * @param string type
+ * The type of data to be remove
+ * @param Array<Object> entries
+ * The values to be removed from this type of data
+ * @return Boolean
+ * True, if at least one entries existed and has been removed.
+ * False, if none of the entries existed and none has been removed.
+ */
+ removeWatchedDataEntry(watchedData, type, entries) {
+ let includesAtLeastOne = false;
+ const keyFunction = DATA_KEY_FUNCTION[type] || idFunction;
+ for (const entry of entries) {
+ const idx = watchedData[type].findIndex(existingEntry => {
+ return keyFunction(existingEntry) === keyFunction(entry);
+ });
+ if (idx !== -1) {
+ watchedData[type].splice(idx, 1);
+ includesAtLeastOne = true;
+ }
+ }
+ if (!includesAtLeastOne) {
+ return false;
+ }
+
+ return true;
+ },
+};
diff --git a/devtools/server/actors/watcher/WatcherRegistry.jsm b/devtools/server/actors/watcher/WatcherRegistry.jsm
new file mode 100644
index 0000000000..f8fc2aed49
--- /dev/null
+++ b/devtools/server/actors/watcher/WatcherRegistry.jsm
@@ -0,0 +1,346 @@
+/* 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";
+
+/**
+ * Helper module around `sharedData` object that helps storing the state
+ * of all observed Targets and Resources, that, for all DevTools connections.
+ * Here is a few words about the C++ implementation of sharedData:
+ * https://searchfox.org/mozilla-central/rev/bc3600def806859c31b2c7ac06e3d69271052a89/dom/ipc/SharedMap.h#30-55
+ *
+ * We may have more than one DevToolsServer and one server may have more than one
+ * client. This module will be the single source of truth in the parent process,
+ * in order to know which targets/resources are currently observed. It will also
+ * be used to declare when something starts/stops being observed.
+ *
+ * `sharedData` is a platform API that helps sharing JS Objects across processes.
+ * We use it in order to communicate to the content process which targets and resources
+ * should be observed. Content processes read this data only once, as soon as they are created.
+ * It isn't used beyond this point. Content processes are not going to update it.
+ * We will notify about changes in observed targets and resources for already running
+ * processes by some other means. (Via JS Window Actor queries "DevTools:(un)watch(Resources|Target)")
+ * This means that only this module will update the "DevTools:watchedPerWatcher" value.
+ * From the parent process, we should be going through this module to fetch the data,
+ * while from the content process, we will read `sharedData` directly.
+ */
+
+var EXPORTED_SYMBOLS = ["WatcherRegistry"];
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+const { ActorManagerParent } = ChromeUtils.import(
+ "resource://gre/modules/ActorManagerParent.jsm"
+);
+const { WatchedDataHelpers } = ChromeUtils.import(
+ "resource://devtools/server/actors/watcher/WatchedDataHelpers.jsm"
+);
+const { SUPPORTED_DATA } = WatchedDataHelpers;
+
+// Define the Map that will be saved in `sharedData`.
+// It is keyed by WatcherActor ID and values contains following attributes:
+// - targets: Set of strings, refering to target types to be listened to
+// - resources: Set of strings, refering to resource types to be observed
+// - browserId: Optional, if set, restrict the observation to one specific Browser Element tree.
+// It can be a tab, a top-level window or a top-level iframe (e.g. special privileged iframe)
+// See https://searchfox.org/mozilla-central/rev/31d8600b73dc85b4cdbabf45ac3f1a9c11700d8e/dom/chrome-webidl/BrowsingContext.webidl#114-121
+// for more information.
+// - connectionPrefix: The DevToolsConnection prefix of the watcher actor. Used to compute new actor ID in the content processes.
+//
+// Unfortunately, `sharedData` is subject to race condition and may have side effect
+// when read/written from multiple places in the same process,
+// which is why this map should be considered as the single source of truth.
+const watchedDataByWatcherActor = new Map();
+
+// In parallel to the previous map, keep all the WatcherActor keyed by the same WatcherActor ID,
+// the WatcherActor ID. We don't (and can't) propagate the WatcherActor instances to the content
+// processes, but still would like to match them by their ID.
+const watcherActors = new Map();
+
+// Name of the attribute into which we save this Map in `sharedData` object.
+const SHARED_DATA_KEY_NAME = "DevTools:watchedPerWatcher";
+
+/**
+ * Use `sharedData` to allow processes, early during their creation,
+ * to know which resources should be listened to. This will be read
+ * from the Target actor, when it gets created early during process start,
+ * in order to start listening to the expected resource types.
+ */
+function persistMapToSharedData() {
+ Services.ppmm.sharedData.set(SHARED_DATA_KEY_NAME, watchedDataByWatcherActor);
+ // Request to immediately flush the data to the content processes in order to prevent
+ // races (bug 1644649). Otherwise content process may have outdated sharedData
+ // and try to create targets for Watcher actor that already stopped watching for targets.
+ Services.ppmm.sharedData.flush();
+}
+
+const WatcherRegistry = {
+ /**
+ * Tells if a given watcher currently watches for a given target type.
+ *
+ * @param WatcherActor watcher
+ * The WatcherActor which should be listening.
+ * @param string targetType
+ * The new target type to query.
+ * @return boolean
+ * Returns true if already watching.
+ */
+ isWatchingTargets(watcher, targetType) {
+ const watchedData = this.getWatchedData(watcher);
+ return watchedData && watchedData.targets.includes(targetType);
+ },
+
+ /**
+ * Retrieve the data saved into `sharedData` that is used to know
+ * about which type of targets and resources we care listening about.
+ * `watchedDataByWatcherActor` is saved into `sharedData` after each mutation,
+ * but `watchedDataByWatcherActor` is the source of truth.
+ *
+ * @param WatcherActor watcher
+ * The related WatcherActor which starts/stops observing.
+ * @param object options (optional)
+ * A dictionary object with `createData` boolean attribute.
+ * If this attribute is set to true, we create the data structure in the Map
+ * if none exists for this prefix.
+ */
+ getWatchedData(watcher, { createData = false } = {}) {
+ // Use WatcherActor ID as a key as we may have multiple clients willing to watch for targets.
+ // For example, a Browser Toolbox debugging everything and a Content Toolbox debugging
+ // just one tab. We might also have multiple watchers, on the same connection when using about:debugging.
+ const watcherActorID = watcher.actorID;
+ let watchedData = watchedDataByWatcherActor.get(watcherActorID);
+ if (!watchedData && createData) {
+ watchedData = {
+ // The Browser ID will be helpful to identify which BrowsingContext should be considered
+ // when running code in the content process. Browser ID, compared to BrowsingContext ID won't change
+ // if we navigate to the parent process or if a new BrowsingContext is used for the <browser> element
+ // we are currently inspecting.
+ browserId: watcher.browserId,
+ // The DevToolsServerConnection prefix will be used to compute actor IDs created in the content process
+ connectionPrefix: watcher.conn.prefix,
+ };
+ // Define empty default array for all data
+ for (const name of Object.values(SUPPORTED_DATA)) {
+ watchedData[name] = [];
+ }
+ watchedDataByWatcherActor.set(watcherActorID, watchedData);
+ watcherActors.set(watcherActorID, watcher);
+ }
+ return watchedData;
+ },
+
+ /**
+ * Given a Watcher Actor ID, return the related Watcher Actor instance.
+ *
+ * @param String actorID
+ * The Watcher Actor ID to search for.
+ * @return WatcherActor
+ * The Watcher Actor instance.
+ */
+ getWatcher(actorID) {
+ return watcherActors.get(actorID);
+ },
+
+ /**
+ * Notify that a given watcher added an entry in a given data type.
+ *
+ * @param WatcherActor watcher
+ * The WatcherActor which starts observing.
+ * @param string type
+ * The type of data to be added
+ * @param Array<Object> entries
+ * The values to be added to this type of data
+ */
+ addWatcherDataEntry(watcher, type, entries) {
+ const watchedData = this.getWatchedData(watcher, {
+ createData: true,
+ });
+
+ if (!(type in watchedData)) {
+ throw new Error(`Unsupported watcher data type: ${type}`);
+ }
+
+ WatchedDataHelpers.addWatchedDataEntry(watchedData, type, entries);
+
+ // Register the JS Window Actor the first time we start watching for something (e.g. resource, target, …).
+ registerJSWindowActor();
+
+ persistMapToSharedData();
+ },
+
+ /**
+ * Notify that a given watcher removed an entry in a given data type.
+ *
+ * See `addWatcherDataEntry` for argument definition.
+ *
+ * @return boolean
+ * True if we such entry was already registered, for this watcher actor.
+ */
+ removeWatcherDataEntry(watcher, type, entries) {
+ const watchedData = this.getWatchedData(watcher);
+ if (!watchedData) {
+ return false;
+ }
+
+ if (!(type in watchedData)) {
+ throw new Error(`Unsupported watcher data type: ${type}`);
+ }
+
+ if (
+ !WatchedDataHelpers.removeWatchedDataEntry(watchedData, type, entries)
+ ) {
+ return false;
+ }
+
+ const isWatchingSomething = Object.values(SUPPORTED_DATA).some(
+ dataType => watchedData[dataType].length > 0
+ );
+ if (!isWatchingSomething) {
+ watchedDataByWatcherActor.delete(watcher.actorID);
+ watcherActors.delete(watcher.actorID);
+ }
+
+ persistMapToSharedData();
+
+ return true;
+ },
+
+ /**
+ * Cleanup everything about a given watcher actor.
+ * Remove it from any registry so that we stop interacting with it.
+ *
+ * The watcher would be automatically unregistered from removeWatcherEntry,
+ * if we remove all entries. But we aren't removing all breakpoints.
+ * So here, we force clearing any reference to the watcher actor when it destroys.
+ */
+ unregisterWatcher(watcher) {
+ watchedDataByWatcherActor.delete(watcher.actorID);
+ watcherActors.delete(watcher.actorID);
+ },
+
+ /**
+ * Notify that a given watcher starts observing a new target type.
+ *
+ * @param WatcherActor watcher
+ * The WatcherActor which starts observing.
+ * @param string targetType
+ * The new target type to start listening to.
+ */
+ watchTargets(watcher, targetType) {
+ this.addWatcherDataEntry(watcher, SUPPORTED_DATA.TARGETS, [targetType]);
+ },
+
+ /**
+ * Notify that a given watcher stops observing a given target type.
+ *
+ * See `watchTargets` for argument definition.
+ *
+ * @return boolean
+ * True if we were watching for this target type, for this watcher actor.
+ */
+ unwatchTargets(watcher, targetType) {
+ return this.removeWatcherDataEntry(watcher, SUPPORTED_DATA.TARGETS, [
+ targetType,
+ ]);
+ },
+
+ /**
+ * Notify that a given watcher starts observing new resource types.
+ *
+ * @param WatcherActor watcher
+ * The WatcherActor which starts observing.
+ * @param Array<string> resourceTypes
+ * The new resource types to start listening to.
+ */
+ watchResources(watcher, resourceTypes) {
+ this.addWatcherDataEntry(watcher, SUPPORTED_DATA.RESOURCES, resourceTypes);
+ },
+
+ /**
+ * Notify that a given watcher stops observing given resource types.
+ *
+ * See `watchResources` for argument definition.
+ *
+ * @return boolean
+ * True if we were watching for this resource type, for this watcher actor.
+ */
+ unwatchResources(watcher, resourceTypes) {
+ return this.removeWatcherDataEntry(
+ watcher,
+ SUPPORTED_DATA.RESOURCES,
+ resourceTypes
+ );
+ },
+
+ /**
+ * Unregister the JS Window Actor if there is no more DevTools code observing any target/resource.
+ */
+ maybeUnregisteringJSWindowActor() {
+ if (watchedDataByWatcherActor.size == 0) {
+ unregisterJSWindowActor();
+ }
+ },
+};
+
+// Boolean flag to know if the DevToolsFrame JS Window Actor is currently registered
+let isJSWindowActorRegistered = false;
+
+/**
+ * Register the JSWindowActor pair "DevToolsFrame".
+ *
+ * We should call this method before we try to use this JS Window Actor from the parent process
+ * (via `WindowGlobal.getActor("DevToolsFrame")` or `WindowGlobal.getActor("DevToolsWorker")`).
+ * Also, registering it will automatically force spawing the content process JSWindow Actor
+ * anytime a new document is opened (via DOMWindowCreated event).
+ */
+
+const JSWindowActorsConfig = {
+ DevToolsFrame: {
+ parent: {
+ moduleURI:
+ "resource://devtools/server/connectors/js-window-actor/DevToolsFrameParent.jsm",
+ },
+ child: {
+ moduleURI:
+ "resource://devtools/server/connectors/js-window-actor/DevToolsFrameChild.jsm",
+ events: {
+ DOMWindowCreated: {},
+ },
+ },
+ allFrames: true,
+ },
+ DevToolsWorker: {
+ parent: {
+ moduleURI:
+ "resource://devtools/server/connectors/js-window-actor/DevToolsWorkerParent.jsm",
+ },
+ child: {
+ moduleURI:
+ "resource://devtools/server/connectors/js-window-actor/DevToolsWorkerChild.jsm",
+ events: {
+ DOMWindowCreated: {},
+ },
+ },
+ allFrames: true,
+ },
+};
+
+function registerJSWindowActor() {
+ if (isJSWindowActorRegistered) {
+ return;
+ }
+ isJSWindowActorRegistered = true;
+ ActorManagerParent.addJSWindowActors(JSWindowActorsConfig);
+}
+
+function unregisterJSWindowActor() {
+ if (!isJSWindowActorRegistered) {
+ return;
+ }
+ isJSWindowActorRegistered = false;
+
+ for (const JSWindowActorName of Object.keys(JSWindowActorsConfig)) {
+ // ActorManagerParent doesn't expose a "removeActors" method, but it would be equivalent to that:
+ ChromeUtils.unregisterWindowActor(JSWindowActorName);
+ }
+}
diff --git a/devtools/server/actors/watcher/moz.build b/devtools/server/actors/watcher/moz.build
new file mode 100644
index 0000000000..227184cf3b
--- /dev/null
+++ b/devtools/server/actors/watcher/moz.build
@@ -0,0 +1,14 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "target-helpers",
+]
+
+DevToolsModules(
+ "WatchedDataHelpers.jsm",
+ "WatcherRegistry.jsm",
+)
diff --git a/devtools/server/actors/watcher/target-helpers/frame-helper.js b/devtools/server/actors/watcher/target-helpers/frame-helper.js
new file mode 100644
index 0000000000..612febab9e
--- /dev/null
+++ b/devtools/server/actors/watcher/target-helpers/frame-helper.js
@@ -0,0 +1,204 @@
+/* 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";
+
+const {
+ WatcherRegistry,
+} = require("devtools/server/actors/watcher/WatcherRegistry.jsm");
+const {
+ WindowGlobalLogger,
+} = require("devtools/server/connectors/js-window-actor/WindowGlobalLogger.jsm");
+const Targets = require("devtools/server/actors/targets/index");
+const {
+ getAllRemoteBrowsingContexts,
+ shouldNotifyWindowGlobal,
+} = require("devtools/server/actors/watcher/target-helpers/utils.js");
+
+/**
+ * Force creating targets for all existing BrowsingContext, that, for a given Watcher Actor.
+ *
+ * @param WatcherActor watcher
+ * The Watcher Actor requesting to watch for new targets.
+ */
+async function createTargets(watcher) {
+ // Go over all existing BrowsingContext in order to:
+ // - Force the instantiation of a DevToolsFrameChild
+ // - Have the DevToolsFrameChild to spawn the BrowsingContextTargetActor
+ const browsingContexts = getFilteredRemoteBrowsingContext(
+ watcher.browserElement
+ );
+ const promises = [];
+ for (const browsingContext of browsingContexts) {
+ logWindowGlobal(
+ browsingContext.currentWindowGlobal,
+ "Existing WindowGlobal"
+ );
+
+ // Await for the query in order to try to resolve only *after* we received these
+ // already available targets.
+ const promise = browsingContext.currentWindowGlobal
+ .getActor("DevToolsFrame")
+ .instantiateTarget({
+ watcherActorID: watcher.actorID,
+ connectionPrefix: watcher.conn.prefix,
+ browserId: watcher.browserId,
+ watchedData: watcher.watchedData,
+ });
+ promises.push(promise);
+ }
+ return Promise.all(promises);
+}
+
+/**
+ * Force destroying all BrowsingContext targets which were related to a given watcher.
+ *
+ * @param WatcherActor watcher
+ * The Watcher Actor requesting to stop watching for new targets.
+ */
+function destroyTargets(watcher) {
+ // Go over all existing BrowsingContext in order to destroy all targets
+ const browsingContexts = getFilteredRemoteBrowsingContext(
+ watcher.browserElement
+ );
+ for (const browsingContext of browsingContexts) {
+ logWindowGlobal(
+ browsingContext.currentWindowGlobal,
+ "Existing WindowGlobal"
+ );
+
+ browsingContext.currentWindowGlobal
+ .getActor("DevToolsFrame")
+ .destroyTarget({
+ watcherActorID: watcher.actorID,
+ browserId: watcher.browserId,
+ });
+ }
+}
+
+/**
+ * Go over all existing BrowsingContext in order to communicate about new data entries
+ *
+ * @param WatcherActor watcher
+ * The Watcher Actor requesting to stop watching for new targets.
+ * @param string type
+ * The type of data to be added
+ * @param Array<Object> entries
+ * The values to be added to this type of data
+ */
+async function addWatcherDataEntry({ watcher, type, entries }) {
+ const browsingContexts = getWatchingBrowsingContexts(watcher);
+ const promises = [];
+ for (const browsingContext of browsingContexts) {
+ logWindowGlobal(
+ browsingContext.currentWindowGlobal,
+ "Existing WindowGlobal"
+ );
+
+ const promise = browsingContext.currentWindowGlobal
+ .getActor("DevToolsFrame")
+ .addWatcherDataEntry({
+ watcherActorID: watcher.actorID,
+ browserId: watcher.browserId,
+ type,
+ entries,
+ });
+ promises.push(promise);
+ }
+ // Await for the queries in order to try to resolve only *after* the remote code processed the new data
+ return Promise.all(promises);
+}
+
+/**
+ * Notify all existing frame targets that some data entries have been removed
+ *
+ * See addWatcherDataEntry for argument documentation.
+ */
+function removeWatcherDataEntry({ watcher, type, entries }) {
+ const browsingContexts = getWatchingBrowsingContexts(watcher);
+ for (const browsingContext of browsingContexts) {
+ logWindowGlobal(
+ browsingContext.currentWindowGlobal,
+ "Existing WindowGlobal"
+ );
+
+ browsingContext.currentWindowGlobal
+ .getActor("DevToolsFrame")
+ .removeWatcherDataEntry({
+ watcherActorID: watcher.actorID,
+ browserId: watcher.browserId,
+ type,
+ entries,
+ });
+ }
+}
+
+module.exports = {
+ createTargets,
+ destroyTargets,
+ addWatcherDataEntry,
+ removeWatcherDataEntry,
+};
+
+/**
+ * Return the list of BrowsingContexts which should be targeted in order to communicate
+ * a new list of resource types to listen or stop listening to.
+ *
+ * @param WatcherActor watcher
+ * The watcher actor will be used to know which target we debug
+ * and what BrowsingContext should be considered.
+ */
+function getWatchingBrowsingContexts(watcher) {
+ // If we are watching for additional frame targets, it means that fission mode is enabled,
+ // either for a content toolbox or a BrowserToolbox via devtools.browsertoolbox.fission pref.
+ const watchingAdditionalTargets = WatcherRegistry.isWatchingTargets(
+ watcher,
+ Targets.TYPES.FRAME
+ );
+ const { browserElement } = watcher;
+ const browsingContexts = watchingAdditionalTargets
+ ? getFilteredRemoteBrowsingContext(browserElement)
+ : [];
+ // Even if we aren't watching additional target, we want to process the top level target.
+ // The top level target isn't returned by getFilteredRemoteBrowsingContext, so add it in both cases.
+ if (browserElement) {
+ const topBrowsingContext = browserElement.browsingContext;
+ // Ignore if we are against a page running in the parent process,
+ // which would not support JSWindowActor API
+ // XXX May be we should toggle `includeChrome` and ensure watch/unwatch works
+ // with such page?
+ if (topBrowsingContext.currentWindowGlobal.osPid != -1) {
+ browsingContexts.push(topBrowsingContext);
+ }
+ }
+ return browsingContexts;
+}
+
+/**
+ * Get the list of all BrowsingContext we should interact with.
+ * The precise condition of which BrowsingContext we should interact with are defined
+ * in `shouldNotifyWindowGlobal`
+ *
+ * @param BrowserElement browserElement (optional)
+ * If defined, this will restrict to only the Browsing Context matching this
+ * Browser Element and any of its (nested) children iframes.
+ */
+function getFilteredRemoteBrowsingContext(browserElement) {
+ return getAllRemoteBrowsingContexts(
+ browserElement?.browsingContext
+ ).filter(browsingContext =>
+ shouldNotifyWindowGlobal(browsingContext, browserElement?.browserId)
+ );
+}
+
+// Set to true to log info about about WindowGlobal's being watched.
+const DEBUG = false;
+
+function logWindowGlobal(windowGlobal, message) {
+ if (!DEBUG) {
+ return;
+ }
+
+ WindowGlobalLogger.logWindowGlobal(windowGlobal, message);
+}
diff --git a/devtools/server/actors/watcher/target-helpers/moz.build b/devtools/server/actors/watcher/target-helpers/moz.build
new file mode 100644
index 0000000000..92413d1f52
--- /dev/null
+++ b/devtools/server/actors/watcher/target-helpers/moz.build
@@ -0,0 +1,12 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "frame-helper.js",
+ "process-helper.js",
+ "utils.js",
+ "worker-helper.js",
+)
diff --git a/devtools/server/actors/watcher/target-helpers/process-helper.js b/devtools/server/actors/watcher/target-helpers/process-helper.js
new file mode 100644
index 0000000000..6a3e76f818
--- /dev/null
+++ b/devtools/server/actors/watcher/target-helpers/process-helper.js
@@ -0,0 +1,281 @@
+/* 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";
+
+const Services = require("Services");
+const {
+ WatcherRegistry,
+} = require("devtools/server/actors/watcher/WatcherRegistry.jsm");
+
+loader.lazyRequireGetter(
+ this,
+ "ChildDebuggerTransport",
+ "devtools/shared/transport/child-transport",
+ true
+);
+
+const CONTENT_PROCESS_SCRIPT =
+ "resource://devtools/server/startup/content-process-script.js";
+
+/**
+ * Map a MessageManager key to an Array of ContentProcessTargetActor "description" objects.
+ * A single MessageManager might be linked to several ContentProcessTargetActors if there are several
+ * Watcher actors instantiated on the DevToolsServer, via a single connection (in theory), but rather
+ * via distinct connections (ex: a content toolbox and the browser toolbox).
+ * Note that if we spawn two DevToolsServer, this module will be instantiated twice.
+ *
+ * Each ContentProcessTargetActor "description" object is structured as follows
+ * - {Object} actor: form of the content process target actor
+ * - {String} prefix: forwarding prefix used to redirect all packet to the right content process's transport
+ * - {ChildDebuggerTransport} childTransport: Transport forwarding all packets to the target's content process
+ * - {WatcherActor} watcher: The Watcher actor for which we instantiated this content process target actor
+ */
+const actors = new WeakMap();
+
+// Save the list of all watcher actors that are watching for processes
+const watchers = new Set();
+
+function onContentProcessActorCreated(msg) {
+ const { watcherActorID, prefix, actor } = msg.data;
+ const watcher = WatcherRegistry.getWatcher(watcherActorID);
+ if (!watcher) {
+ throw new Error(
+ `Receiving a content process actor without a watcher actor ${watcherActorID}`
+ );
+ }
+ // Ignore watchers of other connections.
+ // We may have two browser toolbox connected to the same process.
+ // This will spawn two distinct Watcher actor and two distinct process target helper module.
+ // Avoid processing the event many times, otherwise we will notify about the same target
+ // multiple times.
+ if (!watchers.has(watcher)) {
+ return;
+ }
+ const messageManager = msg.target;
+ const connection = watcher.conn;
+
+ // Pipe Debugger message from/to parent/child via the message manager
+ const childTransport = new ChildDebuggerTransport(messageManager, prefix);
+ childTransport.hooks = {
+ onPacket: connection.send.bind(connection),
+ };
+ childTransport.ready();
+
+ connection.setForwarding(prefix, childTransport);
+
+ const list = actors.get(messageManager) || [];
+ list.push({
+ prefix,
+ childTransport,
+ actor,
+ watcher,
+ });
+ actors.set(messageManager, list);
+
+ watcher.notifyTargetAvailable(actor);
+}
+
+function onMessageManagerClose(messageManager, topic, data) {
+ const list = actors.get(messageManager);
+ if (!list || list.length == 0) {
+ return;
+ }
+ for (const { prefix, childTransport, actor, watcher } of list) {
+ watcher.notifyTargetDestroyed(actor);
+
+ // If we have a child transport, the actor has already
+ // been created. We need to stop using this message manager.
+ childTransport.close();
+ watcher.conn.cancelForwarding(prefix);
+ }
+ actors.delete(messageManager);
+}
+
+function closeWatcherTransports(watcher) {
+ for (let i = 0; i < Services.ppmm.childCount; i++) {
+ const messageManager = Services.ppmm.getChildAt(i);
+ let list = actors.get(messageManager);
+ if (!list || list.length == 0) {
+ continue;
+ }
+ list = list.filter(item => item.watcher != watcher);
+ for (const item of list) {
+ // If we have a child transport, the actor has already
+ // been created. We need to stop using this message manager.
+ item.childTransport.close();
+ watcher.conn.cancelForwarding(item.prefix);
+ }
+ if (list.length == 0) {
+ actors.delete(messageManager);
+ } else {
+ actors.set(messageManager, list);
+ }
+ }
+}
+
+function maybeRegisterMessageListeners(watcher) {
+ const sizeBefore = watchers.size;
+ watchers.add(watcher);
+ if (sizeBefore == 0 && watchers.size == 1) {
+ Services.ppmm.addMessageListener(
+ "debug:content-process-actor",
+ onContentProcessActorCreated
+ );
+ Services.obs.addObserver(onMessageManagerClose, "message-manager-close");
+
+ // Load the content process server startup script only once,
+ // otherwise it will be evaluated twice, listen to events twice and create
+ // target actors twice.
+ // We may try to load it twice when opening one Browser Toolbox via about:debugging
+ // and another regular Browser Toolbox. Both will spawn a WatcherActor and watch for processes.
+ const isContentProcessScripLoaded = Services.ppmm
+ .getDelayedProcessScripts()
+ .some(([uri]) => uri === CONTENT_PROCESS_SCRIPT);
+ if (!isContentProcessScripLoaded) {
+ Services.ppmm.loadProcessScript(CONTENT_PROCESS_SCRIPT, true);
+ }
+ }
+}
+function maybeUnregisterMessageListeners(watcher) {
+ const sizeBefore = watchers.size;
+ watchers.delete(watcher);
+ closeWatcherTransports(watcher);
+
+ if (sizeBefore == 1 && watchers.size == 0) {
+ Services.ppmm.removeMessageListener(
+ "debug:content-process-actor",
+ onContentProcessActorCreated
+ );
+ Services.obs.removeObserver(onMessageManagerClose, "message-manager-close");
+
+ // We inconditionally remove the process script, while we should only remove it
+ // once the last DevToolsServer stop watching for processes.
+ // We might have many server, using distinct loaders, so that this module
+ // will be spawn many times and we should remove the script only once the last
+ // module unregister the last watcher of all.
+ Services.ppmm.removeDelayedProcessScript(CONTENT_PROCESS_SCRIPT);
+
+ Services.ppmm.broadcastAsyncMessage("debug:destroy-process-script");
+ }
+}
+
+async function createTargets(watcher) {
+ // XXX: Should this move to WatcherRegistry??
+ maybeRegisterMessageListeners(watcher);
+
+ // Bug 1648499: This could be simplified when migrating to JSProcessActor by using sendQuery.
+ // For now, hack into WatcherActor in order to know when we created one target
+ // actor for each existing content process.
+ // Also, we substract one as the parent process has a message manager and is counted
+ // in `childCount`, but we ignore it from the process script and it won't reply.
+ const contentProcessCount = Services.ppmm.childCount - 1;
+ if (contentProcessCount == 0) {
+ return;
+ }
+ const onTargetsCreated = new Promise(resolve => {
+ let receivedTargetCount = 0;
+ const listener = () => {
+ if (++receivedTargetCount == contentProcessCount) {
+ watcher.off("target-available-form", listener);
+ resolve();
+ }
+ };
+ watcher.on("target-available-form", listener);
+ });
+
+ Services.ppmm.broadcastAsyncMessage("debug:instantiate-already-available", {
+ watcherActorID: watcher.actorID,
+ connectionPrefix: watcher.conn.prefix,
+ watchedData: watcher.watchedData,
+ });
+
+ await onTargetsCreated;
+}
+
+function destroyTargets(watcher) {
+ maybeUnregisterMessageListeners(watcher);
+
+ Services.ppmm.broadcastAsyncMessage("debug:destroy-target", {
+ watcherActorID: watcher.actorID,
+ });
+}
+
+/**
+ * Go over all existing content processes in order to communicate about new data entries
+ *
+ * @param {Object} options
+ * @param {WatcherActor} options.watcher
+ * The Watcher Actor providing new data entries
+ * @param {string} options.type
+ * The type of data to be added
+ * @param {Array<Object>} options.entries
+ * The values to be added to this type of data
+ */
+async function addWatcherDataEntry({ watcher, type, entries }) {
+ let expectedCount = Services.ppmm.childCount - 1;
+ if (expectedCount == 0) {
+ return;
+ }
+ const onAllReplied = new Promise(resolve => {
+ let count = 0;
+ const listener = msg => {
+ if (msg.data.watcherActorID != watcher.actorID) {
+ return;
+ }
+ count++;
+ maybeResolve();
+ };
+ Services.ppmm.addMessageListener(
+ "debug:add-watcher-data-entry-done",
+ listener
+ );
+ const onContentProcessClosed = (messageManager, topic, data) => {
+ expectedCount--;
+ maybeResolve();
+ };
+ const maybeResolve = () => {
+ if (count == expectedCount) {
+ Services.ppmm.removeMessageListener(
+ "debug:add-watcher-data-entry-done",
+ listener
+ );
+ Services.obs.removeObserver(
+ onContentProcessClosed,
+ "message-manager-close"
+ );
+ resolve();
+ }
+ };
+ Services.obs.addObserver(onContentProcessClosed, "message-manager-close");
+ });
+
+ Services.ppmm.broadcastAsyncMessage("debug:add-watcher-data-entry", {
+ watcherActorID: watcher.actorID,
+ type,
+ entries,
+ });
+
+ await onAllReplied;
+}
+
+/**
+ * Notify all existing content processes that some data entries have been removed
+ *
+ * See addWatcherDataEntry for argument documentation.
+ */
+function removeWatcherDataEntry({ watcher, type, entries }) {
+ Services.ppmm.broadcastAsyncMessage("debug:remove-watcher-data-entry", {
+ watcherActorID: watcher.actorID,
+ type,
+ entries,
+ });
+}
+
+module.exports = {
+ createTargets,
+ destroyTargets,
+ addWatcherDataEntry,
+ removeWatcherDataEntry,
+};
diff --git a/devtools/server/actors/watcher/target-helpers/utils.js b/devtools/server/actors/watcher/target-helpers/utils.js
new file mode 100644
index 0000000000..f59bbceed3
--- /dev/null
+++ b/devtools/server/actors/watcher/target-helpers/utils.js
@@ -0,0 +1,126 @@
+/* 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";
+
+const Services = require("Services");
+
+/**
+ * Helper function to know if a given WindowGlobal should be exposed via watchTargets API
+ * XXX: We probably want to share this function with DevToolsFrameChild,
+ * but may be not, it looks like the checks are really differents because WindowGlobalParent and WindowGlobalChild
+ * expose very different attributes. (WindowGlobalChild exposes much less!)
+ *
+ * @param {BrowsingContext} browsingContext: The browsing context we want to check the window global for
+ * @param {String} watchedBrowserId
+ * @param {Object} options
+ * @param {Boolean} options.acceptNonRemoteFrame: Set to true to not restrict to remote frame only
+ */
+function shouldNotifyWindowGlobal(
+ browsingContext,
+ watchedBrowserId,
+ options = {}
+) {
+ const windowGlobal = browsingContext.currentWindowGlobal;
+ // Loading or destroying BrowsingContext won't have any associated WindowGlobal.
+ // Ignore them. They should be either handled via DOMWindowCreated event or JSWindowActor destroy
+ if (!windowGlobal) {
+ return false;
+ }
+ // Ignore extension for now as attaching to them is special.
+ if (browsingContext.currentRemoteType == "extension") {
+ return false;
+ }
+ // Ignore globals running in the parent process for now as they won't be in a distinct process anyway.
+ // And JSWindowActor will most likely only be created if we toggle includeChrome
+ // on the JSWindowActor registration.
+ if (windowGlobal.osPid == -1 && windowGlobal.isInProcess) {
+ return false;
+ }
+ // Ignore about:blank which are quickly replaced and destroyed by the final URI
+ // bug 1625026 aims at removing this workaround and allow debugging any about:blank load
+ if (
+ windowGlobal.documentURI &&
+ windowGlobal.documentURI.spec == "about:blank"
+ ) {
+ return false;
+ }
+
+ if (watchedBrowserId && browsingContext.browserId != watchedBrowserId) {
+ return false;
+ }
+
+ if (options.acceptNonRemoteFrame) {
+ return true;
+ }
+
+ // If `acceptNonRemoteFrame` options isn't true, only mention the "remote frames".
+ // i.e. the frames which are in a distinct process compared to their parent document
+ return (
+ !browsingContext.parent ||
+ windowGlobal.osPid != browsingContext.parent.currentWindowGlobal.osPid
+ );
+}
+
+/**
+ * Get all the BrowsingContexts.
+ *
+ * Really all of them:
+ * - For all the privileged windows (browser.xhtml, browser console, ...)
+ * - For all chrome *and* content contexts (privileged windows, as well as <browser> elements and their inner content documents)
+ * - For all nested browsing context. We fetch the contexts recursively.
+ *
+ * @param BrowsingContext topBrowsingContext (optional)
+ * If defined, this will restrict to this Browsing Context only
+ * and any of its (nested) children.
+ */
+function getAllRemoteBrowsingContexts(topBrowsingContext) {
+ const browsingContexts = [];
+
+ // For a given BrowsingContext, add the `browsingContext`
+ // all of its children, that, recursively.
+ function walk(browsingContext) {
+ if (browsingContexts.includes(browsingContext)) {
+ return;
+ }
+ browsingContexts.push(browsingContext);
+
+ for (const child of browsingContext.children) {
+ walk(child);
+ }
+
+ if (browsingContext.window) {
+ // If the document is in the parent process, also iterate over each <browser>'s browsing context.
+ // BrowsingContext.children doesn't cross chrome to content boundaries,
+ // so we have to cross these boundaries by ourself.
+ for (const browser of browsingContext.window.document.querySelectorAll(
+ `browser[remote="true"]`
+ )) {
+ walk(browser.browsingContext);
+ }
+ }
+ }
+
+ // If a Browsing Context is passed, only walk through the given BrowsingContext
+ if (topBrowsingContext) {
+ walk(topBrowsingContext);
+ // Remove the top level browsing context we just added by calling walk.
+ browsingContexts.shift();
+ } else {
+ // Fetch all top level window's browsing contexts
+ // Note that getWindowEnumerator works from all processes, including the content process.
+ for (const window of Services.ww.getWindowEnumerator()) {
+ if (window.docShell.browsingContext) {
+ walk(window.docShell.browsingContext);
+ }
+ }
+ }
+
+ return browsingContexts;
+}
+
+module.exports = {
+ getAllRemoteBrowsingContexts,
+ shouldNotifyWindowGlobal,
+};
diff --git a/devtools/server/actors/watcher/target-helpers/worker-helper.js b/devtools/server/actors/watcher/target-helpers/worker-helper.js
new file mode 100644
index 0000000000..1f0fa00b44
--- /dev/null
+++ b/devtools/server/actors/watcher/target-helpers/worker-helper.js
@@ -0,0 +1,144 @@
+/* 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";
+
+const {
+ getAllRemoteBrowsingContexts,
+ shouldNotifyWindowGlobal,
+} = require("devtools/server/actors/watcher/target-helpers/utils.js");
+
+const DEVTOOLS_WORKER_JS_WINDOW_ACTOR_NAME = "DevToolsWorker";
+
+/**
+ * Force creating targets for all existing workers for a given Watcher Actor.
+ *
+ * @param WatcherActor watcher
+ * The Watcher Actor requesting to watch for new targets.
+ */
+async function createTargets(watcher) {
+ // Go over all existing BrowsingContext in order to:
+ // - Force the instantiation of a DevToolsWorkerChild
+ // - Have the DevToolsWorkerChild to spawn the WorkerTargetActors
+ const browsingContexts = getFilteredBrowsingContext(watcher.browserElement);
+ const promises = [];
+ for (const browsingContext of browsingContexts) {
+ const promise = browsingContext.currentWindowGlobal
+ .getActor(DEVTOOLS_WORKER_JS_WINDOW_ACTOR_NAME)
+ .instantiateWorkerTargets({
+ watcherActorID: watcher.actorID,
+ connectionPrefix: watcher.conn.prefix,
+ browserId: watcher.browserId,
+ watchedData: watcher.watchedData,
+ });
+ promises.push(promise);
+ }
+
+ // Await for the different queries in order to try to resolve only *after* we received
+ // the already available worker targets.
+ return Promise.all(promises);
+}
+
+/**
+ * Force destroying all worker targets which were related to a given watcher.
+ *
+ * @param WatcherActor watcher
+ * The Watcher Actor requesting to stop watching for new targets.
+ */
+async function destroyTargets(watcher) {
+ // Go over all existing BrowsingContext in order to destroy all targets
+ const browsingContexts = getFilteredBrowsingContext(watcher.browserElement);
+ for (const browsingContext of browsingContexts) {
+ let windowActor;
+ try {
+ windowActor = browsingContext.currentWindowGlobal.getActor(
+ DEVTOOLS_WORKER_JS_WINDOW_ACTOR_NAME
+ );
+ } catch (e) {
+ continue;
+ }
+
+ windowActor.destroyWorkerTargets({
+ watcher,
+ browserId: watcher.browserId,
+ });
+ }
+}
+
+/**
+ * Go over all existing BrowsingContext in order to communicate about new data entries
+ *
+ * @param WatcherActor watcher
+ * The Watcher Actor requesting to stop watching for new targets.
+ * @param string type
+ * The type of data to be added
+ * @param Array<Object> entries
+ * The values to be added to this type of data
+ */
+async function addWatcherDataEntry({ watcher, type, entries }) {
+ const browsingContexts = getFilteredBrowsingContext(watcher.browserElement);
+ const promises = [];
+ for (const browsingContext of browsingContexts) {
+ const promise = browsingContext.currentWindowGlobal
+ .getActor(DEVTOOLS_WORKER_JS_WINDOW_ACTOR_NAME)
+ .addWatcherDataEntry({
+ watcherActorID: watcher.actorID,
+ browserId: watcher.browserId,
+ type,
+ entries,
+ });
+ promises.push(promise);
+ }
+ // Await for the queries in order to try to resolve only *after* the remote code processed the new data
+ return Promise.all(promises);
+}
+
+/**
+ * Notify all existing frame targets that some data entries have been removed
+ *
+ * See addWatcherDataEntry for argument documentation.
+ */
+function removeWatcherDataEntry({ watcher, type, entries }) {
+ const browsingContexts = getFilteredBrowsingContext(watcher.browserElement);
+ for (const browsingContext of browsingContexts) {
+ browsingContext.currentWindowGlobal
+ .getActor(DEVTOOLS_WORKER_JS_WINDOW_ACTOR_NAME)
+ .removeWatcherDataEntry({
+ watcherActorID: watcher.actorID,
+ browserId: watcher.browserId,
+ type,
+ entries,
+ });
+ }
+}
+
+/**
+ * Get the list of all BrowsingContext we should interact with.
+ * The precise condition of which BrowsingContext we should interact with are defined
+ * in `shouldNotifyWindowGlobal`
+ *
+ * @param BrowserElement browserElement (optional)
+ * If defined, this will restrict to only the Browsing Context matching this
+ * Browser Element and any of its (nested) children iframes.
+ */
+function getFilteredBrowsingContext(browserElement) {
+ const browsingContexts = getAllRemoteBrowsingContexts(
+ browserElement?.browsingContext
+ );
+ if (browserElement?.browsingContext) {
+ browsingContexts.push(browserElement?.browsingContext);
+ }
+ return browsingContexts.filter(browsingContext =>
+ shouldNotifyWindowGlobal(browsingContext, browserElement?.browserId, {
+ acceptNonRemoteFrame: true,
+ })
+ );
+}
+
+module.exports = {
+ createTargets,
+ destroyTargets,
+ addWatcherDataEntry,
+ removeWatcherDataEntry,
+};
diff --git a/devtools/server/actors/webbrowser.js b/devtools/server/actors/webbrowser.js
new file mode 100644
index 0000000000..abcc3fa19b
--- /dev/null
+++ b/devtools/server/actors/webbrowser.js
@@ -0,0 +1,790 @@
+/* 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 { Ci } = require("chrome");
+var Services = require("Services");
+var { DevToolsServer } = require("devtools/server/devtools-server");
+var { ActorRegistry } = require("devtools/server/actors/utils/actor-registry");
+var DevToolsUtils = require("devtools/shared/DevToolsUtils");
+
+loader.lazyRequireGetter(
+ this,
+ "RootActor",
+ "devtools/server/actors/root",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "TabDescriptorActor",
+ "devtools/server/actors/descriptors/tab",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WebExtensionDescriptorActor",
+ "devtools/server/actors/descriptors/webextension",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WorkerDescriptorActorList",
+ "devtools/server/actors/worker/worker-descriptor-actor-list",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "ServiceWorkerRegistrationActorList",
+ "devtools/server/actors/worker/service-worker-registration-list",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "ProcessActorList",
+ "devtools/server/actors/process",
+ true
+);
+loader.lazyImporter(
+ this,
+ "AddonManager",
+ "resource://gre/modules/AddonManager.jsm"
+);
+
+/**
+ * Browser-specific actors.
+ */
+
+/**
+ * Retrieve the window type of the top-level window |window|.
+ */
+function appShellDOMWindowType(window) {
+ /* This is what nsIWindowMediator's enumerator checks. */
+ return window.document.documentElement.getAttribute("windowtype");
+}
+
+/**
+ * Send Debugger:Shutdown events to all "navigator:browser" windows.
+ */
+function sendShutdownEvent() {
+ for (const win of Services.wm.getEnumerator(
+ DevToolsServer.chromeWindowType
+ )) {
+ const evt = win.document.createEvent("Event");
+ evt.initEvent("Debugger:Shutdown", true, false);
+ win.document.documentElement.dispatchEvent(evt);
+ }
+}
+
+exports.sendShutdownEvent = sendShutdownEvent;
+
+/**
+ * Construct a root actor appropriate for use in a server running in a
+ * browser. The returned root actor:
+ * - respects the factories registered with ActorRegistry.addGlobalActor,
+ * - uses a BrowserTabList to supply target actors for tabs,
+ * - sends all navigator:browser window documents a Debugger:Shutdown event
+ * when it exits.
+ *
+ * * @param connection DevToolsServerConnection
+ * The conection to the client.
+ */
+exports.createRootActor = function createRootActor(connection) {
+ return new RootActor(connection, {
+ tabList: new BrowserTabList(connection),
+ addonList: new BrowserAddonList(connection),
+ workerList: new WorkerDescriptorActorList(connection, {}),
+ serviceWorkerRegistrationList: new ServiceWorkerRegistrationActorList(
+ connection
+ ),
+ processList: new ProcessActorList(),
+ globalActorFactories: ActorRegistry.globalActorFactories,
+ onShutdown: sendShutdownEvent,
+ });
+};
+
+/**
+ * A live list of TabDescriptorActors representing the current browser tabs,
+ * to be provided to the root actor to answer 'listTabs' requests.
+ *
+ * This object also takes care of listening for TabClose events and
+ * onCloseWindow notifications, and exiting the target actors concerned.
+ *
+ * (See the documentation for RootActor for the definition of the "live
+ * list" interface.)
+ *
+ * @param connection DevToolsServerConnection
+ * The connection in which this list's target actors may participate.
+ *
+ * Some notes:
+ *
+ * This constructor is specific to the desktop browser environment; it
+ * maintains the tab list by tracking XUL windows and their XUL documents'
+ * "tabbrowser", "tab", and "browser" elements. What's entailed in maintaining
+ * an accurate list of open tabs in this context?
+ *
+ * - Opening and closing XUL windows:
+ *
+ * An nsIWindowMediatorListener is notified when new XUL windows (i.e., desktop
+ * windows) are opened and closed. It is not notified of individual content
+ * browser tabs coming and going within such a XUL window. That seems
+ * reasonable enough; it's concerned with XUL windows, not tab elements in the
+ * window's XUL document.
+ *
+ * However, even if we attach TabOpen and TabClose event listeners to each XUL
+ * window as soon as it is created:
+ *
+ * - we do not receive a TabOpen event for the initial empty tab of a new XUL
+ * window; and
+ *
+ * - we do not receive TabClose events for the tabs of a XUL window that has
+ * been closed.
+ *
+ * This means that TabOpen and TabClose events alone are not sufficient to
+ * maintain an accurate list of live tabs and mark target actors as closed
+ * promptly. Our nsIWindowMediatorListener onCloseWindow handler must find and
+ * exit all actors for tabs that were in the closing window.
+ *
+ * Since this is a bit hairy, we don't make each individual attached target
+ * actor responsible for noticing when it has been closed; we watch for that,
+ * and promise to call each actor's 'exit' method when it's closed, regardless
+ * of how we learn the news.
+ *
+ * - nsIWindowMediator locks
+ *
+ * nsIWindowMediator holds a lock protecting its list of top-level windows
+ * while it calls nsIWindowMediatorListener methods. nsIWindowMediator's
+ * GetEnumerator method also tries to acquire that lock. Thus, enumerating
+ * windows from within a listener method deadlocks (bug 873589). Rah. One
+ * can sometimes work around this by leaving the enumeration for a later
+ * tick.
+ *
+ * - Dragging tabs between windows:
+ *
+ * When a tab is dragged from one desktop window to another, we receive a
+ * TabOpen event for the new tab, and a TabClose event for the old tab; tab XUL
+ * elements do not really move from one document to the other (although their
+ * linked browser's content window objects do).
+ *
+ * However, while we could thus assume that each tab stays with the XUL window
+ * it belonged to when it was created, I'm not sure this is behavior one should
+ * rely upon. When a XUL window is closed, we take the less efficient, more
+ * conservative approach of simply searching the entire table for actors that
+ * belong to the closing XUL window, rather than trying to somehow track which
+ * XUL window each tab belongs to.
+ */
+function BrowserTabList(connection) {
+ this._connection = connection;
+
+ /*
+ * The XUL document of a tabbed browser window has "tab" elements, whose
+ * 'linkedBrowser' JavaScript properties are "browser" elements; those
+ * browsers' 'contentWindow' properties are wrappers on the tabs' content
+ * window objects.
+ *
+ * This map's keys are "browser" XUL elements; it maps each browser element
+ * to the target actor we've created for its content window, if we've created
+ * one. This map serves several roles:
+ *
+ * - During iteration, we use it to find actors we've created previously.
+ *
+ * - On a TabClose event, we use it to find the tab's target actor and exit it.
+ *
+ * - When the onCloseWindow handler is called, we iterate over it to find all
+ * tabs belonging to the closing XUL window, and exit them.
+ *
+ * - When it's empty, and the onListChanged hook is null, we know we can
+ * stop listening for events and notifications.
+ *
+ * We listen for TabClose events and onCloseWindow notifications in order to
+ * send onListChanged notifications, but also to tell actors when their
+ * referent has gone away and remove entries for dead browsers from this map.
+ * If that code is working properly, neither this map nor the actors in it
+ * should ever hold dead tabs alive.
+ */
+ this._actorByBrowser = new Map();
+
+ /* The current onListChanged handler, or null. */
+ this._onListChanged = null;
+
+ /*
+ * True if we've been iterated over since we last called our onListChanged
+ * hook.
+ */
+ this._mustNotify = false;
+
+ /* True if we're testing, and should throw if consistency checks fail. */
+ this._testing = false;
+
+ this._onPageTitleChangedEvent = this._onPageTitleChangedEvent.bind(this);
+}
+
+BrowserTabList.prototype.constructor = BrowserTabList;
+
+BrowserTabList.prototype.destroy = function() {
+ this._actorByBrowser.clear();
+ this.onListChanged = null;
+};
+
+/**
+ * Get the selected browser for the given navigator:browser window.
+ * @private
+ * @param window nsIChromeWindow
+ * The navigator:browser window for which you want the selected browser.
+ * @return Element|null
+ * The currently selected xul:browser element, if any. Note that the
+ * browser window might not be loaded yet - the function will return
+ * |null| in such cases.
+ */
+BrowserTabList.prototype._getSelectedBrowser = function(window) {
+ return window.gBrowser ? window.gBrowser.selectedBrowser : null;
+};
+
+/**
+ * Produces an iterable (in this case a generator) to enumerate all available
+ * browser tabs.
+ */
+BrowserTabList.prototype._getBrowsers = function*() {
+ // Iterate over all navigator:browser XUL windows.
+ for (const win of Services.wm.getEnumerator(
+ DevToolsServer.chromeWindowType
+ )) {
+ // For each tab in this XUL window, ensure that we have an actor for
+ // it, reusing existing actors where possible.
+ for (const browser of this._getChildren(win)) {
+ yield browser;
+ }
+ }
+};
+
+BrowserTabList.prototype._getChildren = function(window) {
+ if (!window.gBrowser) {
+ return [];
+ }
+ const { gBrowser } = window;
+ if (!gBrowser.browsers) {
+ return [];
+ }
+ return gBrowser.browsers.filter(browser => {
+ // Filter tabs that are closing. listTabs calls made right after TabClose
+ // events still list tabs in process of being closed.
+ const tab = gBrowser.getTabForBrowser(browser);
+ return !tab.closing;
+ });
+};
+
+BrowserTabList.prototype.getList = async function() {
+ // As a sanity check, make sure all the actors presently in our map get
+ // picked up when we iterate over all windows' tabs.
+ const initialMapSize = this._actorByBrowser.size;
+ this._foundCount = 0;
+
+ const actors = [];
+
+ for (const browser of this._getBrowsers()) {
+ try {
+ const actor = await this._getActorForBrowser(browser);
+ actors.push(actor);
+ } catch (e) {
+ if (e.error === "tabDestroyed") {
+ // Ignore the error if a tab was destroyed while retrieving the tab list.
+ continue;
+ }
+
+ // Forward unexpected errors.
+ throw e;
+ }
+ }
+
+ if (this._testing && initialMapSize !== this._foundCount) {
+ throw new Error("_actorByBrowser map contained actors for dead tabs");
+ }
+
+ this._mustNotify = true;
+ this._checkListening();
+
+ return actors;
+};
+
+BrowserTabList.prototype._getActorForBrowser = async function(browser) {
+ // Do we have an existing actor for this browser? If not, create one.
+ let actor = this._actorByBrowser.get(browser);
+ if (actor) {
+ this._foundCount++;
+ return actor;
+ }
+
+ actor = new TabDescriptorActor(this._connection, browser);
+ this._actorByBrowser.set(browser, actor);
+ this._checkListening();
+ return actor;
+};
+
+BrowserTabList.prototype.getTab = function({ outerWindowID, tabId }) {
+ if (typeof outerWindowID == "number") {
+ // First look for in-process frames with this ID
+ const window = Services.wm.getOuterWindowWithId(outerWindowID);
+ // Safety check to prevent debugging top level window via getTab
+ if (window?.isChromeWindow) {
+ return Promise.reject({
+ error: "forbidden",
+ message: "Window with outerWindowID '" + outerWindowID + "' is chrome",
+ });
+ }
+ if (window) {
+ const iframe = window.browsingContext.embedderElement;
+ if (iframe) {
+ return this._getActorForBrowser(iframe);
+ }
+ }
+ // Then also look on registered <xul:browsers> when using outerWindowID for
+ // OOP tabs
+ for (const browser of this._getBrowsers()) {
+ if (browser.outerWindowID == outerWindowID) {
+ return this._getActorForBrowser(browser);
+ }
+ }
+ return Promise.reject({
+ error: "noTab",
+ message: "Unable to find tab with outerWindowID '" + outerWindowID + "'",
+ });
+ } else if (typeof tabId == "number") {
+ // Tabs OOP
+ for (const browser of this._getBrowsers()) {
+ if (
+ browser.frameLoader?.remoteTab &&
+ browser.frameLoader.remoteTab.tabId === tabId
+ ) {
+ return this._getActorForBrowser(browser);
+ }
+ }
+ return Promise.reject({
+ error: "noTab",
+ message: "Unable to find tab with tabId '" + tabId + "'",
+ });
+ }
+
+ const topAppWindow = Services.wm.getMostRecentWindow(
+ DevToolsServer.chromeWindowType
+ );
+ if (topAppWindow) {
+ const selectedBrowser = this._getSelectedBrowser(topAppWindow);
+ return this._getActorForBrowser(selectedBrowser);
+ }
+ return Promise.reject({
+ error: "noTab",
+ message: "Unable to find any selected browser",
+ });
+};
+
+Object.defineProperty(BrowserTabList.prototype, "onListChanged", {
+ enumerable: true,
+ configurable: true,
+ get() {
+ return this._onListChanged;
+ },
+ set(v) {
+ if (v !== null && typeof v !== "function") {
+ throw new Error(
+ "onListChanged property may only be set to 'null' or a function"
+ );
+ }
+ this._onListChanged = v;
+ this._checkListening();
+ },
+});
+
+/**
+ * The set of tabs has changed somehow. Call our onListChanged handler, if
+ * one is set, and if we haven't already called it since the last iteration.
+ */
+BrowserTabList.prototype._notifyListChanged = function() {
+ if (!this._onListChanged) {
+ return;
+ }
+ if (this._mustNotify) {
+ this._onListChanged();
+ this._mustNotify = false;
+ }
+};
+
+/**
+ * Exit |actor|, belonging to |browser|, and notify the onListChanged
+ * handle if needed.
+ */
+BrowserTabList.prototype._handleActorClose = function(actor, browser) {
+ if (this._testing) {
+ if (this._actorByBrowser.get(browser) !== actor) {
+ throw new Error(
+ "TabDescriptorActor not stored in map under given browser"
+ );
+ }
+ if (actor.browser !== browser) {
+ throw new Error("actor's browser and map key don't match");
+ }
+ }
+
+ this._actorByBrowser.delete(browser);
+ actor.destroy();
+
+ this._notifyListChanged();
+ this._checkListening();
+};
+
+/**
+ * Make sure we are listening or not listening for activity elsewhere in
+ * the browser, as appropriate. Other than setting up newly created XUL
+ * windows, all listener / observer management should happen here.
+ */
+BrowserTabList.prototype._checkListening = function() {
+ /*
+ * If we have an onListChanged handler that we haven't sent an announcement
+ * to since the last iteration, we need to watch for tab creation as well as
+ * change of the currently selected tab and tab title changes of tabs in
+ * parent process via TabAttrModified (tabs oop uses DOMTitleChanges).
+ *
+ * Oddly, we don't need to watch for 'close' events here. If our actor list
+ * is empty, then either it was empty the last time we iterated, and no
+ * close events are possible, or it was not empty the last time we
+ * iterated, but all the actors have since been closed, and we must have
+ * sent a notification already when they closed.
+ */
+ this._listenForEventsIf(
+ this._onListChanged && this._mustNotify,
+ "_listeningForTabOpen",
+ ["TabOpen", "TabSelect", "TabAttrModified"]
+ );
+
+ /* If we have live actors, we need to be ready to mark them dead. */
+ this._listenForEventsIf(
+ this._actorByBrowser.size > 0,
+ "_listeningForTabClose",
+ ["TabClose"]
+ );
+
+ /*
+ * We must listen to the window mediator in either case, since that's the
+ * only way to find out about tabs that come and go when top-level windows
+ * are opened and closed.
+ */
+ this._listenToMediatorIf(
+ (this._onListChanged && this._mustNotify) || this._actorByBrowser.size > 0
+ );
+
+ /*
+ * We also listen for title changed events on the browser.
+ */
+ this._listenForEventsIf(
+ this._onListChanged && this._mustNotify,
+ "_listeningForTitleChange",
+ ["pagetitlechanged"],
+ this._onPageTitleChangedEvent
+ );
+};
+
+/*
+ * Add or remove event listeners for all XUL windows.
+ *
+ * @param shouldListen boolean
+ * True if we should add event handlers; false if we should remove them.
+ * @param guard string
+ * The name of a guard property of 'this', indicating whether we're
+ * already listening for those events.
+ * @param eventNames array of strings
+ * An array of event names.
+ */
+BrowserTabList.prototype._listenForEventsIf = function(
+ shouldListen,
+ guard,
+ eventNames,
+ listener = this
+) {
+ if (!shouldListen !== !this[guard]) {
+ const op = shouldListen ? "addEventListener" : "removeEventListener";
+ for (const win of Services.wm.getEnumerator(
+ DevToolsServer.chromeWindowType
+ )) {
+ for (const name of eventNames) {
+ win[op](name, listener, false);
+ }
+ }
+ this[guard] = shouldListen;
+ }
+};
+
+/*
+ * Event listener for pagetitlechanged event.
+ */
+BrowserTabList.prototype._onPageTitleChangedEvent = function(event) {
+ switch (event.type) {
+ case "pagetitlechanged": {
+ const window = event.currentTarget.ownerGlobal;
+ this._onDOMTitleChanged(window.browser);
+ break;
+ }
+ }
+};
+
+/**
+ * Handle "DOMTitleChanged" event.
+ */
+BrowserTabList.prototype._onDOMTitleChanged = DevToolsUtils.makeInfallible(
+ function(browser) {
+ const actor = this._actorByBrowser.get(browser);
+ if (actor) {
+ this._notifyListChanged();
+ this._checkListening();
+ }
+ }
+);
+
+/**
+ * Implement nsIDOMEventListener.
+ */
+BrowserTabList.prototype.handleEvent = DevToolsUtils.makeInfallible(function(
+ event
+) {
+ // If event target has `linkedBrowser`, the event target can be assumed <tab> element.
+ // Else, event target is assumed <browser> element, use the target as it is.
+ const browser = event.target.linkedBrowser || event.target;
+ switch (event.type) {
+ case "TabOpen":
+ case "TabSelect": {
+ /* Don't create a new actor; iterate will take care of that. Just notify. */
+ this._notifyListChanged();
+ this._checkListening();
+ break;
+ }
+ case "TabClose": {
+ const actor = this._actorByBrowser.get(browser);
+ if (actor) {
+ this._handleActorClose(actor, browser);
+ }
+ break;
+ }
+ case "TabAttrModified": {
+ // Remote <browser> title changes are handled via DOMTitleChange message
+ // TabAttrModified is only here for browsers in parent process which
+ // don't send this message.
+ if (browser.isRemoteBrowser) {
+ break;
+ }
+ const actor = this._actorByBrowser.get(browser);
+ if (actor) {
+ // TabAttrModified is fired in various cases, here only care about title
+ // changes
+ if (event.detail.changed.includes("label")) {
+ this._notifyListChanged();
+ this._checkListening();
+ }
+ }
+ break;
+ }
+ }
+},
+"BrowserTabList.prototype.handleEvent");
+
+/*
+ * If |shouldListen| is true, ensure we've registered a listener with the
+ * window mediator. Otherwise, ensure we haven't registered a listener.
+ */
+BrowserTabList.prototype._listenToMediatorIf = function(shouldListen) {
+ if (!shouldListen !== !this._listeningToMediator) {
+ const op = shouldListen ? "addListener" : "removeListener";
+ Services.wm[op](this);
+ this._listeningToMediator = shouldListen;
+ }
+};
+
+/**
+ * nsIWindowMediatorListener implementation.
+ *
+ * See _onTabClosed for explanation of why we needn't actually tweak any
+ * actors or tables here.
+ *
+ * An nsIWindowMediatorListener's methods get passed all sorts of windows; we
+ * only care about the tab containers. Those have 'gBrowser' members.
+ */
+BrowserTabList.prototype.onOpenWindow = DevToolsUtils.makeInfallible(function(
+ window
+) {
+ const handleLoad = DevToolsUtils.makeInfallible(() => {
+ /* We don't want any further load events from this window. */
+ window.removeEventListener("load", handleLoad);
+
+ if (appShellDOMWindowType(window) !== DevToolsServer.chromeWindowType) {
+ return;
+ }
+
+ // Listen for future tab activity.
+ if (this._listeningForTabOpen) {
+ window.addEventListener("TabOpen", this);
+ window.addEventListener("TabSelect", this);
+ window.addEventListener("TabAttrModified", this);
+ }
+ if (this._listeningForTabClose) {
+ window.addEventListener("TabClose", this);
+ }
+ if (this._listeningForTitleChange) {
+ window.messageManager.addMessageListener("DOMTitleChanged", this);
+ }
+
+ // As explained above, we will not receive a TabOpen event for this
+ // document's initial tab, so we must notify our client of the new tab
+ // this will have.
+ this._notifyListChanged();
+ });
+
+ /*
+ * You can hardly do anything at all with a XUL window at this point; it
+ * doesn't even have its document yet. Wait until its document has
+ * loaded, and then see what we've got. This also avoids
+ * nsIWindowMediator enumeration from within listeners (bug 873589).
+ */
+ window = window
+ .QueryInterface(Ci.nsIInterfaceRequestor)
+ .getInterface(Ci.nsIDOMWindow);
+
+ window.addEventListener("load", handleLoad);
+},
+"BrowserTabList.prototype.onOpenWindow");
+
+BrowserTabList.prototype.onCloseWindow = DevToolsUtils.makeInfallible(function(
+ window
+) {
+ if (window instanceof Ci.nsIAppWindow) {
+ window = window.docShell.domWindow;
+ }
+
+ if (appShellDOMWindowType(window) !== DevToolsServer.chromeWindowType) {
+ return;
+ }
+
+ /*
+ * nsIWindowMediator deadlocks if you call its GetEnumerator method from
+ * a nsIWindowMediatorListener's onCloseWindow hook (bug 873589), so
+ * handle the close in a different tick.
+ */
+ Services.tm.dispatchToMainThread(
+ DevToolsUtils.makeInfallible(() => {
+ /*
+ * Scan the entire map for actors representing tabs that were in this
+ * top-level window, and exit them.
+ */
+ for (const [browser, actor] of this._actorByBrowser) {
+ /* The browser document of a closed window has no default view. */
+ if (!browser.ownerGlobal) {
+ this._handleActorClose(actor, browser);
+ }
+ }
+ }, "BrowserTabList.prototype.onCloseWindow's delayed body")
+ );
+},
+"BrowserTabList.prototype.onCloseWindow");
+
+exports.BrowserTabList = BrowserTabList;
+
+function BrowserAddonList(connection) {
+ this._connection = connection;
+ this._actorByAddonId = new Map();
+ this._onListChanged = null;
+}
+
+BrowserAddonList.prototype.getList = async function() {
+ const addons = await AddonManager.getAllAddons();
+ for (const addon of addons) {
+ let actor = this._actorByAddonId.get(addon.id);
+ if (!actor) {
+ actor = new WebExtensionDescriptorActor(this._connection, addon);
+ this._actorByAddonId.set(addon.id, actor);
+ }
+ }
+
+ return Array.from(this._actorByAddonId, ([_, actor]) => actor);
+};
+
+Object.defineProperty(BrowserAddonList.prototype, "onListChanged", {
+ enumerable: true,
+ configurable: true,
+ get() {
+ return this._onListChanged;
+ },
+ set(v) {
+ if (v !== null && typeof v != "function") {
+ throw new Error(
+ "onListChanged property may only be set to 'null' or a function"
+ );
+ }
+ this._onListChanged = v;
+ this._adjustListener();
+ },
+});
+
+/**
+ * AddonManager listener must implement onDisabled.
+ */
+BrowserAddonList.prototype.onDisabled = function(addon) {
+ this._onAddonManagerUpdated();
+};
+
+/**
+ * AddonManager listener must implement onEnabled.
+ */
+BrowserAddonList.prototype.onEnabled = function(addon) {
+ this._onAddonManagerUpdated();
+};
+
+/**
+ * AddonManager listener must implement onInstalled.
+ */
+BrowserAddonList.prototype.onInstalled = function(addon) {
+ this._onAddonManagerUpdated();
+};
+
+/**
+ * AddonManager listener must implement onOperationCancelled.
+ */
+BrowserAddonList.prototype.onOperationCancelled = function(addon) {
+ this._onAddonManagerUpdated();
+};
+
+/**
+ * AddonManager listener must implement onUninstalling.
+ */
+BrowserAddonList.prototype.onUninstalling = function(addon) {
+ this._onAddonManagerUpdated();
+};
+
+/**
+ * AddonManager listener must implement onUninstalled.
+ */
+BrowserAddonList.prototype.onUninstalled = function(addon) {
+ this._actorByAddonId.delete(addon.id);
+ this._onAddonManagerUpdated();
+};
+
+BrowserAddonList.prototype._onAddonManagerUpdated = function(addon) {
+ this._notifyListChanged();
+ this._adjustListener();
+};
+
+BrowserAddonList.prototype._notifyListChanged = function() {
+ if (this._onListChanged) {
+ this._onListChanged();
+ }
+};
+
+BrowserAddonList.prototype._adjustListener = function() {
+ if (this._onListChanged) {
+ // As long as the callback exists, we need to listen for changes
+ // so we can notify about add-on changes.
+ AddonManager.addAddonListener(this);
+ } else if (this._actorByAddonId.size === 0) {
+ // When the callback does not exist, we only need to keep listening
+ // if the actor cache will need adjusting when add-ons change.
+ AddonManager.removeAddonListener(this);
+ }
+};
+
+exports.BrowserAddonList = BrowserAddonList;
diff --git a/devtools/server/actors/webconsole.js b/devtools/server/actors/webconsole.js
new file mode 100644
index 0000000000..8c302cfd02
--- /dev/null
+++ b/devtools/server/actors/webconsole.js
@@ -0,0 +1,2215 @@
+/* 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";
+
+/* global XPCNativeWrapper */
+const { ActorClassWithSpec, Actor } = require("devtools/shared/protocol");
+const { webconsoleSpec } = require("devtools/shared/specs/webconsole");
+
+const Services = require("Services");
+const { Cc, Ci, Cu } = require("chrome");
+const { DevToolsServer } = require("devtools/server/devtools-server");
+const { ThreadActor } = require("devtools/server/actors/thread");
+const { ObjectActor } = require("devtools/server/actors/object");
+const { LongStringActor } = require("devtools/server/actors/string");
+const {
+ createValueGrip,
+ isArray,
+ stringIsLong,
+} = require("devtools/server/actors/object/utils");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const ErrorDocs = require("devtools/server/actors/errordocs");
+
+loader.lazyRequireGetter(
+ this,
+ "evalWithDebugger",
+ "devtools/server/actors/webconsole/eval-with-debugger",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "NetworkMonitorActor",
+ "devtools/server/actors/network-monitor/network-monitor",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "ConsoleFileActivityListener",
+ "devtools/server/actors/webconsole/listeners/console-file-activity",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "StackTraceCollector",
+ "devtools/server/actors/network-monitor/stack-trace-collector",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "JSPropertyProvider",
+ "devtools/shared/webconsole/js-property-provider",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "NetUtil",
+ "resource://gre/modules/NetUtil.jsm",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["isCommand", "validCommands"],
+ "devtools/server/actors/webconsole/commands",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "createMessageManagerMocks",
+ "devtools/server/actors/webconsole/message-manager-mock",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ ["addWebConsoleCommands", "CONSOLE_WORKER_IDS", "WebConsoleUtils"],
+ "devtools/server/actors/webconsole/utils",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "EnvironmentActor",
+ "devtools/server/actors/environment",
+ true
+);
+loader.lazyRequireGetter(this, "EventEmitter", "devtools/shared/event-emitter");
+loader.lazyRequireGetter(
+ this,
+ "MESSAGE_CATEGORY",
+ "devtools/shared/constants",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "stringToCauseType",
+ "devtools/server/actors/network-monitor/network-observer",
+ true
+);
+
+// Generated by /devtools/shared/webconsole/GenerateReservedWordsJS.py
+loader.lazyRequireGetter(
+ this,
+ "RESERVED_JS_KEYWORDS",
+ "devtools/shared/webconsole/reserved-js-words"
+);
+
+// Overwrite implemented listeners for workers so that we don't attempt
+// to load an unsupported module.
+if (isWorker) {
+ loader.lazyRequireGetter(
+ this,
+ ["ConsoleAPIListener", "ConsoleServiceListener"],
+ "devtools/server/actors/webconsole/worker-listeners",
+ true
+ );
+} else {
+ loader.lazyRequireGetter(
+ this,
+ "ConsoleAPIListener",
+ "devtools/server/actors/webconsole/listeners/console-api",
+ true
+ );
+ loader.lazyRequireGetter(
+ this,
+ "ConsoleServiceListener",
+ "devtools/server/actors/webconsole/listeners/console-service",
+ true
+ );
+ loader.lazyRequireGetter(
+ this,
+ "ConsoleReflowListener",
+ "devtools/server/actors/webconsole/listeners/console-reflow",
+ true
+ );
+ loader.lazyRequireGetter(
+ this,
+ "ContentProcessListener",
+ "devtools/server/actors/webconsole/listeners/content-process",
+ true
+ );
+ loader.lazyRequireGetter(
+ this,
+ "DocumentEventsListener",
+ "devtools/server/actors/webconsole/listeners/document-events",
+ true
+ );
+}
+loader.lazyRequireGetter(
+ this,
+ "ObjectUtils",
+ "devtools/server/actors/object/utils"
+);
+
+function isObject(value) {
+ return Object(value) === value;
+}
+
+/**
+ * The WebConsoleActor implements capabilities needed for the Web Console
+ * feature.
+ *
+ * @constructor
+ * @param object connection
+ * The connection to the client, DevToolsServerConnection.
+ * @param object [parentActor]
+ * Optional, the parent actor.
+ */
+const WebConsoleActor = ActorClassWithSpec(webconsoleSpec, {
+ initialize: function(connection, parentActor) {
+ Actor.prototype.initialize.call(this, connection);
+ this.conn = connection;
+ this.parentActor = parentActor;
+
+ this._prefs = {};
+ this.dbg = this.parentActor.dbg;
+
+ this._gripDepth = 0;
+ this._evalCounter = 0;
+ this._listeners = new Set();
+ this._lastConsoleInputEvaluation = undefined;
+
+ this.objectGrip = this.objectGrip.bind(this);
+ this._onWillNavigate = this._onWillNavigate.bind(this);
+ this._onChangedToplevelDocument = this._onChangedToplevelDocument.bind(
+ this
+ );
+ this.onConsoleServiceMessage = this.onConsoleServiceMessage.bind(this);
+ this.onConsoleAPICall = this.onConsoleAPICall.bind(this);
+ this.onDocumentEvent = this.onDocumentEvent.bind(this);
+
+ EventEmitter.on(
+ this.parentActor,
+ "changed-toplevel-document",
+ this._onChangedToplevelDocument
+ );
+ this._onObserverNotification = this._onObserverNotification.bind(this);
+ if (this.parentActor.isRootActor) {
+ Services.obs.addObserver(
+ this._onObserverNotification,
+ "last-pb-context-exited"
+ );
+ }
+
+ this.traits = {
+ // Supports retrieving blocked urls
+ blockedUrls: true,
+ };
+ },
+ /**
+ * Debugger instance.
+ *
+ * @see jsdebugger.jsm
+ */
+ dbg: null,
+
+ /**
+ * This is used by the ObjectActor to keep track of the depth of grip() calls.
+ * @private
+ * @type number
+ */
+ _gripDepth: null,
+
+ /**
+ * Web Console-related preferences.
+ * @private
+ * @type object
+ */
+ _prefs: null,
+
+ /**
+ * Holds a set of all currently registered listeners.
+ *
+ * @private
+ * @type Set
+ */
+ _listeners: null,
+
+ /**
+ * The devtools server connection instance.
+ * @type object
+ */
+ conn: null,
+
+ /**
+ * List of supported features by the console actor.
+ * @type object
+ */
+ traits: null,
+
+ /**
+ * The global we work with (this can be a Window, a Worker global or even a Sandbox
+ * for processes and addons).
+ *
+ * @type nsIDOMWindow, WorkerGlobalScope or Sandbox
+ */
+ get global() {
+ if (this.parentActor.isRootActor) {
+ return this._getWindowForBrowserConsole();
+ }
+ return this.parentActor.window || this.parentActor.workerGlobal;
+ },
+
+ /**
+ * Get a window to use for the browser console.
+ *
+ * @private
+ * @return nsIDOMWindow
+ * The window to use, or null if no window could be found.
+ */
+ _getWindowForBrowserConsole: function() {
+ // Check if our last used chrome window is still live.
+ let window = this._lastChromeWindow && this._lastChromeWindow.get();
+ // If not, look for a new one.
+ if (!window || window.closed) {
+ window = this.parentActor.window;
+ if (!window) {
+ // Try to find the Browser Console window to use instead.
+ window = Services.wm.getMostRecentWindow("devtools:webconsole");
+ // We prefer the normal chrome window over the console window,
+ // so we'll look for those windows in order to replace our reference.
+ const onChromeWindowOpened = () => {
+ // We'll look for this window when someone next requests window()
+ Services.obs.removeObserver(onChromeWindowOpened, "domwindowopened");
+ this._lastChromeWindow = null;
+ };
+ Services.obs.addObserver(onChromeWindowOpened, "domwindowopened");
+ }
+
+ this._handleNewWindow(window);
+ }
+
+ return window;
+ },
+
+ /**
+ * Store a newly found window on the actor to be used in the future.
+ *
+ * @private
+ * @param nsIDOMWindow window
+ * The window to store on the actor (can be null).
+ */
+ _handleNewWindow: function(window) {
+ if (window) {
+ if (this._hadChromeWindow) {
+ Services.console.logStringMessage("Webconsole context has changed");
+ }
+ this._lastChromeWindow = Cu.getWeakReference(window);
+ this._hadChromeWindow = true;
+ } else {
+ this._lastChromeWindow = null;
+ }
+ },
+
+ /**
+ * Whether we've been using a window before.
+ *
+ * @private
+ * @type boolean
+ */
+ _hadChromeWindow: false,
+
+ /**
+ * A weak reference to the last chrome window we used to work with.
+ *
+ * @private
+ * @type nsIWeakReference
+ */
+ _lastChromeWindow: null,
+
+ // The evalGlobal is used at the scope for JS evaluation.
+ _evalGlobal: null,
+ get evalGlobal() {
+ return this._evalGlobal || this.global;
+ },
+
+ set evalGlobal(global) {
+ this._evalGlobal = global;
+
+ if (!this._progressListenerActive) {
+ EventEmitter.on(this.parentActor, "will-navigate", this._onWillNavigate);
+ this._progressListenerActive = true;
+ }
+ },
+
+ /**
+ * Flag used to track if we are listening for events from the progress
+ * listener of the target actor. We use the progress listener to clear
+ * this.evalGlobal on page navigation.
+ *
+ * @private
+ * @type boolean
+ */
+ _progressListenerActive: false,
+
+ /**
+ * The ConsoleServiceListener instance.
+ * @type object
+ */
+ consoleServiceListener: null,
+
+ /**
+ * The ConsoleAPIListener instance.
+ */
+ consoleAPIListener: null,
+
+ /**
+ * The ConsoleFileActivityListener instance.
+ */
+ consoleFileActivityListener: null,
+
+ /**
+ * The ConsoleReflowListener instance.
+ */
+ consoleReflowListener: null,
+
+ /**
+ * The Web Console Commands names cache.
+ * @private
+ * @type array
+ */
+ _webConsoleCommandsCache: null,
+
+ grip: function() {
+ return { actor: this.actorID };
+ },
+
+ hasNativeConsoleAPI: function(window) {
+ if (isWorker || !(window instanceof Ci.nsIDOMWindow)) {
+ // We can only use XPCNativeWrapper on non-worker nsIDOMWindow.
+ return true;
+ }
+
+ let isNative = false;
+ try {
+ // We are very explicitly examining the "console" property of
+ // the non-Xrayed object here.
+ const console = window.wrappedJSObject.console;
+ // In xpcshell tests, console ends up being undefined and XPCNativeWrapper
+ // crashes in debug builds.
+ if (console) {
+ isNative = new XPCNativeWrapper(console).IS_NATIVE_CONSOLE;
+ }
+ } catch (ex) {
+ // ignored
+ }
+ return isNative;
+ },
+
+ _findProtoChain: ThreadActor.prototype._findProtoChain,
+ _removeFromProtoChain: ThreadActor.prototype._removeFromProtoChain,
+
+ /**
+ * Destroy the current WebConsoleActor instance.
+ */
+ destroy() {
+ this.stopListeners();
+ Actor.prototype.destroy.call(this);
+
+ EventEmitter.off(
+ this.parentActor,
+ "changed-toplevel-document",
+ this._onChangedToplevelDocument
+ );
+
+ if (this.parentActor.isRootActor) {
+ Services.obs.removeObserver(
+ this._onObserverNotification,
+ "last-pb-context-exited"
+ );
+ }
+
+ this._webConsoleCommandsCache = null;
+ this._lastConsoleInputEvaluation = null;
+ this._evalGlobal = null;
+ this.dbg = null;
+ this.conn = null;
+ },
+
+ /**
+ * Create and return an environment actor that corresponds to the provided
+ * Debugger.Environment. This is a straightforward clone of the ThreadActor's
+ * method except that it stores the environment actor in the web console
+ * actor's pool.
+ *
+ * @param Debugger.Environment environment
+ * The lexical environment we want to extract.
+ * @return The EnvironmentActor for |environment| or |undefined| for host
+ * functions or functions scoped to a non-debuggee global.
+ */
+ createEnvironmentActor: function(environment) {
+ if (!environment) {
+ return undefined;
+ }
+
+ if (environment.actor) {
+ return environment.actor;
+ }
+
+ const actor = new EnvironmentActor(environment, this);
+ this.manage(actor);
+ environment.actor = actor;
+
+ return actor;
+ },
+
+ /**
+ * Create a grip for the given value.
+ *
+ * @param mixed value
+ * @return object
+ */
+ createValueGrip: function(value) {
+ return createValueGrip(value, this, this.objectGrip);
+ },
+
+ /**
+ * Make a debuggee value for the given value.
+ *
+ * @param mixed value
+ * The value you want to get a debuggee value for.
+ * @param boolean useObjectGlobal
+ * If |true| the object global is determined and added as a debuggee,
+ * otherwise |this.global| is used when makeDebuggeeValue() is invoked.
+ * @return object
+ * Debuggee value for |value|.
+ */
+ makeDebuggeeValue: function(value, useObjectGlobal) {
+ if (useObjectGlobal && isObject(value)) {
+ try {
+ const global = Cu.getGlobalForObject(value);
+ const dbgGlobal = this.dbg.makeGlobalObjectReference(global);
+ return dbgGlobal.makeDebuggeeValue(value);
+ } catch (ex) {
+ // The above can throw an exception if value is not an actual object
+ // or 'Object in compartment marked as invisible to Debugger'
+ }
+ }
+ const dbgGlobal = this.dbg.makeGlobalObjectReference(this.global);
+ return dbgGlobal.makeDebuggeeValue(value);
+ },
+
+ /**
+ * Create a grip for the given object.
+ *
+ * @param object object
+ * The object you want.
+ * @param object pool
+ * A Pool where the new actor instance is added.
+ * @param object
+ * The object grip.
+ */
+ objectGrip: function(object, pool) {
+ const actor = new ObjectActor(
+ object,
+ {
+ thread: this.parentActor.threadActor,
+ getGripDepth: () => this._gripDepth,
+ incrementGripDepth: () => this._gripDepth++,
+ decrementGripDepth: () => this._gripDepth--,
+ createValueGrip: v => this.createValueGrip(v),
+ createEnvironmentActor: env => this.createEnvironmentActor(env),
+ },
+ this.conn
+ );
+ pool.manage(actor);
+ return actor.form();
+ },
+
+ /**
+ * Create a grip for the given string.
+ *
+ * @param string string
+ * The string you want to create the grip for.
+ * @param object pool
+ * A Pool where the new actor instance is added.
+ * @return object
+ * A LongStringActor object that wraps the given string.
+ */
+ longStringGrip: function(string, pool) {
+ const actor = new LongStringActor(this.conn, string);
+ pool.manage(actor);
+ return actor.form();
+ },
+
+ /**
+ * Create a long string grip if needed for the given string.
+ *
+ * @private
+ * @param string string
+ * The string you want to create a long string grip for.
+ * @return string|object
+ * A string is returned if |string| is not a long string.
+ * A LongStringActor grip is returned if |string| is a long string.
+ */
+ _createStringGrip: function(string) {
+ if (string && stringIsLong(string)) {
+ return this.longStringGrip(string, this);
+ }
+ return string;
+ },
+
+ /**
+ * Returns the latest web console input evaluation.
+ * This is undefined if no evaluations have been completed.
+ *
+ * @return object
+ */
+ getLastConsoleInputEvaluation: function() {
+ return this._lastConsoleInputEvaluation;
+ },
+
+ /**
+ * Preprocess a debugger object (e.g. return the `boundTargetFunction`
+ * debugger object if the given debugger object is a bound function).
+ *
+ * This method is called by both the `inspect` binding implemented
+ * for the webconsole and the one implemented for the devtools API
+ * `browser.devtools.inspectedWindow.eval`.
+ */
+ preprocessDebuggerObject(dbgObj) {
+ // Returns the bound target function on a bound function.
+ if (dbgObj?.isBoundFunction && dbgObj?.boundTargetFunction) {
+ return dbgObj.boundTargetFunction;
+ }
+
+ return dbgObj;
+ },
+
+ /**
+ * This helper is used by the WebExtensionInspectedWindowActor to
+ * inspect an object in the developer toolbox.
+ *
+ * NOTE: shared parts related to preprocess the debugger object (between
+ * this function and the `inspect` webconsole command defined in
+ * "devtools/server/actor/webconsole/utils.js") should be added to
+ * the webconsole actors' `preprocessDebuggerObject` method.
+ */
+ inspectObject(dbgObj, inspectFromAnnotation) {
+ dbgObj = this.preprocessDebuggerObject(dbgObj);
+ this.emit("inspectObject", {
+ objectActor: this.createValueGrip(dbgObj),
+ inspectFromAnnotation,
+ });
+ },
+
+ // Request handlers for known packet types.
+
+ /**
+ * Handler for the "startListeners" request.
+ *
+ * @param array listeners
+ * An array of events to start sent by the Web Console client.
+ * @return object
+ * The response object which holds the startedListeners array.
+ */
+ // eslint-disable-next-line complexity
+ startListeners: async function(listeners) {
+ const startedListeners = [];
+ const global = !this.parentActor.isRootActor ? this.global : null;
+
+ for (const event of listeners) {
+ switch (event) {
+ case "PageError":
+ // Workers don't support this message type yet
+ if (isWorker) {
+ break;
+ }
+ if (!this.consoleServiceListener) {
+ this.consoleServiceListener = new ConsoleServiceListener(
+ global,
+ this.onConsoleServiceMessage
+ );
+ this.consoleServiceListener.init();
+ }
+ startedListeners.push(event);
+ break;
+ case "ConsoleAPI":
+ if (!this.consoleAPIListener) {
+ // Create the consoleAPIListener
+ // (and apply the filtering options defined in the parent actor).
+ this.consoleAPIListener = new ConsoleAPIListener(
+ global,
+ this.onConsoleAPICall,
+ this.parentActor.consoleAPIListenerOptions
+ );
+ this.consoleAPIListener.init();
+ }
+ startedListeners.push(event);
+ break;
+ case "NetworkActivity":
+ // Workers don't support this message type
+ if (isWorker) {
+ break;
+ }
+ if (!this.netmonitors) {
+ // Instanciate fake message managers used for service worker's netmonitor
+ // when running in the content process, and for netmonitor running in the
+ // same process when running in the parent process.
+ // `createMessageManagerMocks` returns a couple of connected messages
+ // managers that pass messages to each other to simulate the process
+ // boundary. We will use the first one for the webconsole-actor and the
+ // second one will be used by the netmonitor-actor.
+ const [mmMockParent, mmMockChild] = createMessageManagerMocks();
+
+ // Maintain the list of message manager we should message to/listen from
+ // to support the netmonitor instances, also records actorID of each
+ // NetworkMonitorActor.
+ // Array of `{ messageManager, parentProcess }`.
+ // Where `parentProcess` is true for the netmonitor actor instanciated in the
+ // parent process.
+ this.netmonitors = [];
+
+ // Check if the actor is running in a content process
+ const isInContentProcess =
+ Services.appinfo.processType !=
+ Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT &&
+ this.parentActor.messageManager;
+ if (isInContentProcess) {
+ // Start a network monitor in the parent process to listen to
+ // most requests that happen in parent. This one will communicate through
+ // `messageManager`.
+ await this.conn.spawnActorInParentProcess(this.actorID, {
+ module:
+ "devtools/server/actors/network-monitor/network-monitor",
+ constructor: "NetworkMonitorActor",
+ args: [{ browserId: this.parentActor.browserId }, this.actorID],
+ });
+ this.netmonitors.push({
+ messageManager: this.parentActor.messageManager,
+ parentProcess: true,
+ });
+ }
+
+ // When the console actor runs in the parent process, Netmonitor can be ran
+ // in the process and communicate through `messageManagerMock`.
+ // And while it runs in the content process, we also spawn one in the content
+ // to listen to requests that happen in the content process (for instance
+ // service workers requests)
+ new NetworkMonitorActor(
+ this.conn,
+ { window: global },
+ this.actorID,
+ mmMockParent
+ );
+
+ this.netmonitors.push({
+ messageManager: mmMockChild,
+ parentProcess: !isInContentProcess,
+ });
+
+ // Create a StackTraceCollector that's going to be shared both by
+ // the NetworkMonitorActor running in the same process for service worker
+ // requests, as well with the NetworkMonitorActor running in the parent
+ // process. It will communicate via message manager for this one.
+ this.stackTraceCollector = new StackTraceCollector(
+ { window: global },
+ this.netmonitors
+ );
+ this.stackTraceCollector.init();
+ }
+ startedListeners.push(event);
+ break;
+ case "FileActivity":
+ // Workers don't support this message type
+ if (isWorker) {
+ break;
+ }
+ if (this.global instanceof Ci.nsIDOMWindow) {
+ if (!this.consoleFileActivityListener) {
+ this.consoleFileActivityListener = new ConsoleFileActivityListener(
+ this.global,
+ this
+ );
+ }
+ this.consoleFileActivityListener.startMonitor();
+ startedListeners.push(event);
+ }
+ break;
+ case "ReflowActivity":
+ // Workers don't support this message type
+ if (isWorker) {
+ break;
+ }
+ if (!this.consoleReflowListener) {
+ this.consoleReflowListener = new ConsoleReflowListener(
+ this.global,
+ this
+ );
+ }
+ startedListeners.push(event);
+ break;
+ case "ContentProcessMessages":
+ // Workers don't support this message type
+ if (isWorker) {
+ break;
+ }
+ if (!this.contentProcessListener) {
+ this.contentProcessListener = new ContentProcessListener(
+ this.onConsoleAPICall
+ );
+ }
+ startedListeners.push(event);
+ break;
+ case "DocumentEvents":
+ // Workers don't support this message type
+ if (isWorker) {
+ break;
+ }
+ if (!this.documentEventsListener) {
+ this.documentEventsListener = new DocumentEventsListener(
+ this.parentActor
+ );
+ this.documentEventsListener.on("*", this.onDocumentEvent);
+ this.documentEventsListener.listen();
+ }
+ startedListeners.push(event);
+ break;
+ }
+ }
+
+ // Update the live list of running listeners
+ startedListeners.forEach(this._listeners.add, this._listeners);
+
+ return {
+ startedListeners: startedListeners,
+ nativeConsoleAPI: this.hasNativeConsoleAPI(this.global),
+ traits: this.traits,
+ };
+ },
+
+ /**
+ * Handler for the "stopListeners" request.
+ *
+ * @param array listeners
+ * An array of events to stop sent by the Web Console client.
+ * @return object
+ * The response packet to send to the client: holds the
+ * stoppedListeners array.
+ */
+ stopListeners: function(listeners) {
+ const stoppedListeners = [];
+
+ // If no specific listeners are requested to be detached, we stop all
+ // listeners.
+ const eventsToDetach = listeners || [
+ "PageError",
+ "ConsoleAPI",
+ "NetworkActivity",
+ "FileActivity",
+ "ReflowActivity",
+ "ContentProcessMessages",
+ "DocumentEvents",
+ ];
+
+ for (const event of eventsToDetach) {
+ switch (event) {
+ case "PageError":
+ if (this.consoleServiceListener) {
+ this.consoleServiceListener.destroy();
+ this.consoleServiceListener = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ case "ConsoleAPI":
+ if (this.consoleAPIListener) {
+ this.consoleAPIListener.destroy();
+ this.consoleAPIListener = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ case "NetworkActivity":
+ if (this.netmonitors) {
+ for (const { messageManager } of this.netmonitors) {
+ messageManager.sendAsyncMessage("debug:destroy-network-monitor", {
+ actorID: this.actorID,
+ });
+ }
+ this.netmonitors = null;
+ }
+ if (this.stackTraceCollector) {
+ this.stackTraceCollector.destroy();
+ this.stackTraceCollector = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ case "FileActivity":
+ if (this.consoleFileActivityListener) {
+ this.consoleFileActivityListener.stopMonitor();
+ this.consoleFileActivityListener = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ case "ReflowActivity":
+ if (this.consoleReflowListener) {
+ this.consoleReflowListener.destroy();
+ this.consoleReflowListener = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ case "ContentProcessMessages":
+ if (this.contentProcessListener) {
+ this.contentProcessListener.destroy();
+ this.contentProcessListener = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ case "DocumentEvents":
+ if (this.documentEventsListener) {
+ this.documentEventsListener.destroy();
+ this.documentEventsListener = null;
+ }
+ stoppedListeners.push(event);
+ break;
+ }
+ }
+
+ // Update the live list of running listeners
+ stoppedListeners.forEach(this._listeners.delete, this._listeners);
+
+ return { stoppedListeners: stoppedListeners };
+ },
+
+ /**
+ * Handler for the "getCachedMessages" request. This method sends the cached
+ * error messages and the window.console API calls to the client.
+ *
+ * @param array messageTypes
+ * An array of message types sent by the Web Console client.
+ * @return object
+ * The response packet to send to the client: it holds the cached
+ * messages array.
+ */
+ getCachedMessages: function(messageTypes) {
+ if (!messageTypes) {
+ return {
+ error: "missingParameter",
+ message: "The messageTypes parameter is missing.",
+ };
+ }
+
+ const messages = [];
+
+ const consoleServiceCachedMessages =
+ messageTypes.includes("PageError") || messageTypes.includes("LogMessage")
+ ? this.consoleServiceListener?.getCachedMessages(
+ !this.parentActor.isRootActor
+ )
+ : null;
+
+ for (const type of messageTypes) {
+ switch (type) {
+ case "ConsoleAPI": {
+ if (!this.consoleAPIListener) {
+ break;
+ }
+
+ // this.global might not be a window (can be a worker global or a Sandbox),
+ // and in such case performance isn't defined
+ const winStartTime = this.global?.performance?.timing
+ ?.navigationStart;
+
+ const cache = this.consoleAPIListener.getCachedMessages(
+ !this.parentActor.isRootActor
+ );
+ cache.forEach(cachedMessage => {
+ // Filter out messages that came from a ServiceWorker but happened
+ // before the page was requested.
+ if (
+ cachedMessage.innerID === "ServiceWorker" &&
+ winStartTime > cachedMessage.timeStamp
+ ) {
+ return;
+ }
+
+ messages.push({
+ message: this.prepareConsoleMessageForRemote(cachedMessage),
+ type: "consoleAPICall",
+ });
+ });
+ break;
+ }
+
+ case "PageError": {
+ if (!consoleServiceCachedMessages) {
+ break;
+ }
+
+ for (const cachedMessage of consoleServiceCachedMessages) {
+ if (!(cachedMessage instanceof Ci.nsIScriptError)) {
+ continue;
+ }
+
+ messages.push({
+ pageError: this.preparePageErrorForRemote(cachedMessage),
+ type: "pageError",
+ });
+ }
+ break;
+ }
+
+ case "LogMessage": {
+ if (!consoleServiceCachedMessages) {
+ break;
+ }
+
+ for (const cachedMessage of consoleServiceCachedMessages) {
+ if (cachedMessage instanceof Ci.nsIScriptError) {
+ continue;
+ }
+
+ messages.push({
+ message: this._createStringGrip(cachedMessage.message),
+ timeStamp: cachedMessage.timeStamp,
+ type: "logMessage",
+ });
+ }
+ break;
+ }
+ }
+ }
+
+ return {
+ messages: messages,
+ };
+ },
+
+ /**
+ * Handler for the "evaluateJSAsync" request. This method evaluates a given
+ * JavaScript string with an associated `resultID`.
+ *
+ * The result will be returned later as an unsolicited `evaluationResult`,
+ * that can be associated back to this request via the `resultID` field.
+ *
+ * @param object request
+ * The JSON request object received from the Web Console client.
+ * @return object
+ * The response packet to send to with the unique id in the
+ * `resultID` field.
+ */
+ evaluateJSAsync: async function(request) {
+ const startTime = Date.now();
+ // Use Date instead of UUID as this code is used by workers, which
+ // don't have access to the UUID XPCOM component.
+ // Also use a counter in order to prevent mixing up response when calling
+ // evaluateJSAsync during the same millisecond.
+ const resultID = startTime + "-" + this._evalCounter++;
+
+ // Execute the evaluation in the next event loop in order to immediately
+ // reply with the resultID.
+ DevToolsUtils.executeSoon(async () => {
+ try {
+ // Execute the script that may pause.
+ let response = await this.evaluateJS(request);
+ // Wait for any potential returned Promise.
+ response = await this._maybeWaitForResponseResult(response);
+ // Set the timestamp only now, so any messages logged in the expression will come
+ // before the result. Add an extra millisecond so the result has a different timestamp
+ // than the console message it might have emitted (unlike the evaluation result,
+ // console api messages are throttled before being handled by the webconsole client,
+ // which might cause some ordering issue).
+ response.timestamp = Date.now() + 1;
+ // Finally, emit an unsolicited evaluationResult packet with the evaluation result.
+ this.emit("evaluationResult", {
+ type: "evaluationResult",
+ resultID,
+ startTime,
+ ...response,
+ });
+ return;
+ } catch (e) {
+ const message = `Encountered error while waiting for Helper Result: ${e}\n${e.stack}`;
+ DevToolsUtils.reportException("evaluateJSAsync", Error(message));
+ }
+ });
+ return { resultID };
+ },
+
+ /**
+ * In order to have asynchronous commands (e.g. screenshot, top-level await, …) ,
+ * we have to be able to handle promises. This method handles waiting for the promise,
+ * and then returns the result.
+ *
+ * @private
+ * @param object response
+ * The response packet to send to with the unique id in the
+ * `resultID` field, and potentially a promise in the `helperResult` or in the
+ * `awaitResult` field.
+ *
+ * @return object
+ * The updated response object.
+ */
+ _maybeWaitForResponseResult: async function(response) {
+ if (!response) {
+ return response;
+ }
+
+ const thenable = obj => obj && typeof obj.then === "function";
+ const waitForHelperResult =
+ response.helperResult && thenable(response.helperResult);
+ const waitForAwaitResult =
+ response.awaitResult && thenable(response.awaitResult);
+
+ if (!waitForAwaitResult && !waitForHelperResult) {
+ return response;
+ }
+
+ // Wait for asynchronous command completion before sending back the response
+ if (waitForHelperResult) {
+ response.helperResult = await response.helperResult;
+ } else if (waitForAwaitResult) {
+ let result;
+ try {
+ result = await response.awaitResult;
+
+ // `createValueGrip` expect a debuggee value, while here we have the raw object.
+ // We need to call `makeDebuggeeValue` on it to make it work.
+ const dbgResult = this.makeDebuggeeValue(result);
+ response.result = this.createValueGrip(dbgResult);
+ } catch (e) {
+ // The promise was rejected. We let the engine handle this as it will report a
+ // `uncaught exception` error.
+ response.topLevelAwaitRejected = true;
+ }
+
+ // Remove the promise from the response object.
+ delete response.awaitResult;
+ }
+
+ return response;
+ },
+
+ /**
+ * Handler for the "evaluateJS" request. This method evaluates the given
+ * JavaScript string and sends back the result.
+ *
+ * @param object request
+ * The JSON request object received from the Web Console client.
+ * @return object
+ * The evaluation response packet.
+ */
+ evaluateJS: function(request) {
+ const input = request.text;
+
+ const evalOptions = {
+ frameActor: request.frameActor,
+ url: request.url,
+ innerWindowID: request.innerWindowID,
+ selectedNodeActor: request.selectedNodeActor,
+ selectedObjectActor: request.selectedObjectActor,
+ eager: request.eager,
+ bindings: request.bindings,
+ lineNumber: request.lineNumber,
+ };
+
+ const { mapped } = request;
+
+ // Set a flag on the thread actor which indicates an evaluation is being
+ // done for the client. This can affect how debugger handlers behave.
+ this.parentActor.threadActor.insideClientEvaluation = evalOptions;
+
+ const evalInfo = evalWithDebugger(input, evalOptions, this);
+
+ this.parentActor.threadActor.insideClientEvaluation = null;
+
+ return new Promise((resolve, reject) => {
+ // Queue up a task to run in the next tick so any microtask created by the evaluated
+ // expression has the time to be run.
+ // e.g. in :
+ // ```
+ // const promiseThenCb = result => "result: " + result;
+ // new Promise(res => res("hello")).then(promiseThenCb)
+ // ```
+ // we want`promiseThenCb` to have run before handling the result.
+ DevToolsUtils.executeSoon(() => {
+ try {
+ const result = this.prepareEvaluationResult(
+ evalInfo,
+ input,
+ request.eager,
+ mapped
+ );
+ resolve(result);
+ } catch (err) {
+ reject(err);
+ }
+ });
+ });
+ },
+
+ // eslint-disable-next-line complexity
+ prepareEvaluationResult: function(evalInfo, input, eager, mapped) {
+ const evalResult = evalInfo.result;
+ const helperResult = evalInfo.helperResult;
+
+ let result,
+ errorDocURL,
+ errorMessage,
+ errorNotes = null,
+ errorGrip = null,
+ frame = null,
+ awaitResult,
+ errorMessageName,
+ exceptionStack;
+ if (evalResult) {
+ if ("return" in evalResult) {
+ result = evalResult.return;
+ if (
+ mapped?.await &&
+ result &&
+ result.class === "Promise" &&
+ typeof result.unsafeDereference === "function"
+ ) {
+ awaitResult = result.unsafeDereference();
+ }
+ } else if ("yield" in evalResult) {
+ result = evalResult.yield;
+ } else if ("throw" in evalResult) {
+ const error = evalResult.throw;
+ errorGrip = this.createValueGrip(error);
+
+ exceptionStack = this.prepareStackForRemote(evalResult.stack);
+
+ if (exceptionStack) {
+ // Set the frame based on the topmost stack frame for the exception.
+ const {
+ filename: source,
+ sourceId,
+ lineNumber: line,
+ columnNumber: column,
+ } = exceptionStack[0];
+ frame = { source, sourceId, line, column };
+
+ exceptionStack = WebConsoleUtils.removeFramesAboveDebuggerEval(
+ exceptionStack
+ );
+ }
+
+ errorMessage = String(error);
+ if (typeof error === "object" && error !== null) {
+ try {
+ errorMessage = DevToolsUtils.callPropertyOnObject(
+ error,
+ "toString"
+ );
+ } catch (e) {
+ // If the debuggee is not allowed to access the "toString" property
+ // of the error object, calling this property from the debuggee's
+ // compartment will fail. The debugger should show the error object
+ // as it is seen by the debuggee, so this behavior is correct.
+ //
+ // Unfortunately, we have at least one test that assumes calling the
+ // "toString" property of an error object will succeed if the
+ // debugger is allowed to access it, regardless of whether the
+ // debuggee is allowed to access it or not.
+ //
+ // To accomodate these tests, if calling the "toString" property
+ // from the debuggee compartment fails, we rewrap the error object
+ // in the debugger's compartment, and then call the "toString"
+ // property from there.
+ if (typeof error.unsafeDereference === "function") {
+ const rawError = error.unsafeDereference();
+ errorMessage = rawError ? rawError.toString() : "";
+ }
+ }
+ }
+
+ // It is possible that we won't have permission to unwrap an
+ // object and retrieve its errorMessageName.
+ try {
+ errorDocURL = ErrorDocs.GetURL(error);
+ errorMessageName = error.errorMessageName;
+ } catch (ex) {
+ // ignored
+ }
+
+ try {
+ const line = error.errorLineNumber;
+ const column = error.errorColumnNumber;
+
+ if (typeof line === "number" && typeof column === "number") {
+ // Set frame only if we have line/column numbers.
+ frame = {
+ source: "debugger eval code",
+ line,
+ column,
+ };
+ }
+ } catch (ex) {
+ // ignored
+ }
+
+ try {
+ const notes = error.errorNotes;
+ if (notes?.length) {
+ errorNotes = [];
+ for (const note of notes) {
+ errorNotes.push({
+ messageBody: this._createStringGrip(note.message),
+ frame: {
+ source: note.fileName,
+ line: note.lineNumber,
+ column: note.columnNumber,
+ },
+ });
+ }
+ }
+ } catch (ex) {
+ // ignored
+ }
+ }
+ }
+
+ // If a value is encountered that the devtools server doesn't support yet,
+ // the console should remain functional.
+ let resultGrip;
+ if (!awaitResult) {
+ try {
+ const objectActor = this.parentActor.threadActor.getThreadLifetimeObject(
+ result
+ );
+ if (objectActor) {
+ resultGrip = this.parentActor.threadActor.createValueGrip(result);
+ } else {
+ resultGrip = this.createValueGrip(result);
+ }
+ } catch (e) {
+ errorMessage = e;
+ }
+ }
+
+ // Don't update _lastConsoleInputEvaluation in eager evaluation, as it would interfere
+ // with the $_ command.
+ if (!eager) {
+ if (!awaitResult) {
+ this._lastConsoleInputEvaluation = result;
+ } else {
+ // If we evaluated a top-level await expression, we want to assign its result to the
+ // _lastConsoleInputEvaluation only when the promise resolves, and only if it
+ // resolves. If the promise rejects, we don't re-assign _lastConsoleInputEvaluation,
+ // it will keep its previous value.
+
+ const p = awaitResult.then(res => {
+ this._lastConsoleInputEvaluation = this.makeDebuggeeValue(res);
+ });
+
+ // If the top level await was already rejected (e.g. `await Promise.reject("bleh")`),
+ // catch the resulting promise of awaitResult.then.
+ // If we don't do that, the new Promise will also be rejected, and since it's
+ // unhandled, it will generate an error.
+ // We don't want to do that for pending promise (e.g. `await new Promise((res, rej) => setTimeout(rej,250))`),
+ // as the the Promise rejection will be considered as handled, and the "Uncaught (in promise)"
+ // message wouldn't be emitted.
+ const { state } = ObjectUtils.getPromiseState(evalResult.return);
+ if (state === "rejected") {
+ p.catch(() => {});
+ }
+ }
+ }
+
+ return {
+ input: input,
+ result: resultGrip,
+ awaitResult,
+ exception: errorGrip,
+ exceptionMessage: this._createStringGrip(errorMessage),
+ exceptionDocURL: errorDocURL,
+ exceptionStack,
+ hasException: errorGrip !== null,
+ errorMessageName,
+ frame,
+ helperResult: helperResult,
+ notes: errorNotes,
+ };
+ },
+
+ /**
+ * The Autocomplete request handler.
+ *
+ * @param string text
+ * The request message - what input to autocomplete.
+ * @param number cursor
+ * The cursor position at the moment of starting autocomplete.
+ * @param string frameActor
+ * The frameactor id of the current paused frame.
+ * @param string selectedNodeActor
+ * The actor id of the currently selected node.
+ * @param array authorizedEvaluations
+ * Array of the properties access which can be executed by the engine.
+ * @return object
+ * The response message - matched properties.
+ */
+ autocomplete: function(
+ text,
+ cursor,
+ frameActorId,
+ selectedNodeActor,
+ authorizedEvaluations,
+ expressionVars = []
+ ) {
+ let dbgObject = null;
+ let environment = null;
+ let matches = [];
+ let matchProp;
+ let isElementAccess;
+
+ const reqText = text.substr(0, cursor);
+
+ if (isCommand(reqText)) {
+ const commandsCache = this._getWebConsoleCommandsCache();
+ matchProp = reqText;
+ matches = validCommands
+ .filter(
+ c =>
+ `:${c}`.startsWith(reqText) &&
+ commandsCache.find(n => `:${n}`.startsWith(reqText))
+ )
+ .map(c => `:${c}`);
+ } else {
+ // This is the case of the paused debugger
+ if (frameActorId) {
+ const frameActor = this.conn.getActor(frameActorId);
+ try {
+ // Need to try/catch since accessing frame.environment
+ // can throw "Debugger.Frame is not live"
+ const frame = frameActor.frame;
+ environment = frame.environment;
+ } catch (e) {
+ DevToolsUtils.reportException(
+ "autocomplete",
+ Error("The frame actor was not found: " + frameActorId)
+ );
+ }
+ } else {
+ dbgObject = this.dbg.addDebuggee(this.evalGlobal);
+ }
+
+ const result = JSPropertyProvider({
+ dbgObject,
+ environment,
+ inputValue: text,
+ cursor,
+ webconsoleActor: this,
+ selectedNodeActor,
+ authorizedEvaluations,
+ expressionVars,
+ });
+
+ if (result === null) {
+ return {
+ matches: null,
+ };
+ }
+
+ if (result && result.isUnsafeGetter === true) {
+ return {
+ isUnsafeGetter: true,
+ getterPath: result.getterPath,
+ };
+ }
+
+ matches = result.matches || new Set();
+ matchProp = result.matchProp || "";
+ isElementAccess = result.isElementAccess;
+
+ // We consider '$' as alphanumeric because it is used in the names of some
+ // helper functions; we also consider whitespace as alphanum since it should not
+ // be seen as break in the evaled string.
+ const lastNonAlphaIsDot = /[.][a-zA-Z0-9$\s]*$/.test(reqText);
+
+ // We only return commands and keywords when we are not dealing with a property or
+ // element access.
+ if (matchProp && !lastNonAlphaIsDot && !isElementAccess) {
+ this._getWebConsoleCommandsCache().forEach(n => {
+ // filter out `screenshot` command as it is inaccessible without the `:` prefix
+ if (n !== "screenshot" && n.startsWith(result.matchProp)) {
+ matches.add(n);
+ }
+ });
+
+ for (const keyword of RESERVED_JS_KEYWORDS) {
+ if (keyword.startsWith(result.matchProp)) {
+ matches.add(keyword);
+ }
+ }
+ }
+
+ // Sort the results in order to display lowercased item first (e.g. we want to
+ // display `document` then `Document` as we loosely match the user input if the
+ // first letter was lowercase).
+ const firstMeaningfulCharIndex = isElementAccess ? 1 : 0;
+ matches = Array.from(matches).sort((a, b) => {
+ const aFirstMeaningfulChar = a[firstMeaningfulCharIndex];
+ const bFirstMeaningfulChar = b[firstMeaningfulCharIndex];
+ const lA =
+ aFirstMeaningfulChar.toLocaleLowerCase() === aFirstMeaningfulChar;
+ const lB =
+ bFirstMeaningfulChar.toLocaleLowerCase() === bFirstMeaningfulChar;
+ if (lA === lB) {
+ if (a === matchProp) {
+ return -1;
+ }
+ if (b === matchProp) {
+ return 1;
+ }
+ return a.localeCompare(b);
+ }
+ return lA ? -1 : 1;
+ });
+ }
+
+ return {
+ matches,
+ matchProp,
+ isElementAccess: isElementAccess === true,
+ };
+ },
+
+ /**
+ * The "clearMessagesCache" request handler.
+ */
+ clearMessagesCache: function() {
+ if (isWorker) {
+ // At the moment there is no mechanism available to clear the Console API cache for
+ // a given worker target (See https://bugzilla.mozilla.org/show_bug.cgi?id=1674336).
+ // Worker messages from the console service (e.g. error) are emitted from the main
+ // thread, so this cache will be cleared when the associated document target cache
+ // is cleared.
+ return;
+ }
+
+ const windowId = !this.parentActor.isRootActor
+ ? WebConsoleUtils.getInnerWindowId(this.global)
+ : null;
+
+ const ConsoleAPIStorage = Cc[
+ "@mozilla.org/consoleAPI-storage;1"
+ ].getService(Ci.nsIConsoleAPIStorage);
+ ConsoleAPIStorage.clearEvents(windowId);
+
+ CONSOLE_WORKER_IDS.forEach(id => {
+ ConsoleAPIStorage.clearEvents(id);
+ });
+
+ if (this.parentActor.isRootActor || !this.global) {
+ // If were dealing with the root actor (e.g. the browser console), we want
+ // to remove all cached messages, not only the ones specific to a window.
+ Services.console.reset();
+ } else {
+ WebConsoleUtils.getInnerWindowIDsForFrames(this.global).forEach(id =>
+ Services.console.resetWindow(id)
+ );
+ }
+ },
+
+ /**
+ * The "getPreferences" request handler.
+ *
+ * @param array preferences
+ * The preferences that need to be retrieved.
+ * @return object
+ * The response message - a { key: value } object map.
+ */
+ getPreferences: function(preferences) {
+ const prefs = Object.create(null);
+ for (const key of preferences) {
+ prefs[key] = this._prefs[key];
+ }
+ return { preferences: prefs };
+ },
+
+ /**
+ * The "setPreferences" request handler.
+ *
+ * @param object preferences
+ * The preferences that need to be updated.
+ */
+ setPreferences: function(preferences) {
+ for (const key in preferences) {
+ this._prefs[key] = preferences[key];
+
+ if (this.netmonitors) {
+ if (key == "NetworkMonitor.saveRequestAndResponseBodies") {
+ for (const { messageManager } of this.netmonitors) {
+ messageManager.sendAsyncMessage("debug:netmonitor-preference", {
+ saveRequestAndResponseBodies: this._prefs[key],
+ });
+ }
+ } else if (key == "NetworkMonitor.throttleData") {
+ for (const { messageManager } of this.netmonitors) {
+ messageManager.sendAsyncMessage("debug:netmonitor-preference", {
+ throttleData: this._prefs[key],
+ });
+ }
+ }
+ }
+ }
+ return { updated: Object.keys(preferences) };
+ },
+
+ // End of request handlers.
+
+ /**
+ * Create an object with the API we expose to the Web Console during
+ * JavaScript evaluation.
+ * This object inherits properties and methods from the Web Console actor.
+ *
+ * @private
+ * @param object debuggerGlobal
+ * A Debugger.Object that wraps a content global. This is used for the
+ * Web Console Commands.
+ * @return object
+ * The same object as |this|, but with an added |sandbox| property.
+ * The sandbox holds methods and properties that can be used as
+ * bindings during JS evaluation.
+ */
+ _getWebConsoleCommands: function(debuggerGlobal) {
+ const helpers = {
+ window: this.evalGlobal,
+ makeDebuggeeValue: debuggerGlobal.makeDebuggeeValue.bind(debuggerGlobal),
+ createValueGrip: this.createValueGrip.bind(this),
+ preprocessDebuggerObject: this.preprocessDebuggerObject.bind(this),
+ sandbox: Object.create(null),
+ helperResult: null,
+ consoleActor: this,
+ };
+ addWebConsoleCommands(helpers);
+
+ const evalGlobal = this.evalGlobal;
+ function maybeExport(obj, name) {
+ if (typeof obj[name] != "function") {
+ return;
+ }
+
+ // By default, chrome-implemented functions that are exposed to content
+ // refuse to accept arguments that are cross-origin for the caller. This
+ // is generally the safe thing, but causes problems for certain console
+ // helpers like cd(), where we users sometimes want to pass a cross-origin
+ // window. To circumvent this restriction, we use exportFunction along
+ // with a special option designed for this purpose. See bug 1051224.
+ obj[name] = Cu.exportFunction(obj[name], evalGlobal, {
+ allowCrossOriginArguments: true,
+ });
+ }
+ for (const name in helpers.sandbox) {
+ const desc = Object.getOwnPropertyDescriptor(helpers.sandbox, name);
+
+ // Workers don't have access to Cu so won't be able to exportFunction.
+ if (!isWorker) {
+ maybeExport(desc, "get");
+ maybeExport(desc, "set");
+ maybeExport(desc, "value");
+ }
+ if (desc.value) {
+ // Make sure the helpers can be used during eval.
+ desc.value = debuggerGlobal.makeDebuggeeValue(desc.value);
+ }
+ Object.defineProperty(helpers.sandbox, name, desc);
+ }
+ return helpers;
+ },
+
+ _getWebConsoleCommandsCache: function() {
+ if (!this._webConsoleCommandsCache) {
+ const helpers = {
+ sandbox: Object.create(null),
+ };
+ addWebConsoleCommands(helpers);
+ this._webConsoleCommandsCache = Object.getOwnPropertyNames(
+ helpers.sandbox
+ );
+ }
+ return this._webConsoleCommandsCache;
+ },
+
+ // Event handlers for various listeners.
+
+ /**
+ * Handler for messages received from the ConsoleServiceListener. This method
+ * sends the nsIConsoleMessage to the remote Web Console client.
+ *
+ * @param nsIConsoleMessage message
+ * The message we need to send to the client.
+ */
+ onConsoleServiceMessage: function(message) {
+ if (message instanceof Ci.nsIScriptError) {
+ this.emit("pageError", {
+ pageError: this.preparePageErrorForRemote(message),
+ });
+ } else {
+ this.emit("logMessage", {
+ message: this._createStringGrip(message.message),
+ timeStamp: message.timeStamp,
+ });
+ }
+ },
+
+ getActorIdForInternalSourceId(id) {
+ const actor = this.parentActor.sourcesManager.getSourceActorByInternalSourceId(
+ id
+ );
+ return actor ? actor.actorID : null;
+ },
+
+ /**
+ * Prepare a SavedFrame stack to be sent to the client.
+ *
+ * @param SavedFrame errorStack
+ * Stack for an error we need to send to the client.
+ * @return object
+ * The object you can send to the remote client.
+ */
+ prepareStackForRemote(errorStack) {
+ // Convert stack objects to the JSON attributes expected by client code
+ // Bug 1348885: If the global from which this error came from has been
+ // nuked, stack is going to be a dead wrapper.
+ if (!errorStack || (Cu && Cu.isDeadWrapper(errorStack))) {
+ return null;
+ }
+ const stack = [];
+ let s = errorStack;
+ while (s) {
+ stack.push({
+ filename: s.source,
+ sourceId: this.getActorIdForInternalSourceId(s.sourceId),
+ lineNumber: s.line,
+ columnNumber: s.column,
+ functionName: s.functionDisplayName,
+ asyncCause: s.asyncCause ? s.asyncCause : undefined,
+ });
+ s = s.parent || s.asyncParent;
+ }
+ return stack;
+ },
+
+ /**
+ * Prepare an nsIScriptError to be sent to the client.
+ *
+ * @param nsIScriptError pageError
+ * The page error we need to send to the client.
+ * @return object
+ * The object you can send to the remote client.
+ */
+ preparePageErrorForRemote: function(pageError) {
+ const stack = this.prepareStackForRemote(pageError.stack);
+ let lineText = pageError.sourceLine;
+ if (
+ lineText &&
+ lineText.length > DevToolsServer.LONG_STRING_INITIAL_LENGTH
+ ) {
+ lineText = lineText.substr(0, DevToolsServer.LONG_STRING_INITIAL_LENGTH);
+ }
+
+ let notesArray = null;
+ const notes = pageError.notes;
+ if (notes?.length) {
+ notesArray = [];
+ for (let i = 0, len = notes.length; i < len; i++) {
+ const note = notes.queryElementAt(i, Ci.nsIScriptErrorNote);
+ notesArray.push({
+ messageBody: this._createStringGrip(note.errorMessage),
+ frame: {
+ source: note.sourceName,
+ sourceId: this.getActorIdForInternalSourceId(note.sourceId),
+ line: note.lineNumber,
+ column: note.columnNumber,
+ },
+ });
+ }
+ }
+
+ // If there is no location information in the error but we have a stack,
+ // fill in the location with the first frame on the stack.
+ let { sourceName, sourceId, lineNumber, columnNumber } = pageError;
+ if (!sourceName && !sourceId && !lineNumber && !columnNumber && stack) {
+ sourceName = stack[0].filename;
+ sourceId = stack[0].sourceId;
+ lineNumber = stack[0].lineNumber;
+ columnNumber = stack[0].columnNumber;
+ }
+
+ const isCSSMessage = pageError.category === MESSAGE_CATEGORY.CSS_PARSER;
+
+ const result = {
+ errorMessage: this._createStringGrip(pageError.errorMessage),
+ errorMessageName: isCSSMessage ? undefined : pageError.errorMessageName,
+ exceptionDocURL: ErrorDocs.GetURL(pageError),
+ sourceName,
+ sourceId: this.getActorIdForInternalSourceId(sourceId),
+ lineText,
+ lineNumber,
+ columnNumber,
+ category: pageError.category,
+ innerWindowID: pageError.innerWindowID,
+ timeStamp: pageError.timeStamp,
+ warning: !!(pageError.flags & pageError.warningFlag),
+ error: !(pageError.flags & (pageError.warningFlag | pageError.infoFlag)),
+ info: !!(pageError.flags & pageError.infoFlag),
+ private: pageError.isFromPrivateWindow,
+ stacktrace: stack,
+ notes: notesArray,
+ chromeContext: pageError.isFromChromeContext,
+ isPromiseRejection: isCSSMessage
+ ? undefined
+ : pageError.isPromiseRejection,
+ isForwardedFromContentProcess: pageError.isForwardedFromContentProcess,
+ cssSelectors: isCSSMessage ? pageError.cssSelectors : undefined,
+ };
+
+ // If the pageError does have an exception object, we want to return the grip for it,
+ // but only if we do manage to get the grip, as we're checking the property on the
+ // client to render things differently.
+ if (pageError.hasException) {
+ try {
+ const obj = this.makeDebuggeeValue(pageError.exception, true);
+ if (obj?.class !== "DeadObject") {
+ result.exception = this.createValueGrip(obj);
+ result.hasException = true;
+ }
+ } catch (e) {}
+ }
+
+ return result;
+ },
+
+ /**
+ * Handler for window.console API calls received from the ConsoleAPIListener.
+ * This method sends the object to the remote Web Console client.
+ *
+ * @see ConsoleAPIListener
+ * @param object message
+ * The console API call we need to send to the remote client.
+ */
+ onConsoleAPICall: function(message) {
+ this.emit("consoleAPICall", {
+ message: this.prepareConsoleMessageForRemote(message),
+ });
+ },
+
+ /**
+ * Handler for the DocumentEventsListener.
+ *
+ * @see DocumentEventsListener
+ * @param {String} name
+ * The document event name that either of followings.
+ * - dom-loading
+ * - dom-interactive
+ * - dom-complete
+ * @param {Number} time
+ * The time that the event is fired.
+ */
+ onDocumentEvent: function(name, time) {
+ this.emit("documentEvent", {
+ name,
+ time,
+ });
+ },
+
+ /**
+ * Send a new HTTP request from the target's window.
+ *
+ * @param object request
+ * The details of the HTTP request.
+ */
+ async sendHTTPRequest(request) {
+ const { url, method, headers, body, cause } = request;
+ // Set the loadingNode and loadGroup to the target document - otherwise the
+ // request won't show up in the opened netmonitor.
+ const doc = this.global.document;
+
+ const channel = NetUtil.newChannel({
+ uri: NetUtil.newURI(url),
+ loadingNode: doc,
+ securityFlags: Ci.nsILoadInfo.SEC_ALLOW_CROSS_ORIGIN_SEC_CONTEXT_IS_NULL,
+ contentPolicyType:
+ stringToCauseType(cause.type) || Ci.nsIContentPolicy.TYPE_OTHER,
+ });
+
+ channel.QueryInterface(Ci.nsIHttpChannel);
+
+ channel.loadGroup = doc.documentLoadGroup;
+ channel.loadFlags |=
+ Ci.nsIRequest.LOAD_BYPASS_CACHE |
+ Ci.nsIRequest.INHIBIT_CACHING |
+ Ci.nsIRequest.LOAD_ANONYMOUS;
+
+ channel.requestMethod = method;
+ if (headers) {
+ for (const { name, value } of headers) {
+ if (name.toLowerCase() == "referer") {
+ // The referer header and referrerInfo object should always match. So
+ // if we want to set the header from privileged context, we should set
+ // referrerInfo. The referrer header will get set internally.
+ channel.setNewReferrerInfo(
+ value,
+ Ci.nsIReferrerInfo.UNSAFE_URL,
+ true
+ );
+ } else {
+ channel.setRequestHeader(name, value, false);
+ }
+ }
+ }
+
+ if (body) {
+ channel.QueryInterface(Ci.nsIUploadChannel2);
+ const bodyStream = Cc[
+ "@mozilla.org/io/string-input-stream;1"
+ ].createInstance(Ci.nsIStringInputStream);
+ bodyStream.setData(body, body.length);
+ channel.explicitSetUploadStream(bodyStream, null, -1, method, false);
+ }
+
+ NetUtil.asyncFetch(channel, () => {});
+
+ if (!this.netmonitors) {
+ return null;
+ }
+ const { channelId } = channel;
+ // Only query the NetworkMonitorActor running in the parent process, where the
+ // request will be done. There always is one listener running in the parent process,
+ // see startListeners.
+ const netmonitor = this.netmonitors.filter(
+ ({ parentProcess }) => parentProcess
+ )[0];
+ const { messageManager } = netmonitor;
+ return new Promise(resolve => {
+ const onMessage = ({ data }) => {
+ if (data.channelId == channelId) {
+ messageManager.removeMessageListener(
+ "debug:get-network-event-actor:response",
+ onMessage
+ );
+ resolve({
+ eventActor: data.actor,
+ });
+ }
+ };
+ messageManager.addMessageListener(
+ "debug:get-network-event-actor:response",
+ onMessage
+ );
+ messageManager.sendAsyncMessage("debug:get-network-event-actor:request", {
+ channelId,
+ });
+ });
+ },
+
+ /**
+ * Send a message to all the netmonitor message managers, and resolve when
+ * all of them replied with the expected responseName message.
+ *
+ * @param {String} messageName
+ * Name of the message to send via the netmonitor message managers.
+ * @param {String} responseName
+ * Name of the message that should be received when the message has
+ * been processed by the netmonitor instance.
+ * @param {Object} args
+ * argument object passed with the initial message.
+ */
+ async _sendMessageToNetmonitors(messageName, responseName, args) {
+ if (!this.netmonitors) {
+ return null;
+ }
+ const results = await Promise.all(
+ this.netmonitors.map(({ messageManager }) => {
+ const onResponseReceived = new Promise(resolve => {
+ messageManager.addMessageListener(responseName, function onResponse(
+ response
+ ) {
+ messageManager.removeMessageListener(responseName, onResponse);
+ resolve(response);
+ });
+ });
+ messageManager.sendAsyncMessage(messageName, args);
+ return onResponseReceived;
+ })
+ );
+
+ return results;
+ },
+
+ /**
+ * Block a request based on certain filtering options.
+ *
+ * Currently, an exact URL match is the only supported filter type.
+ * In the future, there may be other types of filters, such as domain.
+ * For now, ignore anything other than URL.
+ *
+ * @param object filter
+ * An object containing a `url` key with a URL to block.
+ */
+ async blockRequest(filter) {
+ await this._sendMessageToNetmonitors(
+ "debug:block-request",
+ "debug:block-request:response",
+ { filter }
+ );
+
+ return {};
+ },
+
+ /**
+ * Unblock a request based on certain filtering options.
+ *
+ * Currently, an exact URL match is the only supported filter type.
+ * In the future, there may be other types of filters, such as domain.
+ * For now, ignore anything other than URL.
+ *
+ * @param object filter
+ * An object containing a `url` key with a URL to unblock.
+ */
+ async unblockRequest(filter) {
+ await this._sendMessageToNetmonitors(
+ "debug:unblock-request",
+ "debug:unblock-request:response",
+ { filter }
+ );
+
+ return {};
+ },
+
+ /*
+ * Gets the list of blocked request urls as per the backend
+ */
+ async getBlockedUrls() {
+ const responses =
+ (await this._sendMessageToNetmonitors(
+ "debug:get-blocked-urls",
+ "debug:get-blocked-urls:response"
+ )) || [];
+ if (!responses || responses.length == 0) {
+ return [];
+ }
+
+ return Array.from(
+ new Set(
+ responses
+ .filter(response => response.data)
+ .map(response => response.data)
+ )
+ );
+ },
+
+ /**
+ * Sets the list of blocked request URLs as provided by the netmonitor frontend
+ *
+ * This match will be a (String).includes match, not an exact URL match
+ *
+ * @param object filter
+ * An object containing a `url` key with a URL to unblock.
+ */
+ async setBlockedUrls(urls) {
+ await this._sendMessageToNetmonitors(
+ "debug:set-blocked-urls",
+ "debug:set-blocked-urls:response",
+ { urls }
+ );
+
+ return {};
+ },
+
+ /**
+ * Handler for file activity. This method sends the file request information
+ * to the remote Web Console client.
+ *
+ * @see ConsoleFileActivityListener
+ * @param string fileURI
+ * The requested file URI.
+ */
+ onFileActivity: function(fileURI) {
+ this.emit("fileActivity", {
+ uri: fileURI,
+ });
+ },
+
+ // End of event handlers for various listeners.
+
+ /**
+ * Prepare a message from the console API to be sent to the remote Web Console
+ * instance.
+ *
+ * @param object message
+ * The original message received from console-api-log-event.
+ * @param boolean aUseObjectGlobal
+ * If |true| the object global is determined and added as a debuggee,
+ * otherwise |this.global| is used when makeDebuggeeValue() is invoked.
+ * @return object
+ * The object that can be sent to the remote client.
+ */
+ prepareConsoleMessageForRemote: function(message, useObjectGlobal = true) {
+ const result = WebConsoleUtils.cloneObject(message);
+
+ result.workerType = WebConsoleUtils.getWorkerType(result) || "none";
+ result.sourceId = this.getActorIdForInternalSourceId(result.sourceId);
+
+ delete result.wrappedJSObject;
+ delete result.ID;
+ delete result.innerID;
+ delete result.consoleID;
+
+ if (result.stacktrace) {
+ result.stacktrace = result.stacktrace.map(frame => {
+ return {
+ ...frame,
+ sourceId: this.getActorIdForInternalSourceId(frame.sourceId),
+ };
+ });
+ }
+
+ result.arguments = (message.arguments || []).map(obj => {
+ const dbgObj = this.makeDebuggeeValue(obj, useObjectGlobal);
+ return this.createValueGrip(dbgObj);
+ });
+
+ result.styles = (message.styles || []).map(string => {
+ return this.createValueGrip(string);
+ });
+
+ if (result.level === "table") {
+ const tableItems = this._getConsoleTableMessageItems(result);
+ if (tableItems) {
+ result.arguments[0].ownProperties = tableItems;
+ result.arguments[0].preview = null;
+ }
+
+ // Only return the 2 first params.
+ result.arguments = result.arguments.slice(0, 2);
+ }
+
+ result.category = message.category || "webdev";
+ result.innerWindowID = message.innerID;
+
+ return result;
+ },
+
+ /**
+ * Return the properties needed to display the appropriate table for a given
+ * console.table call.
+ * This function does a little more than creating an ObjectActor for the first
+ * parameter of the message. When layout out the console table in the output, we want
+ * to be able to look into sub-properties so the table can have a different layout (
+ * for arrays of arrays, objects with objects properties, arrays of objects, …).
+ * So here we need to retrieve the properties of the first parameter, and also all the
+ * sub-properties we might need.
+ *
+ * @param {Object} result: The console.table message.
+ * @returns {Object} An object containing the properties of the first argument of the
+ * console.table call.
+ */
+ _getConsoleTableMessageItems: function(result) {
+ if (
+ !result ||
+ !Array.isArray(result.arguments) ||
+ result.arguments.length == 0
+ ) {
+ return null;
+ }
+
+ const [tableItemGrip] = result.arguments;
+ const dataType = tableItemGrip.class;
+ const needEntries = ["Map", "WeakMap", "Set", "WeakSet"].includes(dataType);
+ const ignoreNonIndexedProperties = isArray(tableItemGrip);
+
+ const tableItemActor = this.getActorByID(tableItemGrip.actor);
+ if (!tableItemActor) {
+ return null;
+ }
+
+ // Retrieve the properties (or entries for Set/Map) of the console table first arg.
+ const iterator = needEntries
+ ? tableItemActor.enumEntries()
+ : tableItemActor.enumProperties({
+ ignoreNonIndexedProperties,
+ });
+ const { ownProperties } = iterator.all();
+
+ // The iterator returns a descriptor for each property, wherein the value could be
+ // in one of those sub-property.
+ const descriptorKeys = ["safeGetterValues", "getterValue", "value"];
+
+ Object.values(ownProperties).forEach(desc => {
+ if (typeof desc !== "undefined") {
+ descriptorKeys.forEach(key => {
+ if (desc && desc.hasOwnProperty(key)) {
+ const grip = desc[key];
+
+ // We need to load sub-properties as well to render the table in a nice way.
+ const actor = grip && this.getActorByID(grip.actor);
+ if (actor) {
+ const res = actor
+ .enumProperties({
+ ignoreNonIndexedProperties: isArray(grip),
+ })
+ .all();
+ if (res?.ownProperties) {
+ desc[key].ownProperties = res.ownProperties;
+ }
+ }
+ }
+ });
+ }
+ });
+
+ return ownProperties;
+ },
+
+ /**
+ * Notification observer for the "last-pb-context-exited" topic.
+ *
+ * @private
+ * @param object subject
+ * Notification subject - in this case it is the inner window ID that
+ * was destroyed.
+ * @param string topic
+ * Notification topic.
+ */
+ _onObserverNotification: function(subject, topic) {
+ if (topic === "last-pb-context-exited") {
+ this.emit("lastPrivateContextExited");
+ }
+ },
+
+ /**
+ * The "will-navigate" progress listener. This is used to clear the current
+ * eval scope.
+ */
+ _onWillNavigate: function({ window, isTopLevel }) {
+ if (isTopLevel) {
+ this._evalGlobal = null;
+ EventEmitter.off(this.parentActor, "will-navigate", this._onWillNavigate);
+ this._progressListenerActive = false;
+ }
+ },
+
+ /**
+ * This listener is called when we switch to another frame,
+ * mostly to unregister previous listeners and start listening on the new document.
+ */
+ _onChangedToplevelDocument: function() {
+ // Convert the Set to an Array
+ const listeners = [...this._listeners];
+
+ // Unregister existing listener on the previous document
+ // (pass a copy of the array as it will shift from it)
+ this.stopListeners(listeners.slice());
+
+ // This method is called after this.global is changed,
+ // so we register new listener on this new global
+ this.startListeners(listeners);
+
+ // Also reset the cached top level chrome window being targeted
+ this._lastChromeWindow = null;
+ },
+});
+
+exports.WebConsoleActor = WebConsoleActor;
diff --git a/devtools/server/actors/webconsole/commands.js b/devtools/server/actors/webconsole/commands.js
new file mode 100644
index 0000000000..9e3b8f90d0
--- /dev/null
+++ b/devtools/server/actors/webconsole/commands.js
@@ -0,0 +1,245 @@
+/* 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";
+
+const validCommands = ["block", "help", "screenshot", "unblock"];
+
+const COMMAND = "command";
+const KEY = "key";
+const ARG = "arg";
+
+const COMMAND_PREFIX = /^:/;
+const KEY_PREFIX = /^--/;
+
+// default value for flags
+const DEFAULT_VALUE = true;
+const COMMAND_DEFAULT_FLAG = {
+ block: "url",
+ screenshot: "filename",
+ unblock: "url",
+};
+
+/**
+ * When given a string that begins with `:` and a unix style string,
+ * format a JS like object.
+ * This is intended to be used by the WebConsole actor only.
+ *
+ * @param String string
+ * A string to format that begins with `:`.
+ *
+ * @returns String formatted as `command({ ..args })`
+ */
+function formatCommand(string) {
+ if (!isCommand(string)) {
+ throw Error("formatCommand was called without `:`");
+ }
+ const tokens = string
+ .trim()
+ .split(/\s+/)
+ .map(createToken);
+ const { command, args } = parseCommand(tokens);
+ const argsString = formatArgs(args);
+ return `${command}(${argsString})`;
+}
+
+/**
+ * collapses the array of arguments from the parsed command into
+ * a single string
+ *
+ * @param Object tree
+ * A tree object produced by parseCommand
+ *
+ * @returns String formatted as ` { key: value, ... } ` or an empty string
+ */
+function formatArgs(args) {
+ return Object.keys(args).length ? JSON.stringify(args) : "";
+}
+
+/**
+ * creates a token object depending on a string which as a prefix,
+ * either `:` for a command or `--` for a key, or nothing for an argument
+ *
+ * @param String string
+ * A string to use as the basis for the token
+ *
+ * @returns Object Token Object, with the following shape
+ * { type: String, value: String }
+ */
+function createToken(string) {
+ if (isCommand(string)) {
+ const value = string.replace(COMMAND_PREFIX, "");
+ if (!value || !validCommands.includes(value)) {
+ throw Error(`'${value}' is not a valid command`);
+ }
+ return { type: COMMAND, value };
+ }
+ if (isKey(string)) {
+ const value = string.replace(KEY_PREFIX, "");
+ if (!value) {
+ throw Error("invalid flag");
+ }
+ return { type: KEY, value };
+ }
+ return { type: ARG, value: string };
+}
+
+/**
+ * returns a command Tree object for a set of tokens
+ *
+ *
+ * @param Array Tokens tokens
+ * An array of Token objects
+ *
+ * @returns Object Tree Object, with the following shape
+ * { command: String, args: Array of Strings }
+ */
+function parseCommand(tokens) {
+ let command = null;
+ const args = {};
+
+ for (let i = 0; i < tokens.length; i++) {
+ const token = tokens[i];
+ if (token.type === COMMAND) {
+ if (command) {
+ // we are throwing here because two commands have been passed and it is unclear
+ // what the user's intention was
+ throw Error("Invalid command");
+ }
+ command = token.value;
+ }
+
+ if (token.type === KEY) {
+ const nextTokenIndex = i + 1;
+ const nextToken = tokens[nextTokenIndex];
+ let values = args[token.value] || DEFAULT_VALUE;
+ if (nextToken && nextToken.type === ARG) {
+ const { value, offset } = collectString(
+ nextToken,
+ tokens,
+ nextTokenIndex
+ );
+ // in order for JSON.stringify to correctly output values, they must be correctly
+ // typed
+ // As per the old GCLI documentation, we can only have one value associated with a
+ // flag but multiple flags with the same name can exist and should be combined
+ // into and array. Here we are associating only the value on the right hand
+ // side if it is of type `arg` as a single value; the second case initializes
+ // an array, and the final case pushes a value to an existing array
+ const typedValue = getTypedValue(value);
+ if (values === DEFAULT_VALUE) {
+ values = typedValue;
+ } else if (!Array.isArray(values)) {
+ values = [values, typedValue];
+ } else {
+ values.push(typedValue);
+ }
+ // skip the next token since we have already consumed it
+ i = nextTokenIndex + offset;
+ }
+ args[token.value] = values;
+ }
+
+ // Since this has only been implemented for screenshot, we can only have one default
+ // value. Eventually we may have more default values. For now, ignore multiple
+ // unflagged args
+ const defaultFlag = COMMAND_DEFAULT_FLAG[command];
+ if (token.type === ARG && !args[defaultFlag]) {
+ const { value, offset } = collectString(token, tokens, i);
+ args[defaultFlag] = getTypedValue(value);
+ i = i + offset;
+ }
+ }
+ return { command, args };
+}
+
+const stringChars = ['"', "'", "`"];
+function isStringChar(testChar) {
+ return stringChars.includes(testChar);
+}
+
+function checkLastChar(string, testChar) {
+ const lastChar = string[string.length - 1];
+ return lastChar === testChar;
+}
+
+function hasUnescapedChar(value, char, rightOffset, leftOffset) {
+ const lastPos = value.length - 1;
+ const string = value.slice(rightOffset, lastPos - leftOffset);
+ const index = string.indexOf(char);
+ if (index === -1) {
+ return false;
+ }
+ const prevChar = index > 0 ? string[index - 1] : null;
+ // return false if the unexpected character is escaped, true if it is not
+ return prevChar !== "\\";
+}
+
+function collectString(token, tokens, index) {
+ const firstChar = token.value[0];
+ const isString = isStringChar(firstChar);
+ const UNESCAPED_CHAR_ERROR = segment =>
+ `String has unescaped \`${firstChar}\` in [${segment}...],` +
+ " may miss a space between arguments";
+ let value = token.value;
+
+ // the test value is not a string, or it is a string but a complete one
+ // i.e. `"test"`, as opposed to `"foo`. In either case, this we can return early
+ if (!isString || checkLastChar(value, firstChar)) {
+ return { value, offset: 0 };
+ }
+
+ if (hasUnescapedChar(value, firstChar, 1, 0)) {
+ throw Error(UNESCAPED_CHAR_ERROR(value));
+ }
+
+ let offset = null;
+ for (let i = index + 1; i <= tokens.length; i++) {
+ if (i === tokens.length) {
+ throw Error("String does not terminate");
+ }
+
+ const nextToken = tokens[i];
+ if (nextToken.type !== ARG) {
+ throw Error(`String does not terminate before flag "${nextToken.value}"`);
+ }
+
+ value = `${value} ${nextToken.value}`;
+
+ if (hasUnescapedChar(nextToken.value, firstChar, 0, 1)) {
+ throw Error(UNESCAPED_CHAR_ERROR(value));
+ }
+
+ if (checkLastChar(nextToken.value, firstChar)) {
+ offset = i - index;
+ break;
+ }
+ }
+ return { value, offset };
+}
+
+function isCommand(string) {
+ return COMMAND_PREFIX.test(string);
+}
+
+function isKey(string) {
+ return KEY_PREFIX.test(string);
+}
+
+function getTypedValue(value) {
+ if (!isNaN(value)) {
+ return Number(value);
+ }
+ if (value === "true" || value === "false") {
+ return Boolean(value);
+ }
+ if (isStringChar(value[0])) {
+ return value.slice(1, value.length - 1);
+ }
+ return value;
+}
+
+exports.formatCommand = formatCommand;
+exports.isCommand = isCommand;
+exports.validCommands = validCommands;
diff --git a/devtools/server/actors/webconsole/content-process-forward.js b/devtools/server/actors/webconsole/content-process-forward.js
new file mode 100644
index 0000000000..69720d51b3
--- /dev/null
+++ b/devtools/server/actors/webconsole/content-process-forward.js
@@ -0,0 +1,143 @@
+/* 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";
+
+const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
+
+ChromeUtils.defineModuleGetter(
+ this,
+ "E10SUtils",
+ "resource://gre/modules/E10SUtils.jsm"
+);
+
+/*
+ * The message manager has an upper limit on message sizes that it can
+ * reliably forward to the parent so we limit the size of console log event
+ * messages that we forward here. The web console is local and receives the
+ * full console message, but addons subscribed to console event messages
+ * in the parent receive the truncated version. Due to fragmentation,
+ * messages as small as 1MB have resulted in IPC allocation failures on
+ * 32-bit platforms. To limit IPC allocation sizes, console.log messages
+ * with arguments with total size > MSG_MGR_CONSOLE_MAX_SIZE (bytes) have
+ * their arguments completely truncated. MSG_MGR_CONSOLE_VAR_SIZE is an
+ * approximation of how much space (in bytes) a JS non-string variable will
+ * require in the manager's implementation. For strings, we use 2 bytes per
+ * char. The console message URI and function name are limited to
+ * MSG_MGR_CONSOLE_INFO_MAX characters. We don't attempt to calculate
+ * the exact amount of space the message manager implementation will require
+ * for a given message so this is imperfect.
+ */
+const MSG_MGR_CONSOLE_MAX_SIZE = 1024 * 1024; // 1MB
+const MSG_MGR_CONSOLE_VAR_SIZE = 8;
+const MSG_MGR_CONSOLE_INFO_MAX = 1024;
+
+function ContentProcessForward() {
+ Services.obs.addObserver(this, "console-api-log-event");
+ Services.obs.addObserver(this, "xpcom-shutdown");
+ Services.cpmm.addMessageListener(
+ "DevTools:StopForwardingContentProcessMessage",
+ this
+ );
+}
+ContentProcessForward.prototype = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIObserver",
+ "nsISupportsWeakReference",
+ ]),
+
+ receiveMessage(message) {
+ if (message.name == "DevTools:StopForwardingContentProcessMessage") {
+ this.uninit();
+ }
+ },
+
+ observe(subject, topic, data) {
+ switch (topic) {
+ case "console-api-log-event": {
+ const consoleMsg = subject.wrappedJSObject;
+
+ const msgData = {
+ ...consoleMsg,
+ arguments: [],
+ filename: consoleMsg.filename.substring(0, MSG_MGR_CONSOLE_INFO_MAX),
+ functionName:
+ consoleMsg.functionName &&
+ consoleMsg.functionName.substring(0, MSG_MGR_CONSOLE_INFO_MAX),
+ // Prevents cyclic object error when using msgData in sendAsyncMessage
+ wrappedJSObject: null,
+ };
+
+ // We can't send objects over the message manager, so we sanitize
+ // them out, replacing those arguments with "<unavailable>".
+ const unavailString = "<unavailable>";
+ const unavailStringLength = unavailString.length * 2; // 2-bytes per char
+
+ // When the sum of argument sizes reaches MSG_MGR_CONSOLE_MAX_SIZE,
+ // replace all arguments with "<truncated>".
+ let totalArgLength = 0;
+
+ // Walk through the arguments, checking the type and size.
+ for (let arg of consoleMsg.arguments) {
+ if (
+ (typeof arg == "object" || typeof arg == "function") &&
+ arg !== null
+ ) {
+ if (
+ Services.appinfo.remoteType === E10SUtils.EXTENSION_REMOTE_TYPE
+ ) {
+ // For OOP extensions: we want the developer to be able to see the
+ // logs in the Browser Console. When the Addon Toolbox will be more
+ // prominent we can revisit.
+ try {
+ // If the argument is clonable, then send it as-is. If
+ // cloning fails, fall back to the unavailable string.
+ arg = Cu.cloneInto(arg, {});
+ } catch (e) {
+ arg = unavailString;
+ }
+ } else {
+ arg = unavailString;
+ }
+ totalArgLength += unavailStringLength;
+ } else if (typeof arg == "string") {
+ totalArgLength += arg.length * 2; // 2-bytes per char
+ } else {
+ totalArgLength += MSG_MGR_CONSOLE_VAR_SIZE;
+ }
+
+ if (totalArgLength <= MSG_MGR_CONSOLE_MAX_SIZE) {
+ msgData.arguments.push(arg);
+ } else {
+ // arguments take up too much space
+ msgData.arguments = ["<truncated>"];
+ break;
+ }
+ }
+
+ Services.cpmm.sendAsyncMessage("Console:Log", msgData);
+ break;
+ }
+
+ case "xpcom-shutdown":
+ this.uninit();
+ break;
+ }
+ },
+
+ uninit() {
+ Services.obs.removeObserver(this, "console-api-log-event");
+ Services.obs.removeObserver(this, "xpcom-shutdown");
+ Services.cpmm.removeMessageListener(
+ "DevTools:StopForwardingContentProcessMessage",
+ this
+ );
+ },
+};
+
+// loadProcessScript loads in all processes, including the parent,
+// in which we don't need any forwarding
+if (Services.appinfo.processType == Services.appinfo.PROCESS_TYPE_CONTENT) {
+ new ContentProcessForward();
+}
diff --git a/devtools/server/actors/webconsole/eager-ecma-allowlist.js b/devtools/server/actors/webconsole/eager-ecma-allowlist.js
new file mode 100644
index 0000000000..a91cfd4807
--- /dev/null
+++ b/devtools/server/actors/webconsole/eager-ecma-allowlist.js
@@ -0,0 +1,158 @@
+/* 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/. */
+/* global BigInt */
+
+"use strict";
+
+function matchingProperties(obj, regexp) {
+ return Object.getOwnPropertyNames(obj)
+ .filter(n => regexp.test(n))
+ .map(n => obj[n])
+ .filter(v => typeof v == "function");
+}
+
+function allProperties(obj) {
+ return matchingProperties(obj, /./);
+}
+
+const TypedArray = Reflect.getPrototypeOf(Int8Array);
+
+module.exports = [
+ Array,
+ Array.from,
+ Array.isArray,
+ Array.of,
+ Array.prototype.concat,
+ Array.prototype.entries,
+ Array.prototype.every,
+ Array.prototype.filter,
+ Array.prototype.find,
+ Array.prototype.findIndex,
+ Array.prototype.flat,
+ Array.prototype.flatMap,
+ Array.prototype.forEach,
+ Array.prototype.includes,
+ Array.prototype.indexOf,
+ Array.prototype.join,
+ Array.prototype.keys,
+ Array.prototype.lastIndexOf,
+ Array.prototype.map,
+ Array.prototype.reduce,
+ Array.prototype.reduceRight,
+ Array.prototype.slice,
+ Array.prototype.some,
+ Array.prototype.values,
+ ArrayBuffer,
+ ArrayBuffer.isView,
+ ArrayBuffer.prototype.slice,
+ BigInt,
+ ...allProperties(BigInt),
+ Boolean,
+ DataView,
+ Date,
+ Date.now,
+ Date.parse,
+ Date.UTC,
+ ...matchingProperties(Date.prototype, /^get/),
+ ...matchingProperties(Date.prototype, /^to.*?String$/),
+ Error,
+ Function,
+ Function.prototype.apply,
+ Function.prototype.bind,
+ Function.prototype.call,
+ Function.prototype[Symbol.hasInstance],
+ Int8Array,
+ Uint8Array,
+ Uint8ClampedArray,
+ Int16Array,
+ Uint16Array,
+ Int32Array,
+ Uint32Array,
+ Float32Array,
+ Float64Array,
+ TypedArray.from,
+ TypedArray.of,
+ TypedArray.prototype.entries,
+ TypedArray.prototype.every,
+ TypedArray.prototype.filter,
+ TypedArray.prototype.find,
+ TypedArray.prototype.findIndex,
+ TypedArray.prototype.forEach,
+ TypedArray.prototype.includes,
+ TypedArray.prototype.indexOf,
+ TypedArray.prototype.join,
+ TypedArray.prototype.keys,
+ TypedArray.prototype.lastIndexOf,
+ TypedArray.prototype.map,
+ TypedArray.prototype.reduce,
+ TypedArray.prototype.reduceRight,
+ TypedArray.prototype.slice,
+ TypedArray.prototype.some,
+ TypedArray.prototype.subarray,
+ TypedArray.prototype.values,
+ ...allProperties(JSON),
+ Map,
+ Map.prototype.forEach,
+ Map.prototype.get,
+ Map.prototype.has,
+ Map.prototype.entries,
+ Map.prototype.keys,
+ Map.prototype.values,
+ ...allProperties(Math),
+ Number,
+ ...allProperties(Number),
+ ...allProperties(Number.prototype),
+ Object,
+ Object.create,
+ Object.keys,
+ Object.entries,
+ Object.getOwnPropertyDescriptor,
+ Object.getOwnPropertyDescriptors,
+ Object.getOwnPropertyNames,
+ Object.getOwnPropertySymbols,
+ Object.getPrototypeOf,
+ Object.is,
+ Object.isExtensible,
+ Object.isFrozen,
+ Object.isSealed,
+ Object.values,
+ Object.prototype.hasOwnProperty,
+ Object.prototype.isPrototypeOf,
+ Proxy,
+ Proxy.revocable,
+ Reflect.apply,
+ Reflect.construct,
+ Reflect.get,
+ Reflect.getOwnPropertyDescriptor,
+ Reflect.getPrototypeOf,
+ Reflect.has,
+ Reflect.isExtensible,
+ Reflect.ownKeys,
+ RegExp,
+ RegExp.prototype.exec,
+ RegExp.prototype.test,
+ Set,
+ Set.prototype.entries,
+ Set.prototype.forEach,
+ Set.prototype.has,
+ Set.prototype.values,
+ String,
+ ...allProperties(String),
+ ...allProperties(String.prototype),
+ Symbol,
+ Symbol.keyFor,
+ WeakMap,
+ WeakMap.prototype.get,
+ WeakMap.prototype.has,
+ WeakSet,
+ WeakSet.prototype.has,
+ decodeURI,
+ decodeURIComponent,
+ encodeURI,
+ encodeURIComponent,
+ escape,
+ isFinite,
+ isNaN,
+ unescape,
+];
diff --git a/devtools/server/actors/webconsole/eager-function-allowlist.js b/devtools/server/actors/webconsole/eager-function-allowlist.js
new file mode 100644
index 0000000000..87ef83d7f5
--- /dev/null
+++ b/devtools/server/actors/webconsole/eager-function-allowlist.js
@@ -0,0 +1,72 @@
+/* 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";
+
+const { CC, Cu } = require("chrome");
+
+const idlPureAllowlist = require("devtools/server/actors/webconsole/webidl-pure-allowlist");
+
+// TODO: Bug 1616013 - Move more of these to be part of the pure list.
+const customEagerFunctions = {
+ Document: [
+ ["prototype", "getSelection"],
+ ["prototype", "hasStorageAccess"],
+ ],
+ Range: [
+ ["prototype", "isPointInRange"],
+ ["prototype", "comparePoint"],
+ ["prototype", "intersectsNode"],
+
+ // These two functions aren't pure because they do trigger layout when
+ // they are called, but in the context of eager evaluation, that should be
+ // a totally fine thing to do.
+ ["prototype", "getClientRects"],
+ ["prototype", "getBoundingClientRect"],
+ ],
+ Selection: [
+ ["prototype", "getRangeAt"],
+ ["prototype", "containsNode"],
+ ],
+};
+
+const mergedFunctions = {};
+for (const [key, values] of Object.entries(idlPureAllowlist)) {
+ mergedFunctions[key] = [...values];
+}
+for (const [key, values] of Object.entries(customEagerFunctions)) {
+ if (!mergedFunctions[key]) {
+ mergedFunctions[key] = [];
+ }
+ mergedFunctions[key].push(...values);
+}
+
+const natives = [];
+if (CC && Cu) {
+ const sandbox = Cu.Sandbox(
+ CC("@mozilla.org/systemprincipal;1", "nsIPrincipal")(),
+ {
+ invisibleToDebugger: true,
+ wantGlobalProperties: Object.keys(mergedFunctions),
+ }
+ );
+
+ for (const iface of Object.keys(mergedFunctions)) {
+ for (const path of mergedFunctions[iface]) {
+ let value = sandbox;
+ for (const part of [iface, ...path]) {
+ value = value[part];
+ if (!value) {
+ break;
+ }
+ }
+
+ if (value) {
+ natives.push(value);
+ }
+ }
+ }
+}
+
+module.exports = natives;
diff --git a/devtools/server/actors/webconsole/eval-with-debugger.js b/devtools/server/actors/webconsole/eval-with-debugger.js
new file mode 100644
index 0000000000..e6d5c18403
--- /dev/null
+++ b/devtools/server/actors/webconsole/eval-with-debugger.js
@@ -0,0 +1,619 @@
+/* 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";
+
+const Debugger = require("Debugger");
+const DevToolsUtils = require("devtools/shared/DevToolsUtils");
+const Services = require("Services");
+
+loader.lazyRequireGetter(
+ this,
+ "Reflect",
+ "resource://gre/modules/reflect.jsm",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "formatCommand",
+ "devtools/server/actors/webconsole/commands",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "isCommand",
+ "devtools/server/actors/webconsole/commands",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "WebConsoleCommands",
+ "devtools/server/actors/webconsole/utils",
+ true
+);
+
+loader.lazyRequireGetter(
+ this,
+ "LongStringActor",
+ "devtools/server/actors/string",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "eagerEcmaAllowlist",
+ "devtools/server/actors/webconsole/eager-ecma-allowlist"
+);
+loader.lazyRequireGetter(
+ this,
+ "eagerFunctionAllowlist",
+ "devtools/server/actors/webconsole/eager-function-allowlist"
+);
+
+function isObject(value) {
+ return Object(value) === value;
+}
+
+/**
+ * Evaluates a string using the debugger API.
+ *
+ * To allow the variables view to update properties from the Web Console we
+ * provide the "selectedObjectActor" mechanism: the Web Console tells the
+ * ObjectActor ID for which it desires to evaluate an expression. The
+ * Debugger.Object pointed at by the actor ID is bound such that it is
+ * available during expression evaluation (executeInGlobalWithBindings()).
+ *
+ * Example:
+ * _self['foobar'] = 'test'
+ * where |_self| refers to the desired object.
+ *
+ * The |frameActor| property allows the Web Console client to provide the
+ * frame actor ID, such that the expression can be evaluated in the
+ * user-selected stack frame.
+ *
+ * For the above to work we need the debugger and the Web Console to share
+ * a connection, otherwise the Web Console actor will not find the frame
+ * actor.
+ *
+ * The Debugger.Frame comes from the jsdebugger's Debugger instance, which
+ * is different from the Web Console's Debugger instance. This means that
+ * for evaluation to work, we need to create a new instance for the Web
+ * Console Commands helpers - they need to be Debugger.Objects coming from the
+ * jsdebugger's Debugger instance.
+ *
+ * When |selectedObjectActor| is used objects can come from different iframes,
+ * from different domains. To avoid permission-related errors when objects
+ * come from a different window, we also determine the object's own global,
+ * such that evaluation happens in the context of that global. This means that
+ * evaluation will happen in the object's iframe, rather than the top level
+ * window.
+ *
+ * @param string string
+ * String to evaluate.
+ * @param object [options]
+ * Options for evaluation:
+ * - selectedObjectActor: the ObjectActor ID to use for evaluation.
+ * |evalWithBindings()| will be called with one additional binding:
+ * |_self| which will point to the Debugger.Object of the given
+ * ObjectActor. Executes with the top level window as the global.
+ * - frameActor: the FrameActor ID to use for evaluation. The given
+ * debugger frame is used for evaluation, instead of the global window.
+ * - selectedNodeActor: the NodeActor ID of the currently selected node
+ * in the Inspector (or null, if there is no selection). This is used
+ * for helper functions that make reference to the currently selected
+ * node, like $0.
+ * - innerWindowID: An optional window id to use instead of webConsole.evalWindow.
+ * This is used by function that need to evaluate in a different window for which
+ * we don't have a dedicated target (for example a non-remote iframe).
+ * - eager: Set to true if you want the evaluation to bail if it may have side effects.
+ * - url: the url to evaluate the script as. Defaults to "debugger eval code",
+ * or "debugger eager eval code" if eager is true.
+ * @return object
+ * An object that holds the following properties:
+ * - dbg: the debugger where the string was evaluated.
+ * - frame: (optional) the frame where the string was evaluated.
+ * - global: the Debugger.Object for the global where the string was evaluated in.
+ * - result: the result of the evaluation.
+ * - helperResult: any result coming from a Web Console commands
+ * function.
+ */
+exports.evalWithDebugger = function(string, options = {}, webConsole) {
+ if (isCommand(string.trim()) && options.eager) {
+ return {
+ result: null,
+ };
+ }
+
+ const evalString = getEvalInput(string);
+ const { frame, dbg } = getFrameDbg(options, webConsole);
+
+ const { dbgGlobal, bindSelf } = getDbgGlobal(options, dbg, webConsole);
+ const helpers = getHelpers(dbgGlobal, options, webConsole);
+ let { bindings, helperCache } = bindCommands(
+ isCommand(string),
+ dbgGlobal,
+ bindSelf,
+ frame,
+ helpers
+ );
+
+ if (options.bindings) {
+ bindings = { ...(bindings || {}), ...options.bindings };
+ }
+
+ // Ready to evaluate the string.
+ helpers.evalInput = string;
+ const evalOptions = {};
+
+ const urlOption =
+ options.url || (options.eager ? "debugger eager eval code" : null);
+ if (typeof urlOption === "string") {
+ evalOptions.url = urlOption;
+ }
+
+ if (typeof options.lineNumber === "number") {
+ evalOptions.lineNumber = options.lineNumber;
+ }
+
+ updateConsoleInputEvaluation(dbg, webConsole);
+
+ let noSideEffectDebugger = null;
+ if (options.eager) {
+ noSideEffectDebugger = makeSideeffectFreeDebugger();
+ }
+
+ let result;
+ try {
+ result = getEvalResult(
+ dbg,
+ evalString,
+ evalOptions,
+ bindings,
+ frame,
+ dbgGlobal,
+ noSideEffectDebugger
+ );
+ } finally {
+ // We need to be absolutely sure that the sideeffect-free debugger's
+ // debuggees are removed because otherwise we risk them terminating
+ // execution of later code in the case of unexpected exceptions.
+ if (noSideEffectDebugger) {
+ noSideEffectDebugger.removeAllDebuggees();
+ }
+ }
+
+ // Attempt to initialize any declarations found in the evaluated string
+ // since they may now be stuck in an "initializing" state due to the
+ // error. Already-initialized bindings will be ignored.
+ if (!frame && result && "throw" in result) {
+ parseErrorOutput(dbgGlobal, string);
+ }
+
+ const { helperResult } = helpers;
+
+ // Clean up helpers helpers and bindings
+ delete helpers.evalInput;
+ delete helpers.helperResult;
+ delete helpers.selectedNode;
+ cleanupBindings(bindings, helperCache);
+
+ return {
+ result,
+ helperResult,
+ dbg,
+ frame,
+ dbgGlobal,
+ };
+};
+
+function getEvalResult(
+ dbg,
+ string,
+ evalOptions,
+ bindings,
+ frame,
+ dbgGlobal,
+ noSideEffectDebugger
+) {
+ if (noSideEffectDebugger) {
+ // Bug 1637883 demonstrated an issue where dbgGlobal was somehow in the
+ // same compartment as the Debugger, meaning it could not be debugged
+ // and thus cannot handle eager evaluation. In that case we skip execution.
+ if (!noSideEffectDebugger.hasDebuggee(dbgGlobal.unsafeDereference())) {
+ return null;
+ }
+
+ // When a sideeffect-free debugger has been created, we need to eval
+ // in the context of that debugger in order for the side-effect tracking
+ // to apply.
+ frame = frame ? noSideEffectDebugger.adoptFrame(frame) : null;
+ dbgGlobal = noSideEffectDebugger.adoptDebuggeeValue(dbgGlobal);
+ if (bindings) {
+ bindings = Object.keys(bindings).reduce((acc, key) => {
+ acc[key] = noSideEffectDebugger.adoptDebuggeeValue(bindings[key]);
+ return acc;
+ }, {});
+ }
+ }
+
+ let result;
+ if (frame) {
+ result = frame.evalWithBindings(string, bindings, evalOptions);
+ } else {
+ result = dbgGlobal.executeInGlobalWithBindings(
+ string,
+ bindings,
+ evalOptions
+ );
+ }
+ if (noSideEffectDebugger && result) {
+ if ("return" in result) {
+ result.return = dbg.adoptDebuggeeValue(result.return);
+ }
+ if ("throw" in result) {
+ result.throw = dbg.adoptDebuggeeValue(result.throw);
+ }
+ }
+ return result;
+}
+
+function parseErrorOutput(dbgGlobal, string) {
+ // Reflect is not usable in workers, so return early to avoid logging an error
+ // to the console when loading it.
+ if (isWorker) {
+ return;
+ }
+
+ let ast;
+ // Parse errors will raise an exception. We can/should ignore the error
+ // since it's already being handled elsewhere and we are only interested
+ // in initializing bindings.
+ try {
+ ast = Reflect.parse(string);
+ } catch (ex) {
+ return;
+ }
+ for (const line of ast.body) {
+ // Only let and const declarations put bindings into an
+ // "initializing" state.
+ if (!(line.kind == "let" || line.kind == "const")) {
+ continue;
+ }
+
+ const identifiers = [];
+ for (const decl of line.declarations) {
+ switch (decl.id.type) {
+ case "Identifier":
+ // let foo = bar;
+ identifiers.push(decl.id.name);
+ break;
+ case "ArrayPattern":
+ // let [foo, bar] = [1, 2];
+ // let [foo=99, bar] = [1, 2];
+ for (const e of decl.id.elements) {
+ if (e.type == "Identifier") {
+ identifiers.push(e.name);
+ } else if (e.type == "AssignmentExpression") {
+ identifiers.push(e.left.name);
+ }
+ }
+ break;
+ case "ObjectPattern":
+ // let {bilbo, my} = {bilbo: "baggins", my: "precious"};
+ // let {blah: foo} = {blah: yabba()}
+ // let {blah: foo=99} = {blah: yabba()}
+ for (const prop of decl.id.properties) {
+ // key
+ if (prop.key.type == "Identifier") {
+ identifiers.push(prop.key.name);
+ }
+ // value
+ if (prop.value.type == "Identifier") {
+ identifiers.push(prop.value.name);
+ } else if (prop.value.type == "AssignmentExpression") {
+ identifiers.push(prop.value.left.name);
+ }
+ }
+ break;
+ }
+ }
+
+ for (const name of identifiers) {
+ dbgGlobal.forceLexicalInitializationByName(name);
+ }
+ }
+}
+
+function makeSideeffectFreeDebugger() {
+ // We ensure that the metadata for native functions is loaded before we
+ // initialize sideeffect-prevention because the data is lazy-loaded, and this
+ // logic can run inside of debuggee compartments because the
+ // "addAllGlobalsAsDebuggees" considers the vast majority of realms
+ // valid debuggees. Without this, eager-eval runs the risk of failing
+ // because building the list of valid native functions is itself a
+ // side-effectful operation because it needs to populate a
+ // module cache, among any number of other things.
+ ensureSideEffectFreeNatives();
+
+ // Note: It is critical for debuggee performance that we implement all of
+ // this debuggee tracking logic with a separate Debugger instance.
+ // Bug 1617666 arises otherwise if we set an onEnterFrame hook on the
+ // existing debugger object and then later clear it.
+ const dbg = new Debugger();
+ dbg.addAllGlobalsAsDebuggees();
+
+ const timeoutDuration = 100;
+ const endTime = Date.now() + timeoutDuration;
+ let count = 0;
+ function shouldCancel() {
+ // To keep the evaled code as quick as possible, we avoid querying the
+ // current time on ever single step and instead check every 100 steps
+ // as an arbitrary count that seemed to be "often enough".
+ return ++count % 100 === 0 && Date.now() > endTime;
+ }
+
+ const executedScripts = new Set();
+ const handler = {
+ hit: () => null,
+ };
+ dbg.onEnterFrame = frame => {
+ if (shouldCancel()) {
+ return null;
+ }
+ frame.onStep = () => {
+ if (shouldCancel()) {
+ return null;
+ }
+ return undefined;
+ };
+
+ const script = frame.script;
+
+ if (executedScripts.has(script)) {
+ return undefined;
+ }
+ executedScripts.add(script);
+
+ const offsets = script.getEffectfulOffsets();
+ for (const offset of offsets) {
+ script.setBreakpoint(offset, handler);
+ }
+
+ return undefined;
+ };
+
+ // The debugger only calls onNativeCall handlers on the debugger that is
+ // explicitly calling eval, so we need to add this hook on "dbg" even though
+ // the rest of our hooks work via "newDbg".
+ dbg.onNativeCall = (callee, reason) => {
+ try {
+ // Getters are never considered effectful, and setters are always effectful.
+ // Natives called normally are handled with an allowlist.
+ if (
+ reason == "get" ||
+ (reason == "call" && nativeHasNoSideEffects(callee))
+ ) {
+ // Returning undefined causes execution to continue normally.
+ return undefined;
+ }
+ } catch (err) {
+ DevToolsUtils.reportException(
+ "evalWithDebugger onNativeCall",
+ new Error("Unable to validate native function against allowlist")
+ );
+ }
+ // Returning null terminates the current evaluation.
+ return null;
+ };
+
+ return dbg;
+}
+
+// Native functions which are considered to be side effect free.
+let gSideEffectFreeNatives; // string => Array(Function)
+
+function ensureSideEffectFreeNatives() {
+ if (gSideEffectFreeNatives) {
+ return;
+ }
+
+ const natives = [
+ ...eagerEcmaAllowlist,
+
+ // Pull in all of the non-ECMAScript native functions that we want to
+ // allow as well.
+ ...eagerFunctionAllowlist,
+ ];
+
+ const map = new Map();
+ for (const n of natives) {
+ if (!map.has(n.name)) {
+ map.set(n.name, []);
+ }
+ map.get(n.name).push(n);
+ }
+
+ gSideEffectFreeNatives = map;
+}
+
+function nativeHasNoSideEffects(fn) {
+ if (fn.isBoundFunction) {
+ fn = fn.boundTargetFunction;
+ }
+
+ // Natives with certain names are always considered side effect free.
+ switch (fn.name) {
+ case "toString":
+ case "toLocaleString":
+ case "valueOf":
+ return true;
+ }
+
+ const natives = gSideEffectFreeNatives.get(fn.name);
+ return natives && natives.some(n => fn.isSameNative(n));
+}
+
+function updateConsoleInputEvaluation(dbg, webConsole) {
+ // Adopt webConsole._lastConsoleInputEvaluation value in the new debugger,
+ // to prevent "Debugger.Object belongs to a different Debugger" exceptions
+ // related to the $_ bindings if the debugger object is changed from the
+ // last evaluation.
+ if (webConsole._lastConsoleInputEvaluation) {
+ webConsole._lastConsoleInputEvaluation = dbg.adoptDebuggeeValue(
+ webConsole._lastConsoleInputEvaluation
+ );
+ }
+}
+
+function getEvalInput(string) {
+ const trimmedString = string.trim();
+ // The help function needs to be easy to guess, so we make the () optional.
+ if (trimmedString === "help" || trimmedString === "?") {
+ return "help()";
+ }
+ // we support Unix like syntax for commands if it is preceeded by `:`
+ if (isCommand(string)) {
+ try {
+ return formatCommand(string);
+ } catch (e) {
+ console.log(e);
+ return `throw "${e}"`;
+ }
+ }
+
+ // Add easter egg for console.mihai().
+ if (
+ trimmedString == "console.mihai()" ||
+ trimmedString == "console.mihai();"
+ ) {
+ return '"http://incompleteness.me/blog/2015/02/09/console-dot-mihai/"';
+ }
+ return string;
+}
+
+function getFrameDbg(options, webConsole) {
+ if (!options.frameActor) {
+ return { frame: null, dbg: webConsole.dbg };
+ }
+ // Find the Debugger.Frame of the given FrameActor.
+ const frameActor = webConsole.conn.getActor(options.frameActor);
+ if (frameActor) {
+ // If we've been given a frame actor in whose scope we should evaluate the
+ // expression, be sure to use that frame's Debugger (that is, the JavaScript
+ // debugger's Debugger) for the whole operation, not the console's Debugger.
+ // (One Debugger will treat a different Debugger's Debugger.Object instances
+ // as ordinary objects, not as references to be followed, so mixing
+ // debuggers causes strange behaviors.)
+ return { frame: frameActor.frame, dbg: frameActor.threadActor.dbg };
+ }
+ return DevToolsUtils.reportException(
+ "evalWithDebugger",
+ Error("The frame actor was not found: " + options.frameActor)
+ );
+}
+
+function getDbgGlobal(options, dbg, webConsole) {
+ let evalGlobal = webConsole.evalGlobal;
+
+ if (options.innerWindowID) {
+ const window = Services.wm.getCurrentInnerWindowWithId(
+ options.innerWindowID
+ );
+
+ if (window) {
+ evalGlobal = window;
+ }
+ }
+
+ const dbgGlobal = dbg.makeGlobalObjectReference(evalGlobal);
+
+ // If we have an object to bind to |_self|, create a Debugger.Object
+ // referring to that object, belonging to dbg.
+ if (!options.selectedObjectActor) {
+ return { bindSelf: null, dbgGlobal };
+ }
+
+ // For objects related to console messages, they will be registered under the Target Actor
+ // instead of the WebConsoleActor. That's because console messages are resources and all resources
+ // are emitted by the Target Actor.
+ const actor =
+ webConsole.getActorByID(options.selectedObjectActor) ||
+ webConsole.parentActor.getActorByID(options.selectedObjectActor);
+
+ if (!actor) {
+ return { bindSelf: null, dbgGlobal };
+ }
+
+ const jsVal = actor instanceof LongStringActor ? actor.str : actor.rawValue();
+ if (!isObject(jsVal)) {
+ return { bindSelf: jsVal, dbgGlobal };
+ }
+
+ // If we use the makeDebuggeeValue method of jsVal's own global, then
+ // we'll get a D.O that sees jsVal as viewed from its own compartment -
+ // that is, without wrappers. The evalWithBindings call will then wrap
+ // jsVal appropriately for the evaluation compartment.
+ const bindSelf = dbgGlobal.makeDebuggeeValue(jsVal);
+ return { bindSelf, dbgGlobal };
+}
+
+function getHelpers(dbgGlobal, options, webConsole) {
+ // Get the Web Console commands for the given debugger global.
+ const helpers = webConsole._getWebConsoleCommands(dbgGlobal);
+ if (options.selectedNodeActor) {
+ const actor = webConsole.conn.getActor(options.selectedNodeActor);
+ if (actor) {
+ helpers.selectedNode = actor.rawNode;
+ }
+ }
+
+ return helpers;
+}
+
+function cleanupBindings(bindings, helperCache) {
+ // Replaces bindings that were overwritten with commands saved in the helperCache
+ for (const [helperName, helper] of Object.entries(helperCache)) {
+ bindings[helperName] = helper;
+ }
+
+ if (bindings._self) {
+ delete bindings._self;
+ }
+}
+
+function bindCommands(isCmd, dbgGlobal, bindSelf, frame, helpers) {
+ const bindings = helpers.sandbox;
+ if (bindSelf) {
+ bindings._self = bindSelf;
+ }
+ // Check if the Debugger.Frame or Debugger.Object for the global include any of the
+ // helper function we set. We will not overwrite these functions with the Web Console
+ // commands.
+ const availableHelpers = [...WebConsoleCommands._originalCommands.keys()];
+
+ let helpersToDisable = [];
+ const helperCache = {};
+
+ // do not override command functions if we are using the command key `:`
+ // before the command string
+ if (!isCmd) {
+ if (frame) {
+ const env = frame.environment;
+ if (env) {
+ helpersToDisable = availableHelpers.filter(name => !!env.find(name));
+ }
+ } else {
+ helpersToDisable = availableHelpers.filter(
+ name => !!dbgGlobal.getOwnPropertyDescriptor(name)
+ );
+ }
+ // if we do not have the command key as a prefix, screenshot is disabled by default
+ helpersToDisable.push("screenshot");
+ }
+
+ for (const helper of helpersToDisable) {
+ helperCache[helper] = bindings[helper];
+ delete bindings[helper];
+ }
+ return { bindings, helperCache };
+}
diff --git a/devtools/server/actors/webconsole/listeners/console-api.js b/devtools/server/actors/webconsole/listeners/console-api.js
new file mode 100644
index 0000000000..59202556e2
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/console-api.js
@@ -0,0 +1,203 @@
+/* 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";
+
+const { Cc, Ci } = require("chrome");
+const { isWindowIncluded } = require("devtools/shared/layout/utils");
+const Services = require("Services");
+const ChromeUtils = require("ChromeUtils");
+const {
+ CONSOLE_WORKER_IDS,
+ WebConsoleUtils,
+} = require("devtools/server/actors/webconsole/utils");
+
+// The window.console API observer
+
+/**
+ * The window.console API observer. This allows the window.console API messages
+ * to be sent to the remote Web Console instance.
+ *
+ * @constructor
+ * @param nsIDOMWindow window
+ * Optional - the window object for which we are created. This is used
+ * for filtering out messages that belong to other windows.
+ * @param Function handler
+ * This function is invoked with one argument, the Console API message that comes
+ * from the observer service, whenever a relevant console API call is received.
+ * @param object filteringOptions
+ * Optional - The filteringOptions that this listener should listen to:
+ * - addonId: filter console messages based on the addonId.
+ */
+class ConsoleAPIListener {
+ constructor(window, handler, { addonId } = {}) {
+ this.window = window;
+ this.handler = handler;
+ this.addonId = addonId;
+ }
+
+ QueryInterface = ChromeUtils.generateQI([Ci.nsIObserver]);
+
+ /**
+ * The content window for which we listen to window.console API calls.
+ * @type nsIDOMWindow
+ */
+ window = null;
+
+ /**
+ * The function which is notified of window.console API calls. It is invoked with one
+ * argument: the console API call object that comes from the observer service.
+ *
+ * @type function
+ */
+ handler = null;
+
+ /**
+ * The addonId that we listen for. If not null then only messages from this
+ * console will be returned.
+ */
+ addonId = null;
+
+ /**
+ * Initialize the window.console API observer.
+ */
+ init() {
+ // Note that the observer is process-wide. We will filter the messages as
+ // needed, see CAL_observe().
+ Services.obs.addObserver(this, "console-api-log-event");
+ }
+
+ /**
+ * The console API message observer. When messages are received from the
+ * observer service we forward them to the remote Web Console instance.
+ *
+ * @param object message
+ * The message object receives from the observer service.
+ * @param string topic
+ * The message topic received from the observer service.
+ */
+ observe(message, topic) {
+ if (!this.handler) {
+ return;
+ }
+
+ // Here, wrappedJSObject is not a security wrapper but a property defined
+ // by the XPCOM component which allows us to unwrap the XPCOM interface and
+ // access the underlying JSObject.
+ const apiMessage = message.wrappedJSObject;
+
+ if (!this.isMessageRelevant(apiMessage)) {
+ return;
+ }
+
+ this.handler(apiMessage);
+ }
+
+ /**
+ * Given a message, return true if this window should show it and false
+ * if it should be ignored.
+ *
+ * @param message
+ * The message from the Storage Service
+ * @return bool
+ * Do we care about this message?
+ */
+ isMessageRelevant(message) {
+ const workerType = WebConsoleUtils.getWorkerType(message);
+
+ if (this.window && workerType === "ServiceWorker") {
+ // For messages from Service Workers, message.ID is the
+ // scope, which can be used to determine whether it's controlling
+ // a window.
+ const scope = message.ID;
+
+ if (!this.window.shouldReportForServiceWorkerScope(scope)) {
+ return false;
+ }
+ }
+
+ if (this.window && !workerType) {
+ const msgWindow = Services.wm.getCurrentInnerWindowWithId(
+ message.innerID
+ );
+ if (!msgWindow || !isWindowIncluded(this.window, msgWindow)) {
+ // Not the same window!
+ return false;
+ }
+ }
+
+ if (this.addonId) {
+ // ConsoleAPI.jsm messages contains a consoleID, (and it is currently
+ // used in Addon SDK add-ons), the standard 'console' object
+ // (which is used in regular webpages and in WebExtensions pages)
+ // contains the originAttributes of the source document principal.
+
+ // Filtering based on the originAttributes used by
+ // the Console API object.
+ if (message.addonId == this.addonId) {
+ return true;
+ }
+
+ // Filtering based on the old-style consoleID property used by
+ // the legacy Console JSM module.
+ if (message.consoleID && message.consoleID == `addon/${this.addonId}`) {
+ return true;
+ }
+
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Get the cached messages for the current inner window and its (i)frames.
+ *
+ * @param boolean [includePrivate=false]
+ * Tells if you want to also retrieve messages coming from private
+ * windows. Defaults to false.
+ * @return array
+ * The array of cached messages.
+ */
+ getCachedMessages(includePrivate = false) {
+ let messages = [];
+ const ConsoleAPIStorage = Cc[
+ "@mozilla.org/consoleAPI-storage;1"
+ ].getService(Ci.nsIConsoleAPIStorage);
+
+ // if !this.window, we're in a browser console. Retrieve all events
+ // for filtering based on privacy.
+ if (!this.window) {
+ messages = ConsoleAPIStorage.getEvents();
+ } else {
+ const ids = WebConsoleUtils.getInnerWindowIDsForFrames(this.window);
+ ids.forEach(id => {
+ messages = messages.concat(ConsoleAPIStorage.getEvents(id));
+ });
+ }
+
+ CONSOLE_WORKER_IDS.forEach(id => {
+ messages = messages.concat(ConsoleAPIStorage.getEvents(id));
+ });
+
+ messages = messages.filter(msg => {
+ return this.isMessageRelevant(msg);
+ });
+
+ if (includePrivate) {
+ return messages;
+ }
+
+ return messages.filter(m => !m.private);
+ }
+
+ /**
+ * Destroy the console API listener.
+ */
+ destroy() {
+ Services.obs.removeObserver(this, "console-api-log-event");
+ this.window = this.handler = null;
+ }
+}
+exports.ConsoleAPIListener = ConsoleAPIListener;
diff --git a/devtools/server/actors/webconsole/listeners/console-file-activity.js b/devtools/server/actors/webconsole/listeners/console-file-activity.js
new file mode 100644
index 0000000000..fa33fae3ed
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/console-file-activity.js
@@ -0,0 +1,129 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const ChromeUtils = require("ChromeUtils");
+
+/**
+ * A WebProgressListener that listens for file loads.
+ *
+ * @constructor
+ * @param object window
+ * The window for which we need to track file loads.
+ * @param object owner
+ * The listener owner which needs to implement:
+ * - onFileActivity(aFileURI)
+ */
+function ConsoleFileActivityListener(window, owner) {
+ this.window = window;
+ this.owner = owner;
+}
+exports.ConsoleFileActivityListener = ConsoleFileActivityListener;
+
+ConsoleFileActivityListener.prototype = {
+ /**
+ * Tells if the console progress listener is initialized or not.
+ * @private
+ * @type boolean
+ */
+ _initialized: false,
+
+ _webProgress: null,
+
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIWebProgressListener",
+ "nsISupportsWeakReference",
+ ]),
+
+ /**
+ * Initialize the ConsoleFileActivityListener.
+ * @private
+ */
+ _init: function() {
+ if (this._initialized) {
+ return;
+ }
+
+ this._webProgress = this.window.docShell.QueryInterface(Ci.nsIWebProgress);
+ this._webProgress.addProgressListener(
+ this,
+ Ci.nsIWebProgress.NOTIFY_STATE_ALL
+ );
+
+ this._initialized = true;
+ },
+
+ /**
+ * Start a monitor/tracker related to the current nsIWebProgressListener
+ * instance.
+ */
+ startMonitor: function() {
+ this._init();
+ },
+
+ /**
+ * Stop monitoring.
+ */
+ stopMonitor: function() {
+ this.destroy();
+ },
+
+ onStateChange: function(progress, request, state, status) {
+ if (!this.owner) {
+ return;
+ }
+
+ this._checkFileActivity(progress, request, state, status);
+ },
+
+ /**
+ * Check if there is any file load, given the arguments of
+ * nsIWebProgressListener.onStateChange. If the state change tells that a file
+ * URI has been loaded, then the remote Web Console instance is notified.
+ * @private
+ */
+ _checkFileActivity: function(progress, request, state, status) {
+ if (!(state & Ci.nsIWebProgressListener.STATE_START)) {
+ return;
+ }
+
+ let uri = null;
+ if (request instanceof Ci.imgIRequest) {
+ const imgIRequest = request.QueryInterface(Ci.imgIRequest);
+ uri = imgIRequest.URI;
+ } else if (request instanceof Ci.nsIChannel) {
+ const nsIChannel = request.QueryInterface(Ci.nsIChannel);
+ uri = nsIChannel.URI;
+ }
+
+ if (!uri || (!uri.schemeIs("file") && !uri.schemeIs("ftp"))) {
+ return;
+ }
+
+ this.owner.onFileActivity(uri.spec);
+ },
+
+ /**
+ * Destroy the ConsoleFileActivityListener.
+ */
+ destroy: function() {
+ if (!this._initialized) {
+ return;
+ }
+
+ this._initialized = false;
+
+ try {
+ this._webProgress.removeProgressListener(this);
+ } catch (ex) {
+ // This can throw during browser shutdown.
+ }
+
+ this._webProgress = null;
+ this.window = null;
+ this.owner = null;
+ },
+};
diff --git a/devtools/server/actors/webconsole/listeners/console-reflow.js b/devtools/server/actors/webconsole/listeners/console-reflow.js
new file mode 100644
index 0000000000..14f1f8c324
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/console-reflow.js
@@ -0,0 +1,93 @@
+/* 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";
+
+const { components } = require("chrome");
+const ChromeUtils = require("ChromeUtils");
+
+/**
+ * A ReflowObserver that listens for reflow events from the page.
+ * Implements nsIReflowObserver.
+ *
+ * @constructor
+ * @param object window
+ * The window for which we need to track reflow.
+ * @param object owner
+ * The listener owner which needs to implement:
+ * - onReflowActivity(reflowInfo)
+ */
+
+function ConsoleReflowListener(window, listener) {
+ this.docshell = window.docShell;
+ this.listener = listener;
+ this.docshell.addWeakReflowObserver(this);
+}
+
+exports.ConsoleReflowListener = ConsoleReflowListener;
+
+ConsoleReflowListener.prototype = {
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIReflowObserver",
+ "nsISupportsWeakReference",
+ ]),
+ docshell: null,
+ listener: null,
+
+ /**
+ * Forward reflow event to listener.
+ *
+ * @param DOMHighResTimeStamp start
+ * @param DOMHighResTimeStamp end
+ * @param boolean interruptible
+ */
+ sendReflow: function(start, end, interruptible) {
+ const frame = components.stack.caller.caller;
+
+ let filename = frame ? frame.filename : null;
+
+ if (filename) {
+ // Because filename could be of the form "xxx.js -> xxx.js -> xxx.js",
+ // we only take the last part.
+ filename = filename.split(" ").pop();
+ }
+
+ this.listener.onReflowActivity({
+ interruptible: interruptible,
+ start: start,
+ end: end,
+ sourceURL: filename,
+ sourceLine: frame ? frame.lineNumber : null,
+ functionName: frame ? frame.name : null,
+ });
+ },
+
+ /**
+ * On uninterruptible reflow
+ *
+ * @param DOMHighResTimeStamp start
+ * @param DOMHighResTimeStamp end
+ */
+ reflow: function(start, end) {
+ this.sendReflow(start, end, false);
+ },
+
+ /**
+ * On interruptible reflow
+ *
+ * @param DOMHighResTimeStamp start
+ * @param DOMHighResTimeStamp end
+ */
+ reflowInterruptible: function(start, end) {
+ this.sendReflow(start, end, true);
+ },
+
+ /**
+ * Unregister listener.
+ */
+ destroy: function() {
+ this.docshell.removeWeakReflowObserver(this);
+ this.listener = this.docshell = null;
+ },
+};
diff --git a/devtools/server/actors/webconsole/listeners/console-service.js b/devtools/server/actors/webconsole/listeners/console-service.js
new file mode 100644
index 0000000000..613a7cc7de
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/console-service.js
@@ -0,0 +1,176 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const { isWindowIncluded } = require("devtools/shared/layout/utils");
+const Services = require("Services");
+const ChromeUtils = require("ChromeUtils");
+const { WebConsoleUtils } = require("devtools/server/actors/webconsole/utils");
+
+// The page errors listener
+
+/**
+ * The nsIConsoleService listener. This is used to send all of the console
+ * messages (JavaScript, CSS and more) to the remote Web Console instance.
+ *
+ * @constructor
+ * @param nsIDOMWindow [window]
+ * Optional - the window object for which we are created. This is used
+ * for filtering out messages that belong to other windows.
+ * @param Function handler
+ * This function is invoked with one argument, the nsIConsoleMessage, whenever a
+ * relevant message is received.
+ */
+class ConsoleServiceListener {
+ constructor(window, handler) {
+ this.window = window;
+ this.handler = handler;
+ }
+
+ QueryInterface = ChromeUtils.generateQI([Ci.nsIConsoleListener]);
+
+ /**
+ * The content window for which we listen to page errors.
+ * @type nsIDOMWindow
+ */
+ window = null;
+
+ /**
+ * The function which is notified of messages from the console service.
+ * @type function
+ */
+ handler = null;
+
+ /**
+ * Initialize the nsIConsoleService listener.
+ */
+ init() {
+ Services.console.registerListener(this);
+ }
+
+ /**
+ * The nsIConsoleService observer. This method takes all the script error
+ * messages belonging to the current window and sends them to the remote Web
+ * Console instance.
+ *
+ * @param nsIConsoleMessage message
+ * The message object coming from the nsIConsoleService.
+ */
+ observe(message) {
+ if (!this.handler) {
+ return;
+ }
+
+ if (this.window) {
+ if (
+ !(message instanceof Ci.nsIScriptError) ||
+ !message.outerWindowID ||
+ !this.isCategoryAllowed(message.category)
+ ) {
+ return;
+ }
+
+ const errorWindow = Services.wm.getOuterWindowWithId(
+ message.outerWindowID
+ );
+ if (!errorWindow || !isWindowIncluded(this.window, errorWindow)) {
+ return;
+ }
+ }
+
+ // Don't display messages triggered by eager evaluation.
+ if (message.sourceName === "debugger eager eval code") {
+ return;
+ }
+ this.handler(message);
+ }
+
+ /**
+ * Check if the given message category is allowed to be tracked or not.
+ * We ignore chrome-originating errors as we only care about content.
+ *
+ * @param string category
+ * The message category you want to check.
+ * @return boolean
+ * True if the category is allowed to be logged, false otherwise.
+ */
+ isCategoryAllowed(category) {
+ if (!category) {
+ return false;
+ }
+
+ switch (category) {
+ case "XPConnect JavaScript":
+ case "component javascript":
+ case "chrome javascript":
+ case "chrome registration":
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Get the cached page errors for the current inner window and its (i)frames.
+ *
+ * @param boolean [includePrivate=false]
+ * Tells if you want to also retrieve messages coming from private
+ * windows. Defaults to false.
+ * @return array
+ * The array of cached messages. Each element is an nsIScriptError or
+ * an nsIConsoleMessage
+ */
+ getCachedMessages(includePrivate = false) {
+ const errors = Services.console.getMessageArray() || [];
+
+ // if !this.window, we're in a browser console. Still need to filter
+ // private messages.
+ if (!this.window) {
+ return errors.filter(error => {
+ if (error instanceof Ci.nsIScriptError) {
+ if (!includePrivate && error.isFromPrivateWindow) {
+ return false;
+ }
+ }
+
+ return true;
+ });
+ }
+
+ const ids = WebConsoleUtils.getInnerWindowIDsForFrames(this.window);
+
+ return errors.filter(error => {
+ if (error instanceof Ci.nsIScriptError) {
+ if (!includePrivate && error.isFromPrivateWindow) {
+ return false;
+ }
+ if (
+ ids &&
+ (!ids.includes(error.innerWindowID) ||
+ !this.isCategoryAllowed(error.category))
+ ) {
+ return false;
+ }
+ } else if (ids?.[0]) {
+ // If this is not an nsIScriptError and we need to do window-based
+ // filtering we skip this message.
+ return false;
+ }
+
+ return true;
+ });
+ }
+
+ /**
+ * Remove the nsIConsoleService listener.
+ */
+ destroy() {
+ Services.console.unregisterListener(this);
+ this.handler = this.window = null;
+ }
+}
+
+exports.ConsoleServiceListener = ConsoleServiceListener;
diff --git a/devtools/server/actors/webconsole/listeners/content-process.js b/devtools/server/actors/webconsole/listeners/content-process.js
new file mode 100644
index 0000000000..e096ad9bfb
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/content-process.js
@@ -0,0 +1,50 @@
+/* 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";
+
+const Services = require("Services");
+
+// Process script used to forward console calls from content processes to parent process
+const CONTENT_PROCESS_SCRIPT =
+ "resource://devtools/server/actors/webconsole/content-process-forward.js";
+
+/**
+ * Forward console message calls from content processes to the parent process.
+ * Used by non-multiprocess Browser Console and Browser Toolbox Console to see messages
+ * from all processes.
+ *
+ * @constructor
+ * @param Function handler
+ * This function is invoked with one argument, the message that was forwarded from
+ * the content process to the parent process.
+ */
+class ContentProcessListener {
+ constructor(handler) {
+ this.handler = handler;
+
+ Services.ppmm.addMessageListener("Console:Log", this);
+ Services.ppmm.loadProcessScript(CONTENT_PROCESS_SCRIPT, true);
+ }
+
+ receiveMessage(message) {
+ const logMsg = message.data;
+ logMsg.wrappedJSObject = logMsg;
+ this.handler(logMsg);
+ }
+
+ destroy() {
+ // Tell the content processes to stop listening and forwarding messages
+ Services.ppmm.broadcastAsyncMessage(
+ "DevTools:StopForwardingContentProcessMessage"
+ );
+
+ Services.ppmm.removeMessageListener("Console:Log", this);
+ Services.ppmm.removeDelayedProcessScript(CONTENT_PROCESS_SCRIPT);
+
+ this.handler = null;
+ }
+}
+
+exports.ContentProcessListener = ContentProcessListener;
diff --git a/devtools/server/actors/webconsole/listeners/document-events.js b/devtools/server/actors/webconsole/listeners/document-events.js
new file mode 100644
index 0000000000..9377d1e6e4
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/document-events.js
@@ -0,0 +1,78 @@
+/* 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";
+
+const EventEmitter = require("devtools/shared/event-emitter");
+
+/**
+ * Forward `DOMContentLoaded` and `load` events with precise timing
+ * of when events happened according to window.performance numbers.
+ *
+ * @constructor
+ * @param BrowsingContextTarget targetActor
+ */
+function DocumentEventsListener(targetActor) {
+ this.targetActor = targetActor;
+
+ EventEmitter.decorate(this);
+ this.onWindowReady = this.onWindowReady.bind(this);
+ this.onContentLoaded = this.onContentLoaded.bind(this);
+ this.onLoad = this.onLoad.bind(this);
+}
+
+exports.DocumentEventsListener = DocumentEventsListener;
+
+DocumentEventsListener.prototype = {
+ listen() {
+ EventEmitter.on(this.targetActor, "window-ready", this.onWindowReady);
+ this.onWindowReady({ window: this.targetActor.window, isTopLevel: true });
+ },
+
+ onWindowReady({ window, isTopLevel }) {
+ // Ignore iframes
+ if (!isTopLevel) {
+ return;
+ }
+
+ const time = window.performance.timing.navigationStart;
+ this.emit("dom-loading", time);
+
+ const { readyState } = window.document;
+ if (readyState != "interactive" && readyState != "complete") {
+ window.addEventListener("DOMContentLoaded", this.onContentLoaded, {
+ once: true,
+ });
+ } else {
+ this.onContentLoaded({ target: window.document });
+ }
+ if (readyState != "complete") {
+ window.addEventListener("load", this.onLoad, { once: true });
+ } else {
+ this.onLoad({ target: window.document });
+ }
+ },
+
+ onContentLoaded(event) {
+ // milliseconds since the UNIX epoch, when the parser finished its work
+ // on the main document, that is when its Document.readyState changes to
+ // 'interactive' and the corresponding readystatechange event is thrown
+ const window = event.target.defaultView;
+ const time = window.performance.timing.domInteractive;
+ this.emit("dom-interactive", time);
+ },
+
+ onLoad(event) {
+ // milliseconds since the UNIX epoch, when the parser finished its work
+ // on the main document, that is when its Document.readyState changes to
+ // 'complete' and the corresponding readystatechange event is thrown
+ const window = event.target.defaultView;
+ const time = window.performance.timing.domComplete;
+ this.emit("dom-complete", time);
+ },
+
+ destroy() {
+ this.listener = null;
+ },
+};
diff --git a/devtools/server/actors/webconsole/listeners/moz.build b/devtools/server/actors/webconsole/listeners/moz.build
new file mode 100644
index 0000000000..372818f6c9
--- /dev/null
+++ b/devtools/server/actors/webconsole/listeners/moz.build
@@ -0,0 +1,14 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "console-api.js",
+ "console-file-activity.js",
+ "console-reflow.js",
+ "console-service.js",
+ "content-process.js",
+ "document-events.js",
+)
diff --git a/devtools/server/actors/webconsole/message-manager-mock.js b/devtools/server/actors/webconsole/message-manager-mock.js
new file mode 100644
index 0000000000..900dfcb3d5
--- /dev/null
+++ b/devtools/server/actors/webconsole/message-manager-mock.js
@@ -0,0 +1,70 @@
+/* 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";
+
+/**
+ * Implements a fake MessageManager class that allows to use the message
+ * manager API within the same process. This implementation will forward
+ * messages within the same process.
+ *
+ * It helps having the same codepath for actors being evaluated in the same
+ * process *and* in a remote one.
+ */
+function MessageManagerMock() {
+ this._listeners = new Map();
+}
+MessageManagerMock.prototype = {
+ addMessageListener(name, listener) {
+ let listeners = this._listeners.get(name);
+ if (!listeners) {
+ listeners = [];
+ this._listeners.set(name, listeners);
+ }
+ if (!listeners.includes(listener)) {
+ listeners.push(listener);
+ }
+ },
+ removeMessageListener(name, listener) {
+ const listeners = this._listeners.get(name);
+ const idx = listeners.indexOf(listener);
+ listeners.splice(idx, 1);
+ },
+ sendAsyncMessage(name, data) {
+ this.other.internalSendAsyncMessage(name, data);
+ },
+ internalSendAsyncMessage(name, data) {
+ const listeners = this._listeners.get(name);
+ if (!listeners) {
+ return;
+ }
+ const message = {
+ target: this,
+ data,
+ };
+ for (const listener of listeners) {
+ if (
+ typeof listener === "object" &&
+ typeof listener.receiveMessage === "function"
+ ) {
+ listener.receiveMessage(message);
+ } else if (typeof listener === "function") {
+ listener(message);
+ }
+ }
+ },
+};
+
+/**
+ * Create two MessageManager mocks, connected to each others.
+ * Calling sendAsyncMessage on the first will dispatch messages on the second one,
+ * and the other way around
+ */
+exports.createMessageManagerMocks = function() {
+ const a = new MessageManagerMock();
+ const b = new MessageManagerMock();
+ a.other = b;
+ b.other = a;
+ return [a, b];
+};
diff --git a/devtools/server/actors/webconsole/moz.build b/devtools/server/actors/webconsole/moz.build
new file mode 100644
index 0000000000..9e1197710f
--- /dev/null
+++ b/devtools/server/actors/webconsole/moz.build
@@ -0,0 +1,22 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DIRS += [
+ "listeners",
+]
+
+DevToolsModules(
+ "commands.js",
+ "content-process-forward.js",
+ "eager-ecma-allowlist.js",
+ "eager-function-allowlist.js",
+ "eval-with-debugger.js",
+ "message-manager-mock.js",
+ "utils.js",
+ "webidl-deprecated-list.js",
+ "webidl-pure-allowlist.js",
+ "worker-listeners.js",
+)
diff --git a/devtools/server/actors/webconsole/utils.js b/devtools/server/actors/webconsole/utils.js
new file mode 100644
index 0000000000..6ddf74f695
--- /dev/null
+++ b/devtools/server/actors/webconsole/utils.js
@@ -0,0 +1,685 @@
+/* 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";
+
+const { Cu } = require("chrome");
+
+// Note that this is only used in WebConsoleCommands, see $0 and screenshot.
+if (!isWorker) {
+ loader.lazyRequireGetter(
+ this,
+ "captureScreenshot",
+ "devtools/server/actors/utils/capture-screenshot",
+ true
+ );
+}
+
+const CONSOLE_WORKER_IDS = (exports.CONSOLE_WORKER_IDS = [
+ "SharedWorker",
+ "ServiceWorker",
+ "Worker",
+]);
+
+var WebConsoleUtils = {
+ /**
+ * Given a message, return one of CONSOLE_WORKER_IDS if it matches
+ * one of those.
+ *
+ * @return string
+ */
+ getWorkerType: function(message) {
+ const id = message ? message.innerID : null;
+ return CONSOLE_WORKER_IDS[CONSOLE_WORKER_IDS.indexOf(id)] || null;
+ },
+
+ /**
+ * Clone an object.
+ *
+ * @param object object
+ * The object you want cloned.
+ * @param boolean recursive
+ * Tells if you want to dig deeper into the object, to clone
+ * recursively.
+ * @param function [filter]
+ * Optional, filter function, called for every property. Three
+ * arguments are passed: key, value and object. Return true if the
+ * property should be added to the cloned object. Return false to skip
+ * the property.
+ * @return object
+ * The cloned object.
+ */
+ cloneObject: function(object, recursive, filter) {
+ if (typeof object != "object") {
+ return object;
+ }
+
+ let temp;
+
+ if (Array.isArray(object)) {
+ temp = [];
+ object.forEach(function(value, index) {
+ if (!filter || filter(index, value, object)) {
+ temp.push(recursive ? WebConsoleUtils.cloneObject(value) : value);
+ }
+ });
+ } else {
+ temp = {};
+ for (const key in object) {
+ const value = object[key];
+ if (
+ object.hasOwnProperty(key) &&
+ (!filter || filter(key, value, object))
+ ) {
+ temp[key] = recursive ? WebConsoleUtils.cloneObject(value) : value;
+ }
+ }
+ }
+
+ return temp;
+ },
+
+ /**
+ * Gets the ID of the inner window of this DOM window.
+ *
+ * @param nsIDOMWindow window
+ * @return integer|null
+ * Inner ID for the given window, null if we can't access it.
+ */
+ getInnerWindowId: function(window) {
+ // Might throw with SecurityError: Permission denied to access property
+ // "windowGlobalChild" on cross-origin object.
+ try {
+ return window.windowGlobalChild.innerWindowId;
+ } catch (e) {
+ return null;
+ }
+ },
+
+ /**
+ * Recursively gather a list of inner window ids given a
+ * top level window.
+ *
+ * @param nsIDOMWindow window
+ * @return Array
+ * list of inner window ids.
+ */
+ getInnerWindowIDsForFrames: function(window) {
+ const innerWindowID = this.getInnerWindowId(window);
+ if (innerWindowID === null) {
+ return [];
+ }
+
+ let ids = [innerWindowID];
+
+ if (window.frames) {
+ for (let i = 0; i < window.frames.length; i++) {
+ const frame = window.frames[i];
+ ids = ids.concat(this.getInnerWindowIDsForFrames(frame));
+ }
+ }
+
+ return ids;
+ },
+
+ /**
+ * Create a grip for the given value. If the value is an object,
+ * an object wrapper will be created.
+ *
+ * @param mixed value
+ * The value you want to create a grip for, before sending it to the
+ * client.
+ * @param function objectWrapper
+ * If the value is an object then the objectWrapper function is
+ * invoked to give us an object grip. See this.getObjectGrip().
+ * @return mixed
+ * The value grip.
+ */
+ createValueGrip: function(value, objectWrapper) {
+ switch (typeof value) {
+ case "boolean":
+ return value;
+ case "string":
+ return objectWrapper(value);
+ case "number":
+ if (value === Infinity) {
+ return { type: "Infinity" };
+ } else if (value === -Infinity) {
+ return { type: "-Infinity" };
+ } else if (Number.isNaN(value)) {
+ return { type: "NaN" };
+ } else if (!value && 1 / value === -Infinity) {
+ return { type: "-0" };
+ }
+ return value;
+ case "undefined":
+ return { type: "undefined" };
+ case "object":
+ if (value === null) {
+ return { type: "null" };
+ }
+ // Fall through.
+ case "function":
+ return objectWrapper(value);
+ default:
+ console.error(
+ "Failed to provide a grip for value of " + typeof value + ": " + value
+ );
+ return null;
+ }
+ },
+
+ /**
+ * Remove any frames in a stack that are above a debugger-triggered evaluation
+ * and will correspond with devtools server code, which we never want to show
+ * to the user.
+ *
+ * @param array stack
+ * An array of frames, with the topmost first, and each of which has a
+ * 'filename' property.
+ * @return array
+ * An array of stack frames with any devtools server frames removed.
+ * The original array is not modified.
+ */
+ removeFramesAboveDebuggerEval(stack) {
+ const debuggerEvalFilename = "debugger eval code";
+
+ // Remove any frames for server code above the last debugger eval frame.
+ const evalIndex = stack.findIndex(({ filename }, idx, arr) => {
+ const nextFrame = arr[idx + 1];
+ return (
+ filename == debuggerEvalFilename &&
+ (!nextFrame || nextFrame.filename !== debuggerEvalFilename)
+ );
+ });
+ if (evalIndex != -1) {
+ return stack.slice(0, evalIndex + 1);
+ }
+
+ // In some cases (e.g. evaluated expression with SyntaxError), we might not have a
+ // "debugger eval code" frame but still have internal ones. If that's the case, we
+ // return null as the end user shouldn't see those frames.
+ if (
+ stack.some(
+ ({ filename }) =>
+ filename && filename.startsWith("resource://devtools/")
+ )
+ ) {
+ return null;
+ }
+
+ return stack;
+ },
+};
+
+exports.WebConsoleUtils = WebConsoleUtils;
+
+/**
+ * WebConsole commands manager.
+ *
+ * Defines a set of functions /variables ("commands") that are available from
+ * the Web Console but not from the web page.
+ *
+ */
+var WebConsoleCommands = {
+ _registeredCommands: new Map(),
+ _originalCommands: new Map(),
+
+ /**
+ * @private
+ * Reserved for built-in commands. To register a command from the code of an
+ * add-on, see WebConsoleCommands.register instead.
+ *
+ * @see WebConsoleCommands.register
+ */
+ _registerOriginal: function(name, command) {
+ this.register(name, command);
+ this._originalCommands.set(name, this.getCommand(name));
+ },
+
+ /**
+ * Register a new command.
+ * @param {string} name The command name (exemple: "$")
+ * @param {(function|object)} command The command to register.
+ * It can be a function so the command is a function (like "$()"),
+ * or it can also be a property descriptor to describe a getter / value (like
+ * "$0").
+ *
+ * The command function or the command getter are passed a owner object as
+ * their first parameter (see the example below).
+ *
+ * Note that setters don't work currently and "enumerable" and "configurable"
+ * are forced to true.
+ *
+ * @example
+ *
+ * WebConsoleCommands.register("$", function JSTH_$(owner, selector)
+ * {
+ * return owner.window.document.querySelector(selector);
+ * });
+ *
+ * WebConsoleCommands.register("$0", {
+ * get: function(owner) {
+ * return owner.makeDebuggeeValue(owner.selectedNode);
+ * }
+ * });
+ */
+ register: function(name, command) {
+ this._registeredCommands.set(name, command);
+ },
+
+ /**
+ * Unregister a command.
+ *
+ * If the command being unregister overrode a built-in command,
+ * the latter is restored.
+ *
+ * @param {string} name The name of the command
+ */
+ unregister: function(name) {
+ this._registeredCommands.delete(name);
+ if (this._originalCommands.has(name)) {
+ this.register(name, this._originalCommands.get(name));
+ }
+ },
+
+ /**
+ * Returns a command by its name.
+ *
+ * @param {string} name The name of the command.
+ *
+ * @return {(function|object)} The command.
+ */
+ getCommand: function(name) {
+ return this._registeredCommands.get(name);
+ },
+
+ /**
+ * Returns true if a command is registered with the given name.
+ *
+ * @param {string} name The name of the command.
+ *
+ * @return {boolean} True if the command is registered.
+ */
+ hasCommand: function(name) {
+ return this._registeredCommands.has(name);
+ },
+};
+
+exports.WebConsoleCommands = WebConsoleCommands;
+
+/*
+ * Built-in commands.
+ *
+ * A list of helper functions used by Firebug can be found here:
+ * http://getfirebug.com/wiki/index.php/Command_Line_API
+ */
+
+/**
+ * Find a node by ID.
+ *
+ * @param string id
+ * The ID of the element you want.
+ * @return Node or null
+ * The result of calling document.querySelector(selector).
+ */
+WebConsoleCommands._registerOriginal("$", function(owner, selector) {
+ try {
+ return owner.window.document.querySelector(selector);
+ } catch (err) {
+ // Throw an error like `err` but that belongs to `owner.window`.
+ throw new owner.window.DOMException(err.message, err.name);
+ }
+});
+
+/**
+ * Find the nodes matching a CSS selector.
+ *
+ * @param string selector
+ * A string that is passed to window.document.querySelectorAll.
+ * @return NodeList
+ * Returns the result of document.querySelectorAll(selector).
+ */
+WebConsoleCommands._registerOriginal("$$", function(owner, selector) {
+ let nodes;
+ try {
+ nodes = owner.window.document.querySelectorAll(selector);
+ } catch (err) {
+ // Throw an error like `err` but that belongs to `owner.window`.
+ throw new owner.window.DOMException(err.message, err.name);
+ }
+
+ // Calling owner.window.Array.from() doesn't work without accessing the
+ // wrappedJSObject, so just loop through the results instead.
+ const result = new owner.window.Array();
+ for (let i = 0; i < nodes.length; i++) {
+ result.push(nodes[i]);
+ }
+ return result;
+});
+
+/**
+ * Returns the result of the last console input evaluation
+ *
+ * @return object|undefined
+ * Returns last console evaluation or undefined
+ */
+WebConsoleCommands._registerOriginal("$_", {
+ get: function(owner) {
+ return owner.consoleActor.getLastConsoleInputEvaluation();
+ },
+});
+
+/**
+ * Runs an xPath query and returns all matched nodes.
+ *
+ * @param string xPath
+ * xPath search query to execute.
+ * @param [optional] Node context
+ * Context to run the xPath query on. Uses window.document if not set.
+ * @param [optional] string|number resultType
+ Specify the result type. Default value XPathResult.ANY_TYPE
+ * @return array of Node
+ */
+WebConsoleCommands._registerOriginal("$x", function(
+ owner,
+ xPath,
+ context,
+ resultType = owner.window.XPathResult.ANY_TYPE
+) {
+ const nodes = new owner.window.Array();
+ // Not waiving Xrays, since we want the original Document.evaluate function,
+ // instead of anything that's been redefined.
+ const doc = owner.window.document;
+ context = context || doc;
+ switch (resultType) {
+ case "number":
+ resultType = owner.window.XPathResult.NUMBER_TYPE;
+ break;
+
+ case "string":
+ resultType = owner.window.XPathResult.STRING_TYPE;
+ break;
+
+ case "bool":
+ resultType = owner.window.XPathResult.BOOLEAN_TYPE;
+ break;
+
+ case "node":
+ resultType = owner.window.XPathResult.FIRST_ORDERED_NODE_TYPE;
+ break;
+
+ case "nodes":
+ resultType = owner.window.XPathResult.UNORDERED_NODE_ITERATOR_TYPE;
+ break;
+ }
+ const results = doc.evaluate(xPath, context, null, resultType, null);
+ if (results.resultType === owner.window.XPathResult.NUMBER_TYPE) {
+ return results.numberValue;
+ }
+ if (results.resultType === owner.window.XPathResult.STRING_TYPE) {
+ return results.stringValue;
+ }
+ if (results.resultType === owner.window.XPathResult.BOOLEAN_TYPE) {
+ return results.booleanValue;
+ }
+ if (
+ results.resultType === owner.window.XPathResult.ANY_UNORDERED_NODE_TYPE ||
+ results.resultType === owner.window.XPathResult.FIRST_ORDERED_NODE_TYPE
+ ) {
+ return results.singleNodeValue;
+ }
+ if (
+ results.resultType ===
+ owner.window.XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE ||
+ results.resultType === owner.window.XPathResult.ORDERED_NODE_SNAPSHOT_TYPE
+ ) {
+ for (let i = 0; i < results.snapshotLength; i++) {
+ nodes.push(results.snapshotItem(i));
+ }
+ return nodes;
+ }
+
+ let node;
+ while ((node = results.iterateNext())) {
+ nodes.push(node);
+ }
+
+ return nodes;
+});
+
+/**
+ * Returns the currently selected object in the highlighter.
+ *
+ * @return Object representing the current selection in the
+ * Inspector, or null if no selection exists.
+ */
+WebConsoleCommands._registerOriginal("$0", {
+ get: function(owner) {
+ return owner.makeDebuggeeValue(owner.selectedNode);
+ },
+});
+
+/**
+ * Clears the output of the WebConsole.
+ */
+WebConsoleCommands._registerOriginal("clear", function(owner) {
+ owner.helperResult = {
+ type: "clearOutput",
+ };
+});
+
+/**
+ * Clears the input history of the WebConsole.
+ */
+WebConsoleCommands._registerOriginal("clearHistory", function(owner) {
+ owner.helperResult = {
+ type: "clearHistory",
+ };
+});
+
+/**
+ * Returns the result of Object.keys(object).
+ *
+ * @param object object
+ * Object to return the property names from.
+ * @return array of strings
+ */
+WebConsoleCommands._registerOriginal("keys", function(owner, object) {
+ // Need to waive Xrays so we can iterate functions and accessor properties
+ return Cu.cloneInto(Object.keys(Cu.waiveXrays(object)), owner.window);
+});
+
+/**
+ * Returns the values of all properties on object.
+ *
+ * @param object object
+ * Object to display the values from.
+ * @return array of string
+ */
+WebConsoleCommands._registerOriginal("values", function(owner, object) {
+ const values = [];
+ // Need to waive Xrays so we can iterate functions and accessor properties
+ const waived = Cu.waiveXrays(object);
+ const names = Object.getOwnPropertyNames(waived);
+
+ for (const name of names) {
+ values.push(waived[name]);
+ }
+
+ return Cu.cloneInto(values, owner.window);
+});
+
+/**
+ * Opens a help window in MDN.
+ */
+WebConsoleCommands._registerOriginal("help", function(owner) {
+ owner.helperResult = { type: "help" };
+});
+
+/**
+ * Inspects the passed object. This is done by opening the PropertyPanel.
+ *
+ * @param object object
+ * Object to inspect.
+ */
+WebConsoleCommands._registerOriginal("inspect", function(
+ owner,
+ object,
+ forceExpandInConsole = false
+) {
+ const dbgObj = owner.preprocessDebuggerObject(
+ owner.makeDebuggeeValue(object)
+ );
+
+ const grip = owner.createValueGrip(dbgObj);
+ owner.helperResult = {
+ type: "inspectObject",
+ input: owner.evalInput,
+ object: grip,
+ forceExpandInConsole,
+ };
+});
+
+/**
+ * Copy the String representation of a value to the clipboard.
+ *
+ * @param any value
+ * A value you want to copy as a string.
+ * @return void
+ */
+WebConsoleCommands._registerOriginal("copy", function(owner, value) {
+ let payload;
+ try {
+ if (Element.isInstance(value)) {
+ payload = value.outerHTML;
+ } else if (typeof value == "string") {
+ payload = value;
+ } else {
+ payload = JSON.stringify(value, null, " ");
+ }
+ } catch (ex) {
+ payload = "/* " + ex + " */";
+ }
+ owner.helperResult = {
+ type: "copyValueToClipboard",
+ value: payload,
+ };
+});
+
+/**
+ * Take a screenshot of a page.
+ *
+ * @param object args
+ * The arguments to be passed to the screenshot
+ * @return void
+ */
+WebConsoleCommands._registerOriginal("screenshot", function(owner, args = {}) {
+ owner.helperResult = (async () => {
+ // creates data for saving the screenshot
+ // help is handled on the client side
+ const value = await captureScreenshot(args, owner.window.document);
+ return {
+ type: "screenshotOutput",
+ value,
+ // pass args through to the client, so that the client can take care of copying
+ // and saving the screenshot data on the client machine instead of on the
+ // remote machine
+ args,
+ };
+ })();
+});
+
+/**
+ * Block specific resource from loading
+ *
+ * @param object args
+ * an object with key "url", i.e. a filter
+ *
+ * @return void
+ */
+WebConsoleCommands._registerOriginal("block", function(owner, args = {}) {
+ if (!args.url) {
+ owner.helperResult = {
+ type: "error",
+ message: "webconsole.messages.commands.blockArgMissing",
+ };
+ return;
+ }
+
+ owner.helperResult = (async () => {
+ await owner.consoleActor.blockRequest(args);
+
+ return {
+ type: "blockURL",
+ args,
+ };
+ })();
+});
+
+/*
+ * Unblock a blocked a resource
+ *
+ * @param object filter
+ * an object with key "url", i.e. a filter
+ *
+ * @return void
+ */
+WebConsoleCommands._registerOriginal("unblock", function(owner, args = {}) {
+ if (!args.url) {
+ owner.helperResult = {
+ type: "error",
+ message: "webconsole.messages.commands.blockArgMissing",
+ };
+ return;
+ }
+
+ owner.helperResult = (async () => {
+ await owner.consoleActor.unblockRequest(args);
+
+ return {
+ type: "unblockURL",
+ args,
+ };
+ })();
+});
+
+/**
+ * (Internal only) Add the bindings to |owner.sandbox|.
+ * This is intended to be used by the WebConsole actor only.
+ *
+ * @param object owner
+ * The owning object.
+ */
+function addWebConsoleCommands(owner) {
+ // Not supporting extra commands in workers yet. This should be possible to
+ // add one by one as long as they don't require jsm, Cu, etc.
+ const commands = isWorker ? [] : WebConsoleCommands._registeredCommands;
+ if (!owner) {
+ throw new Error("The owner is required");
+ }
+ for (const [name, command] of commands) {
+ if (typeof command === "function") {
+ owner.sandbox[name] = command.bind(undefined, owner);
+ } else if (typeof command === "object") {
+ const clone = Object.assign({}, command, {
+ // We force the enumerability and the configurability (so the
+ // WebConsoleActor can reconfigure the property).
+ enumerable: true,
+ configurable: true,
+ });
+
+ if (typeof command.get === "function") {
+ clone.get = command.get.bind(undefined, owner);
+ }
+ if (typeof command.set === "function") {
+ clone.set = command.set.bind(undefined, owner);
+ }
+
+ Object.defineProperty(owner.sandbox, name, clone);
+ }
+ }
+}
+
+exports.addWebConsoleCommands = addWebConsoleCommands;
diff --git a/devtools/server/actors/webconsole/webidl-deprecated-list.js b/devtools/server/actors/webconsole/webidl-deprecated-list.js
new file mode 100644
index 0000000000..cb4b811bc1
--- /dev/null
+++ b/devtools/server/actors/webconsole/webidl-deprecated-list.js
@@ -0,0 +1,43 @@
+/* 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/. */
+
+// This file is automatically generated by the GenerateDataFromWebIdls.py
+// script. Do not modify it manually.
+"use strict";
+
+module.exports = {
+ CanvasRenderingContext2D: [["prototype", "mozImageSmoothingEnabled"]],
+ Document: [
+ ["prototype", "onmozfullscreenchange"],
+ ["prototype", "onmozfullscreenerror"],
+ ],
+ Element: [["prototype", "mozRequestFullScreen"]],
+ HTMLElement: [
+ ["prototype", "onmozfullscreenchange"],
+ ["prototype", "onmozfullscreenerror"],
+ ],
+ ImageBitmapRenderingContext: [["prototype", "transferImageBitmap"]],
+ MathMLElement: [
+ ["prototype", "onmozfullscreenchange"],
+ ["prototype", "onmozfullscreenerror"],
+ ],
+ MouseEvent: [["prototype", "mozPressure"]],
+ Navigator: [["prototype", "mozGetUserMedia"]],
+ RTCPeerConnection: [
+ ["prototype", "getLocalStreams"],
+ ["prototype", "getRemoteStreams"],
+ ],
+ SVGElement: [
+ ["prototype", "onmozfullscreenchange"],
+ ["prototype", "onmozfullscreenerror"],
+ ],
+ Window: [
+ ["prototype", "onmozfullscreenchange"],
+ ["prototype", "onmozfullscreenerror"],
+ ],
+ XULElement: [
+ ["prototype", "onmozfullscreenchange"],
+ ["prototype", "onmozfullscreenerror"],
+ ],
+};
diff --git a/devtools/server/actors/webconsole/webidl-pure-allowlist.js b/devtools/server/actors/webconsole/webidl-pure-allowlist.js
new file mode 100644
index 0000000000..911dbfda85
--- /dev/null
+++ b/devtools/server/actors/webconsole/webidl-pure-allowlist.js
@@ -0,0 +1,72 @@
+/* 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/. */
+
+// This file is automatically generated by the GenerateDataFromWebIdls.py
+// script. Do not modify it manually.
+"use strict";
+
+module.exports = {
+ DOMTokenList: [
+ ["prototype", "item"],
+ ["prototype", "contains"],
+ ],
+ Document: [
+ ["prototype", "getElementsByTagName"],
+ ["prototype", "getElementsByTagNameNS"],
+ ["prototype", "getElementsByClassName"],
+ ["prototype", "getElementById"],
+ ["prototype", "getElementsByName"],
+ ["prototype", "querySelector"],
+ ["prototype", "querySelectorAll"],
+ ["prototype", "createNSResolver"],
+ ],
+ Element: [
+ ["prototype", "getAttributeNames"],
+ ["prototype", "getAttribute"],
+ ["prototype", "getAttributeNS"],
+ ["prototype", "hasAttribute"],
+ ["prototype", "hasAttributeNS"],
+ ["prototype", "hasAttributes"],
+ ["prototype", "closest"],
+ ["prototype", "matches"],
+ ["prototype", "webkitMatchesSelector"],
+ ["prototype", "getElementsByTagName"],
+ ["prototype", "getElementsByTagNameNS"],
+ ["prototype", "getElementsByClassName"],
+ ["prototype", "mozMatchesSelector"],
+ ["prototype", "querySelector"],
+ ["prototype", "querySelectorAll"],
+ ["prototype", "getAsFlexContainer"],
+ ["prototype", "getGridFragments"],
+ ["prototype", "hasGridFragments"],
+ ["prototype", "getElementsWithGrid"],
+ ],
+ FormData: [
+ ["prototype", "entries"],
+ ["prototype", "keys"],
+ ["prototype", "values"],
+ ],
+ Headers: [
+ ["prototype", "entries"],
+ ["prototype", "keys"],
+ ["prototype", "values"],
+ ],
+ Node: [
+ ["prototype", "getRootNode"],
+ ["prototype", "hasChildNodes"],
+ ["prototype", "isSameNode"],
+ ["prototype", "isEqualNode"],
+ ["prototype", "compareDocumentPosition"],
+ ["prototype", "contains"],
+ ["prototype", "lookupPrefix"],
+ ["prototype", "lookupNamespaceURI"],
+ ["prototype", "isDefaultNamespace"],
+ ],
+ Performance: [["prototype", "now"]],
+ URLSearchParams: [
+ ["prototype", "entries"],
+ ["prototype", "keys"],
+ ["prototype", "values"],
+ ],
+};
diff --git a/devtools/server/actors/webconsole/worker-listeners.js b/devtools/server/actors/webconsole/worker-listeners.js
new file mode 100644
index 0000000000..6861c6da62
--- /dev/null
+++ b/devtools/server/actors/webconsole/worker-listeners.js
@@ -0,0 +1,35 @@
+/* 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/. */
+
+/* global setConsoleEventHandler, retrieveConsoleEvents */
+
+"use strict";
+
+// This file is loaded on the server side for worker debugging.
+// Since the server is running in the worker thread, it doesn't
+// have access to Services / Components but the listeners defined here
+// are imported by webconsole-utils and used for the webconsole actor.
+class ConsoleAPIListener {
+ constructor(window, listener, consoleID) {
+ this.window = window;
+ this.listener = listener;
+ this.consoleID = consoleID;
+ this.observe = this.observe.bind(this);
+ }
+
+ init() {
+ setConsoleEventHandler(this.observe);
+ }
+ destroy() {
+ setConsoleEventHandler(null);
+ }
+ observe(message) {
+ this.listener(message.wrappedJSObject);
+ }
+ getCachedMessages() {
+ return retrieveConsoleEvents();
+ }
+}
+
+exports.ConsoleAPIListener = ConsoleAPIListener;
diff --git a/devtools/server/actors/worker/moz.build b/devtools/server/actors/worker/moz.build
new file mode 100644
index 0000000000..4c9023879b
--- /dev/null
+++ b/devtools/server/actors/worker/moz.build
@@ -0,0 +1,14 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DevToolsModules(
+ "push-subscription.js",
+ "service-worker-process.js",
+ "service-worker-registration-list.js",
+ "service-worker-registration.js",
+ "service-worker.js",
+ "worker-descriptor-actor-list.js",
+)
diff --git a/devtools/server/actors/worker/push-subscription.js b/devtools/server/actors/worker/push-subscription.js
new file mode 100644
index 0000000000..d2fa904383
--- /dev/null
+++ b/devtools/server/actors/worker/push-subscription.js
@@ -0,0 +1,41 @@
+/* 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";
+
+const protocol = require("devtools/shared/protocol");
+const {
+ pushSubscriptionSpec,
+} = require("devtools/shared/specs/worker/push-subscription");
+
+const PushSubscriptionActor = protocol.ActorClassWithSpec(
+ pushSubscriptionSpec,
+ {
+ initialize(conn, subscription) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this._subscription = subscription;
+ },
+
+ form() {
+ const subscription = this._subscription;
+
+ // Note: subscription.pushCount & subscription.lastPush are no longer
+ // returned here because the corresponding getters throw on GeckoView.
+ // Since they were not used in DevTools they were removed from the
+ // actor in Bug 1637687. If they are reintroduced, make sure to provide
+ // meaningful fallback values when debugging a GeckoView runtime.
+ return {
+ actor: this.actorID,
+ endpoint: subscription.endpoint,
+ quota: subscription.quota,
+ };
+ },
+
+ destroy() {
+ this._subscription = null;
+ protocol.Actor.prototype.destroy.call(this);
+ },
+ }
+);
+exports.PushSubscriptionActor = PushSubscriptionActor;
diff --git a/devtools/server/actors/worker/service-worker-process.js b/devtools/server/actors/worker/service-worker-process.js
new file mode 100644
index 0000000000..8d492ab5cd
--- /dev/null
+++ b/devtools/server/actors/worker/service-worker-process.js
@@ -0,0 +1,41 @@
+/* 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/. */
+
+/* global addMessageListener */
+
+"use strict";
+
+/*
+ * Process script used to control service workers via a DevTools actor.
+ * Loaded into content processes by the service worker actors.
+ */
+
+const swm = Cc["@mozilla.org/serviceworkers/manager;1"].getService(
+ Ci.nsIServiceWorkerManager
+);
+
+addMessageListener("serviceWorkerRegistration:start", message => {
+ const { data } = message;
+ const array = swm.getAllRegistrations();
+
+ // Find the service worker registration with the desired scope.
+ for (let i = 0; i < array.length; i++) {
+ const registration = array.queryElementAt(
+ i,
+ Ci.nsIServiceWorkerRegistrationInfo
+ );
+ // XXX: In some rare cases, `registration.activeWorker` can be null for a
+ // brief moment (e.g. while the service worker is first installing, or if
+ // there was an unhandled exception during install that will cause the
+ // registration to be removed). We can't do much about it here, simply
+ // ignore these cases.
+ if (registration.scope === data.scope && registration.activeWorker) {
+ // Briefly attaching a debugger to the active service worker will cause
+ // it to start running.
+ registration.activeWorker.attachDebugger();
+ registration.activeWorker.detachDebugger();
+ return;
+ }
+ }
+});
diff --git a/devtools/server/actors/worker/service-worker-registration-list.js b/devtools/server/actors/worker/service-worker-registration-list.js
new file mode 100644
index 0000000000..e0b6939a90
--- /dev/null
+++ b/devtools/server/actors/worker/service-worker-registration-list.js
@@ -0,0 +1,113 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
+loader.lazyRequireGetter(
+ this,
+ "ServiceWorkerRegistrationActor",
+ "devtools/server/actors/worker/service-worker-registration",
+ true
+);
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "swm",
+ "@mozilla.org/serviceworkers/manager;1",
+ "nsIServiceWorkerManager"
+);
+
+function ServiceWorkerRegistrationActorList(conn) {
+ this._conn = conn;
+ this._actors = new Map();
+ this._onListChanged = null;
+ this._mustNotify = false;
+ this.onRegister = this.onRegister.bind(this);
+ this.onUnregister = this.onUnregister.bind(this);
+}
+
+ServiceWorkerRegistrationActorList.prototype = {
+ getList() {
+ // Create a set of registrations.
+ const registrations = new Set();
+ const array = swm.getAllRegistrations();
+ for (let index = 0; index < array.length; ++index) {
+ registrations.add(
+ array.queryElementAt(index, Ci.nsIServiceWorkerRegistrationInfo)
+ );
+ }
+
+ // Delete each actor for which we don't have a registration.
+ for (const [registration] of this._actors) {
+ if (!registrations.has(registration)) {
+ this._actors.delete(registration);
+ }
+ }
+
+ // Create an actor for each registration for which we don't have one.
+ for (const registration of registrations) {
+ if (!this._actors.has(registration)) {
+ this._actors.set(
+ registration,
+ new ServiceWorkerRegistrationActor(this._conn, registration)
+ );
+ }
+ }
+
+ if (!this._mustNotify) {
+ if (this._onListChanged !== null) {
+ swm.addListener(this);
+ }
+ this._mustNotify = true;
+ }
+
+ const actors = [];
+ for (const [, actor] of this._actors) {
+ actors.push(actor);
+ }
+
+ return Promise.resolve(actors);
+ },
+
+ get onListchanged() {
+ return this._onListchanged;
+ },
+
+ set onListChanged(onListChanged) {
+ if (typeof onListChanged !== "function" && onListChanged !== null) {
+ throw new Error("onListChanged must be either a function or null.");
+ }
+
+ if (this._mustNotify) {
+ if (this._onListChanged === null && onListChanged !== null) {
+ swm.addListener(this);
+ }
+ if (this._onListChanged !== null && onListChanged === null) {
+ swm.removeListener(this);
+ }
+ }
+ this._onListChanged = onListChanged;
+ },
+
+ _notifyListChanged() {
+ this._onListChanged();
+
+ if (this._onListChanged !== null) {
+ swm.removeListener(this);
+ }
+ this._mustNotify = false;
+ },
+
+ onRegister(registration) {
+ this._notifyListChanged();
+ },
+
+ onUnregister(registration) {
+ this._notifyListChanged();
+ },
+};
+
+exports.ServiceWorkerRegistrationActorList = ServiceWorkerRegistrationActorList;
diff --git a/devtools/server/actors/worker/service-worker-registration.js b/devtools/server/actors/worker/service-worker-registration.js
new file mode 100644
index 0000000000..bb6361f94b
--- /dev/null
+++ b/devtools/server/actors/worker/service-worker-registration.js
@@ -0,0 +1,335 @@
+/* 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";
+
+const ChromeUtils = require("ChromeUtils");
+const Services = require("Services");
+const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
+const protocol = require("devtools/shared/protocol");
+const {
+ serviceWorkerRegistrationSpec,
+} = require("devtools/shared/specs/worker/service-worker-registration");
+const {
+ PushSubscriptionActor,
+} = require("devtools/server/actors/worker/push-subscription");
+const {
+ ServiceWorkerActor,
+} = require("devtools/server/actors/worker/service-worker");
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "swm",
+ "@mozilla.org/serviceworkers/manager;1",
+ "nsIServiceWorkerManager"
+);
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "PushService",
+ "@mozilla.org/push/Service;1",
+ "nsIPushService"
+);
+
+// Lazily load the service-worker-process.js process script only once.
+let _serviceWorkerProcessScriptLoaded = false;
+
+const ServiceWorkerRegistrationActor = protocol.ActorClassWithSpec(
+ serviceWorkerRegistrationSpec,
+ {
+ /**
+ * Create the ServiceWorkerRegistrationActor
+ * @param DevToolsServerConnection conn
+ * The server connection.
+ * @param ServiceWorkerRegistrationInfo registration
+ * The registration's information.
+ */
+ initialize(conn, registration) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this._conn = conn;
+ this._registration = registration;
+ this._pushSubscriptionActor = null;
+
+ // A flag to know if preventShutdown has been called and we should
+ // try to allow the shutdown of the SW when the actor is destroyed
+ this._preventedShutdown = false;
+
+ this._registration.addListener(this);
+
+ this._createServiceWorkerActors();
+
+ Services.obs.addObserver(this, PushService.subscriptionModifiedTopic);
+ },
+
+ onChange() {
+ this._destroyServiceWorkerActors();
+ this._createServiceWorkerActors();
+ this.emit("registration-changed");
+ },
+
+ form() {
+ const registration = this._registration;
+ const evaluatingWorker = this._evaluatingWorker.form();
+ const installingWorker = this._installingWorker.form();
+ const waitingWorker = this._waitingWorker.form();
+ const activeWorker = this._activeWorker.form();
+
+ const newestWorker =
+ activeWorker || waitingWorker || installingWorker || evaluatingWorker;
+
+ const isMultiE10sWithOldImplementation =
+ Services.appinfo.browserTabsRemoteAutostart &&
+ !swm.isParentInterceptEnabled();
+ return {
+ actor: this.actorID,
+ scope: registration.scope,
+ url: registration.scriptSpec,
+ evaluatingWorker,
+ installingWorker,
+ waitingWorker,
+ activeWorker,
+ fetch: newestWorker?.fetch,
+ // - In old multi e10s: only active registrations are available.
+ // - In non-e10s or new implementaion: check if we have an active worker
+ active: isMultiE10sWithOldImplementation ? true : !!activeWorker,
+ lastUpdateTime: registration.lastUpdateTime,
+ traits: {},
+ };
+ },
+
+ destroy() {
+ protocol.Actor.prototype.destroy.call(this);
+
+ // Ensure resuming the service worker in case the connection drops
+ if (
+ swm.isParentInterceptEnabled() &&
+ this._registration.activeWorker &&
+ this._preventedShutdown
+ ) {
+ this.allowShutdown();
+ }
+
+ Services.obs.removeObserver(this, PushService.subscriptionModifiedTopic);
+ this._registration.removeListener(this);
+ this._registration = null;
+ if (this._pushSubscriptionActor) {
+ this._pushSubscriptionActor.destroy();
+ }
+ this._pushSubscriptionActor = null;
+
+ this._destroyServiceWorkerActors();
+
+ this._evaluatingWorker = null;
+ this._installingWorker = null;
+ this._waitingWorker = null;
+ this._activeWorker = null;
+ },
+
+ /**
+ * Standard observer interface to listen to push messages and changes.
+ */
+ observe(subject, topic, data) {
+ const scope = this._registration.scope;
+ if (data !== scope) {
+ // This event doesn't concern us, pretend nothing happened.
+ return;
+ }
+ switch (topic) {
+ case PushService.subscriptionModifiedTopic:
+ if (this._pushSubscriptionActor) {
+ this._pushSubscriptionActor.destroy();
+ this._pushSubscriptionActor = null;
+ }
+ this.emit("push-subscription-modified");
+ break;
+ }
+ },
+
+ start() {
+ if (swm.isParentInterceptEnabled()) {
+ const { activeWorker } = this._registration;
+
+ // TODO: don't return "started" if there's no active worker.
+ if (activeWorker) {
+ // This starts up the Service Worker if it's not already running.
+ // Note that with parent-intercept (i.e. swm.isParentInterceptEnabled /
+ // dom.serviceWorkers.parent_intercept=true), the Service Workers exist
+ // in content processes but are managed from the parent process. This is
+ // why we call `attachDebugger` here (in the parent process) instead of
+ // in a process script.
+ activeWorker.attachDebugger();
+ activeWorker.detachDebugger();
+ }
+
+ return { type: "started" };
+ }
+
+ if (!_serviceWorkerProcessScriptLoaded) {
+ Services.ppmm.loadProcessScript(
+ "resource://devtools/server/actors/worker/service-worker-process.js",
+ true
+ );
+ _serviceWorkerProcessScriptLoaded = true;
+ }
+
+ // XXX: Send the permissions down to the content process before starting
+ // the service worker within the content process. As we don't know what
+ // content process we're starting the service worker in (as we're using a
+ // broadcast channel to talk to it), we just broadcast the permissions to
+ // everyone as well.
+ //
+ // This call should be replaced with a proper implementation when
+ // ServiceWorker debugging is improved to support multiple content processes
+ // correctly.
+ Services.perms.broadcastPermissionsForPrincipalToAllContentProcesses(
+ this._registration.principal
+ );
+
+ Services.ppmm.broadcastAsyncMessage("serviceWorkerRegistration:start", {
+ scope: this._registration.scope,
+ });
+ return { type: "started" };
+ },
+
+ unregister() {
+ const { principal, scope } = this._registration;
+ const unregisterCallback = {
+ unregisterSucceeded: function() {},
+ unregisterFailed: function() {
+ console.error("Failed to unregister the service worker for " + scope);
+ },
+ QueryInterface: ChromeUtils.generateQI([
+ "nsIServiceWorkerUnregisterCallback",
+ ]),
+ };
+ swm.propagateUnregister(principal, unregisterCallback, scope);
+
+ return { type: "unregistered" };
+ },
+
+ push() {
+ if (!swm.isParentInterceptEnabled()) {
+ throw new Error(
+ "ServiceWorkerRegistrationActor.push can only be used " +
+ "in parent-intercept mode"
+ );
+ }
+
+ const { principal, scope } = this._registration;
+ const originAttributes = ChromeUtils.originAttributesToSuffix(
+ principal.originAttributes
+ );
+ swm.sendPushEvent(originAttributes, scope);
+ },
+
+ /**
+ * Prevent the current active worker to shutdown after the idle timeout.
+ */
+ preventShutdown() {
+ if (!swm.isParentInterceptEnabled()) {
+ // In non parent-intercept mode, this is handled by the WorkerDescriptorActor attach().
+ throw new Error(
+ "ServiceWorkerRegistrationActor.preventShutdown can only be used " +
+ "in parent-intercept mode"
+ );
+ }
+
+ if (!this._registration.activeWorker) {
+ throw new Error(
+ "ServiceWorkerRegistrationActor.preventShutdown could not find " +
+ "activeWorker in parent-intercept mode"
+ );
+ }
+
+ // attachDebugger has to be called from the parent process in parent-intercept mode.
+ this._registration.activeWorker.attachDebugger();
+ this._preventedShutdown = true;
+ },
+
+ /**
+ * Allow the current active worker to shut down again.
+ */
+ allowShutdown() {
+ if (!swm.isParentInterceptEnabled()) {
+ // In non parent-intercept mode, this is handled by the WorkerDescriptorActor detach().
+ throw new Error(
+ "ServiceWorkerRegistrationActor.allowShutdown can only be used " +
+ "in parent-intercept mode"
+ );
+ }
+
+ if (!this._registration.activeWorker) {
+ throw new Error(
+ "ServiceWorkerRegistrationActor.allowShutdown could not find " +
+ "activeWorker in parent-intercept mode"
+ );
+ }
+
+ this._registration.activeWorker.detachDebugger();
+ this._preventedShutdown = false;
+ },
+
+ getPushSubscription() {
+ const registration = this._registration;
+ let pushSubscriptionActor = this._pushSubscriptionActor;
+ if (pushSubscriptionActor) {
+ return Promise.resolve(pushSubscriptionActor);
+ }
+ return new Promise((resolve, reject) => {
+ PushService.getSubscription(
+ registration.scope,
+ registration.principal,
+ (result, subscription) => {
+ if (!subscription) {
+ resolve(null);
+ return;
+ }
+ pushSubscriptionActor = new PushSubscriptionActor(
+ this._conn,
+ subscription
+ );
+ this._pushSubscriptionActor = pushSubscriptionActor;
+ resolve(pushSubscriptionActor);
+ }
+ );
+ });
+ },
+
+ _destroyServiceWorkerActors() {
+ this._evaluatingWorker.destroy();
+ this._installingWorker.destroy();
+ this._waitingWorker.destroy();
+ this._activeWorker.destroy();
+ },
+
+ _createServiceWorkerActors() {
+ const {
+ evaluatingWorker,
+ installingWorker,
+ waitingWorker,
+ activeWorker,
+ } = this._registration;
+
+ this._evaluatingWorker = new ServiceWorkerActor(
+ this._conn,
+ evaluatingWorker
+ );
+ this._installingWorker = new ServiceWorkerActor(
+ this._conn,
+ installingWorker
+ );
+ this._waitingWorker = new ServiceWorkerActor(this._conn, waitingWorker);
+ this._activeWorker = new ServiceWorkerActor(this._conn, activeWorker);
+
+ // Add the ServiceWorker actors as children of this ServiceWorkerRegistration actor,
+ // assigning them valid actorIDs.
+ this.manage(this._evaluatingWorker);
+ this.manage(this._installingWorker);
+ this.manage(this._waitingWorker);
+ this.manage(this._activeWorker);
+ },
+ }
+);
+
+exports.ServiceWorkerRegistrationActor = ServiceWorkerRegistrationActor;
diff --git a/devtools/server/actors/worker/service-worker.js b/devtools/server/actors/worker/service-worker.js
new file mode 100644
index 0000000000..d77d5c1e9c
--- /dev/null
+++ b/devtools/server/actors/worker/service-worker.js
@@ -0,0 +1,45 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const protocol = require("devtools/shared/protocol");
+const {
+ serviceWorkerSpec,
+} = require("devtools/shared/specs/worker/service-worker");
+
+const ServiceWorkerActor = protocol.ActorClassWithSpec(serviceWorkerSpec, {
+ initialize(conn, worker) {
+ protocol.Actor.prototype.initialize.call(this, conn);
+ this._worker = worker;
+ },
+
+ form() {
+ if (!this._worker) {
+ return null;
+ }
+
+ // handlesFetchEvents is not available if the worker's main script is in the
+ // evaluating state.
+ const isEvaluating =
+ this._worker.state == Ci.nsIServiceWorkerInfo.STATE_PARSED;
+ const fetch = isEvaluating ? undefined : this._worker.handlesFetchEvents;
+
+ return {
+ actor: this.actorID,
+ url: this._worker.scriptSpec,
+ state: this._worker.state,
+ fetch,
+ id: this._worker.id,
+ };
+ },
+
+ destroy() {
+ protocol.Actor.prototype.destroy.call(this);
+ this._worker = null;
+ },
+});
+
+exports.ServiceWorkerActor = ServiceWorkerActor;
diff --git a/devtools/server/actors/worker/worker-descriptor-actor-list.js b/devtools/server/actors/worker/worker-descriptor-actor-list.js
new file mode 100644
index 0000000000..fa6aa12a75
--- /dev/null
+++ b/devtools/server/actors/worker/worker-descriptor-actor-list.js
@@ -0,0 +1,212 @@
+/* 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";
+
+const { Ci } = require("chrome");
+const { XPCOMUtils } = require("resource://gre/modules/XPCOMUtils.jsm");
+loader.lazyRequireGetter(
+ this,
+ "WorkerDescriptorActor",
+ "devtools/server/actors/descriptors/worker",
+ true
+);
+
+XPCOMUtils.defineLazyServiceGetter(
+ this,
+ "wdm",
+ "@mozilla.org/dom/workers/workerdebuggermanager;1",
+ "nsIWorkerDebuggerManager"
+);
+
+function matchWorkerDebugger(dbg, options) {
+ if ("type" in options && dbg.type !== options.type) {
+ return false;
+ }
+ if ("window" in options) {
+ let window = dbg.window;
+ while (window !== null && window.parent !== window) {
+ window = window.parent;
+ }
+
+ if (window !== options.window) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+function matchServiceWorker(dbg, origin) {
+ return (
+ dbg.type == Ci.nsIWorkerDebugger.TYPE_SERVICE &&
+ new URL(dbg.url).origin == origin
+ );
+}
+
+// When a new worker appears, in some cases (i.e. the debugger is running) we
+// want it to pause during registration until a later time (i.e. the debugger
+// finishes attaching to the worker). This is an optional WorkderDebuggerManager
+// listener that can be installed in addition to the WorkerDescriptorActorList
+// listener. It always listens to new workers and pauses any matching filters
+// which have been set on it.
+//
+// Two kinds of filters are supported:
+//
+// setPauseMatching(true) will pause all workers which match the options strcut
+// passed in on creation.
+//
+// setPauseServiceWorkers(origin) will pause all service workers which have the
+// specified origin.
+//
+// FIXME Bug 1601279 separate WorkerPauser from WorkerDescriptorActorList and give
+// it a more consistent interface.
+function WorkerPauser(options) {
+ this._options = options;
+ this._pauseMatching = null;
+ this._pauseServiceWorkerOrigin = null;
+
+ this.onRegister = this._onRegister.bind(this);
+ this.onUnregister = () => {};
+
+ wdm.addListener(this);
+}
+
+WorkerPauser.prototype = {
+ destroy() {
+ wdm.removeListener(this);
+ },
+
+ _onRegister(dbg) {
+ if (
+ (this._pauseMatching && matchWorkerDebugger(dbg, this._options)) ||
+ (this._pauseServiceWorkerOrigin &&
+ matchServiceWorker(dbg, this._pauseServiceWorkerOrigin))
+ ) {
+ // Prevent the debuggee from executing in this worker until the debugger
+ // has finished attaching to it.
+ dbg.setDebuggerReady(false);
+ }
+ },
+
+ setPauseMatching(shouldPause) {
+ this._pauseMatching = shouldPause;
+ },
+
+ setPauseServiceWorkers(origin) {
+ this._pauseServiceWorkerOrigin = origin;
+ },
+};
+
+function WorkerDescriptorActorList(conn, options) {
+ this._conn = conn;
+ this._options = options;
+ this._actors = new Map();
+ this._onListChanged = null;
+ this._workerPauser = null;
+ this._mustNotify = false;
+ this.onRegister = this.onRegister.bind(this);
+ this.onUnregister = this.onUnregister.bind(this);
+}
+
+WorkerDescriptorActorList.prototype = {
+ destroy() {
+ this.onListChanged = null;
+ if (this._workerPauser) {
+ this._workerPauser.destroy();
+ this._workerPauser = null;
+ }
+ },
+
+ getList() {
+ // Create a set of debuggers.
+ const dbgs = new Set();
+ for (const dbg of wdm.getWorkerDebuggerEnumerator()) {
+ if (matchWorkerDebugger(dbg, this._options)) {
+ dbgs.add(dbg);
+ }
+ }
+
+ // Delete each actor for which we don't have a debugger.
+ for (const [dbg] of this._actors) {
+ if (!dbgs.has(dbg)) {
+ this._actors.delete(dbg);
+ }
+ }
+
+ // Create an actor for each debugger for which we don't have one.
+ for (const dbg of dbgs) {
+ if (!this._actors.has(dbg)) {
+ this._actors.set(dbg, new WorkerDescriptorActor(this._conn, dbg));
+ }
+ }
+
+ const actors = [];
+ for (const [, actor] of this._actors) {
+ actors.push(actor);
+ }
+
+ if (!this._mustNotify) {
+ if (this._onListChanged !== null) {
+ wdm.addListener(this);
+ }
+ this._mustNotify = true;
+ }
+
+ return Promise.resolve(actors);
+ },
+
+ get onListChanged() {
+ return this._onListChanged;
+ },
+
+ set onListChanged(onListChanged) {
+ if (typeof onListChanged !== "function" && onListChanged !== null) {
+ throw new Error("onListChanged must be either a function or null.");
+ }
+ if (onListChanged === this._onListChanged) {
+ return;
+ }
+
+ if (this._mustNotify) {
+ if (this._onListChanged === null && onListChanged !== null) {
+ wdm.addListener(this);
+ }
+ if (this._onListChanged !== null && onListChanged === null) {
+ wdm.removeListener(this);
+ }
+ }
+ this._onListChanged = onListChanged;
+ },
+
+ _notifyListChanged() {
+ this._onListChanged();
+
+ if (this._onListChanged !== null) {
+ wdm.removeListener(this);
+ }
+ this._mustNotify = false;
+ },
+
+ onRegister(dbg) {
+ if (matchWorkerDebugger(dbg, this._options)) {
+ this._notifyListChanged();
+ }
+ },
+
+ onUnregister(dbg) {
+ if (matchWorkerDebugger(dbg, this._options)) {
+ this._notifyListChanged();
+ }
+ },
+
+ get workerPauser() {
+ if (!this._workerPauser) {
+ this._workerPauser = new WorkerPauser(this._options);
+ }
+ return this._workerPauser;
+ },
+};
+
+exports.WorkerDescriptorActorList = WorkerDescriptorActorList;