summaryrefslogtreecommitdiffstats
path: root/devtools/client/framework/devtools.js
blob: e56efb0c4b902201964a630e11650bfbcec176de (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
/* 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 { DevToolsShim } = ChromeUtils.importESModule(
  "chrome://devtools-startup/content/DevToolsShim.sys.mjs"
);

const { DEFAULT_SANDBOX_NAME } = ChromeUtils.importESModule(
  "resource://devtools/shared/loader/Loader.sys.mjs"
);

const lazy = {};
ChromeUtils.defineESModuleGetters(lazy, {
  BrowserToolboxLauncher:
    "resource://devtools/client/framework/browser-toolbox/Launcher.sys.mjs",
});

loader.lazyRequireGetter(
  this,
  "LocalTabCommandsFactory",
  "resource://devtools/client/framework/local-tab-commands-factory.js",
  true
);
loader.lazyRequireGetter(
  this,
  "CommandsFactory",
  "resource://devtools/shared/commands/commands-factory.js",
  true
);
loader.lazyRequireGetter(
  this,
  "ToolboxHostManager",
  "resource://devtools/client/framework/toolbox-host-manager.js",
  true
);
loader.lazyRequireGetter(
  this,
  "BrowserConsoleManager",
  "resource://devtools/client/webconsole/browser-console-manager.js",
  true
);
loader.lazyRequireGetter(
  this,
  "Toolbox",
  "resource://devtools/client/framework/toolbox.js",
  true
);

loader.lazyRequireGetter(
  this,
  "Telemetry",
  "resource://devtools/client/shared/telemetry.js"
);

const {
  defaultTools: DefaultTools,
  defaultThemes: DefaultThemes,
} = require("resource://devtools/client/definitions.js");
const EventEmitter = require("resource://devtools/shared/event-emitter.js");
const {
  getTheme,
  setTheme,
  getAutoTheme,
  addThemeObserver,
  removeThemeObserver,
} = require("resource://devtools/client/shared/theme.js");

const FORBIDDEN_IDS = new Set(["toolbox", ""]);
const MAX_ORDINAL = 99;
const POPUP_DEBUG_PREF = "devtools.popups.debug";
const DEVTOOLS_ALWAYS_ON_TOP = "devtools.toolbox.alwaysOnTop";

/**
 * DevTools is a class that represents a set of developer tools, it holds a
 * set of tools and keeps track of open toolboxes in the browser.
 */
function DevTools() {
  // We should be careful to always load a unique instance of this module:
  // - only in the parent process
  // - only in the "shared JSM global" spawn by mozJSModuleLoader
  //   The server codebase typically use another global named "DevTools global",
  //   which will load duplicated instances of all the modules -or- another
  //   DevTools module loader named "DevTools (Server Module loader)".
  //   Also the realm location is appended the loading callsite, so only check
  //   the beginning of the string.
  if (
    Services.appinfo.processType != Services.appinfo.PROCESS_TYPE_DEFAULT ||
    !Cu.getRealmLocation(globalThis).startsWith(DEFAULT_SANDBOX_NAME)
  ) {
    throw new Error(
      "This module should be loaded in the parent process only, in the shared global."
    );
  }

  this._tools = new Map(); // Map<toolId, tool>
  this._themes = new Map(); // Map<themeId, theme>
  this._toolboxesPerCommands = new Map(); // Map<commands, toolbox>
  // List of toolboxes that are still in process of creation
  this._creatingToolboxes = new Map(); // Map<commands, toolbox Promise>

  EventEmitter.decorate(this);
  this._telemetry = new Telemetry();
  this._telemetry.setEventRecordingEnabled(true);

  // List of all commands of debugged local Web Extension.
  this._commandsPromiseByWebExtId = new Map(); // Map<extensionId, commands>

  // Listen for changes to the theme pref.
  this._onThemeChanged = this._onThemeChanged.bind(this);
  addThemeObserver(this._onThemeChanged);

  // This is important step in initialization codepath where we are going to
  // start registering all default tools and themes: create menuitems, keys, emit
  // related events.
  this.registerDefaults();

  // Register this DevTools instance on the DevToolsShim, which is used by non-devtools
  // code to interact with DevTools.
  DevToolsShim.register(this);
}

DevTools.prototype = {
  // The windowtype of the main window, used in various tools. This may be set
  // to something different by other gecko apps.
  chromeWindowType: "navigator:browser",

  registerDefaults() {
    // Ensure registering items in the sorted order (getDefault* functions
    // return sorted lists)
    this.getDefaultTools().forEach(definition => this.registerTool(definition));
    this.getDefaultThemes().forEach(definition =>
      this.registerTheme(definition)
    );
  },

  unregisterDefaults() {
    for (const definition of this.getToolDefinitionArray()) {
      this.unregisterTool(definition.id);
    }
    for (const definition of this.getThemeDefinitionArray()) {
      this.unregisterTheme(definition.id);
    }
  },

  /**
   * Register a new developer tool.
   *
   * A definition is a light object that holds different information about a
   * developer tool. This object is not supposed to have any operational code.
   * See it as a "manifest".
   * The only actual code lives in the build() function, which will be used to
   * start an instance of this tool.
   *
   * Each toolDefinition has the following properties:
   * - id: Unique identifier for this tool (string|required)
   * - visibilityswitch: Property name to allow us to hide this tool from the
   *                     DevTools Toolbox.
   *                     A falsy value indicates that it cannot be hidden.
   * - icon: URL pointing to a graphic which will be used as the src for an
   *         16x16 img tag (string|required)
   * - url: URL pointing to a XUL/XHTML document containing the user interface
   *        (string|required)
   * - label: Localized name for the tool to be displayed to the user
   *          (string|required)
   * - hideInOptions: Boolean indicating whether or not this tool should be
                      shown in toolbox options or not. Defaults to false.
   *                  (boolean)
   * - build: Function that takes an iframe, which has been populated with the
   *          markup from |url|, and also the toolbox containing the panel.
   *          And returns an instance of ToolPanel (function|required)
   */
  registerTool(toolDefinition) {
    const toolId = toolDefinition.id;

    if (!toolId || FORBIDDEN_IDS.has(toolId)) {
      throw new Error("Invalid definition.id");
    }

    // Make sure that additional tools will always be able to be hidden.
    // When being called from main.js, defaultTools has not yet been exported.
    // But, we can assume that in this case, it is a default tool.
    if (!DefaultTools.includes(toolDefinition)) {
      toolDefinition.visibilityswitch = "devtools." + toolId + ".enabled";
    }

    this._tools.set(toolId, toolDefinition);

    this.emit("tool-registered", toolId);
  },

  /**
   * Removes all tools that match the given |toolId|
   * Needed so that add-ons can remove themselves when they are deactivated
   *
   * @param {string|object} tool
   *        Definition or the id of the tool to unregister. Passing the
   *        tool id should be avoided as it is a temporary measure.
   * @param {boolean} isQuitApplication
   *        true to indicate that the call is due to app quit, so we should not
   *        cause a cascade of costly events
   */
  unregisterTool(tool, isQuitApplication) {
    let toolId = null;
    if (typeof tool == "string") {
      toolId = tool;
      tool = this._tools.get(tool);
    } else {
      const { Deprecated } = ChromeUtils.importESModule(
        "resource://gre/modules/Deprecated.sys.mjs"
      );
      Deprecated.warning(
        "Deprecation WARNING: gDevTools.unregisterTool(tool) is " +
          "deprecated. You should unregister a tool using its toolId: " +
          "gDevTools.unregisterTool(toolId)."
      );
      toolId = tool.id;
    }
    this._tools.delete(toolId);

    if (!isQuitApplication) {
      this.emit("tool-unregistered", toolId);
    }
  },

  /**
   * Sorting function used for sorting tools based on their ordinals.
   */
  ordinalSort(d1, d2) {
    const o1 = typeof d1.ordinal == "number" ? d1.ordinal : MAX_ORDINAL;
    const o2 = typeof d2.ordinal == "number" ? d2.ordinal : MAX_ORDINAL;
    return o1 - o2;
  },

  getDefaultTools() {
    return DefaultTools.sort(this.ordinalSort);
  },

  getAdditionalTools() {
    const tools = [];
    for (const [, value] of this._tools) {
      if (!DefaultTools.includes(value)) {
        tools.push(value);
      }
    }
    return tools.sort(this.ordinalSort);
  },

  getDefaultThemes() {
    return DefaultThemes.sort(this.ordinalSort);
  },

  /**
   * Get a tool definition if it exists and is enabled.
   *
   * @param {string} toolId
   *        The id of the tool to show
   *
   * @return {ToolDefinition|null} tool
   *         The ToolDefinition for the id or null.
   */
  getToolDefinition(toolId) {
    const tool = this._tools.get(toolId);
    if (!tool) {
      return null;
    } else if (!tool.visibilityswitch) {
      return tool;
    }

    const enabled = Services.prefs.getBoolPref(tool.visibilityswitch, true);

    return enabled ? tool : null;
  },

  /**
   * Allow ToolBoxes to get at the list of tools that they should populate
   * themselves with.
   *
   * @return {Map} tools
   *         A map of the the tool definitions registered in this instance
   */
  getToolDefinitionMap() {
    const tools = new Map();

    for (const [id, definition] of this._tools) {
      if (this.getToolDefinition(id)) {
        tools.set(id, definition);
      }
    }

    return tools;
  },

  /**
   * Tools have an inherent ordering that can't be represented in a Map so
   * getToolDefinitionArray provides an alternative representation of the
   * definitions sorted by ordinal value.
   *
   * @return {Array} tools
   *         A sorted array of the tool definitions registered in this instance
   */
  getToolDefinitionArray() {
    const definitions = [];

    for (const [id, definition] of this._tools) {
      if (this.getToolDefinition(id)) {
        definitions.push(definition);
      }
    }

    return definitions.sort(this.ordinalSort);
  },

  /**
   * Returns the name of the current theme for devtools.
   *
   * @return {string} theme
   *         The name of the current devtools theme.
   */
  getTheme() {
    return getTheme();
  },

  /**
   * Returns the name of the default (auto) theme for devtools.
   *
   * @return {string} theme
   */
  getAutoTheme() {
    return getAutoTheme();
  },

  /**
   * Called when the developer tools theme changes.
   */
  _onThemeChanged() {
    this.emit("theme-changed", getTheme());
  },

  /**
   * Register a new theme for developer tools toolbox.
   *
   * A definition is a light object that holds various information about a
   * theme.
   *
   * Each themeDefinition has the following properties:
   * - id: Unique identifier for this theme (string|required)
   * - label: Localized name for the theme to be displayed to the user
   *          (string|required)
   * - stylesheets: Array of URLs pointing to a CSS document(s) containing
   *                the theme style rules (array|required)
   * - classList: Array of class names identifying the theme within a document.
   *              These names are set to document element when applying
   *              the theme (array|required)
   * - onApply: Function that is executed by the framework when the theme
   *            is applied. The function takes the current iframe window
   *            and the previous theme id as arguments (function)
   * - onUnapply: Function that is executed by the framework when the theme
   *            is unapplied. The function takes the current iframe window
   *            and the new theme id as arguments (function)
   */
  registerTheme(themeDefinition) {
    const themeId = themeDefinition.id;

    if (!themeId) {
      throw new Error("Invalid theme id");
    }

    if (this._themes.get(themeId)) {
      throw new Error("Theme with the same id is already registered");
    }

    this._themes.set(themeId, themeDefinition);

    this.emit("theme-registered", themeId);
  },

  /**
   * Removes an existing theme from the list of registered themes.
   * Needed so that add-ons can remove themselves when they are deactivated
   *
   * @param {string|object} theme
   *        Definition or the id of the theme to unregister.
   */
  unregisterTheme(theme) {
    let themeId = null;
    if (typeof theme == "string") {
      themeId = theme;
      theme = this._themes.get(theme);
    } else {
      themeId = theme.id;
    }

    const currTheme = getTheme();

    // Note that we can't check if `theme` is an item
    // of `DefaultThemes` as we end up reloading definitions
    // module and end up with different theme objects
    const isCoreTheme = DefaultThemes.some(t => t.id === themeId);

    // Reset the theme if an extension theme that's currently applied
    // is being removed.
    // Ignore shutdown since addons get disabled during that time.
    if (
      !Services.startup.shuttingDown &&
      !isCoreTheme &&
      theme.id == currTheme
    ) {
      setTheme("auto");

      this.emit("theme-unregistered", theme);
    }

    this._themes.delete(themeId);
  },

  /**
   * Get a theme definition if it exists.
   *
   * @param {string} themeId
   *        The id of the theme
   *
   * @return {ThemeDefinition|null} theme
   *         The ThemeDefinition for the id or null.
   */
  getThemeDefinition(themeId) {
    const theme = this._themes.get(themeId);
    if (!theme) {
      return null;
    }
    return theme;
  },

  /**
   * Get map of registered themes.
   *
   * @return {Map} themes
   *         A map of the the theme definitions registered in this instance
   */
  getThemeDefinitionMap() {
    const themes = new Map();

    for (const [id, definition] of this._themes) {
      if (this.getThemeDefinition(id)) {
        themes.set(id, definition);
      }
    }

    return themes;
  },

  /**
   * Get registered themes definitions sorted by ordinal value.
   *
   * @return {Array} themes
   *         A sorted array of the theme definitions registered in this instance
   */
  getThemeDefinitionArray() {
    const definitions = [];

    for (const [id, definition] of this._themes) {
      if (this.getThemeDefinition(id)) {
        definitions.push(definition);
      }
    }

    return definitions.sort(this.ordinalSort);
  },

  /**
   * Called from SessionStore.sys.mjs in mozilla-central when saving the current state.
   *
   * @param {Object} state
   *                 A SessionStore state object that gets modified by reference
   */
  saveDevToolsSession(state) {
    state.browserConsole =
      BrowserConsoleManager.getBrowserConsoleSessionState();
    state.browserToolbox =
      lazy.BrowserToolboxLauncher.getBrowserToolboxSessionState();
  },

  /**
   * Restore the devtools session state as provided by SessionStore.
   */
  async restoreDevToolsSession({ browserConsole, browserToolbox }) {
    if (browserToolbox) {
      lazy.BrowserToolboxLauncher.init();
    }

    if (browserConsole && !BrowserConsoleManager.getBrowserConsole()) {
      await BrowserConsoleManager.toggleBrowserConsole();
    }
  },

  /**
   * Boolean, true, if we never opened a toolbox.
   * Used to implement the telemetry tracking toolbox opening.
   */
  _firstShowToolbox: true,

  /**
   * Show a Toolbox for a given "commands" (either by creating a new one, or if a
   * toolbox already exists for the commands, by bringing to the front the
   * existing one).
   *
   * If a Toolbox already exists, we will still update it based on some of the
   * provided parameters:
   *   - if |toolId| is provided then the toolbox will switch to the specified
   *     tool.
   *   - if |hostType| is provided then the toolbox will be switched to the
   *     specified HostType.
   *
   * @param {Commands Object} commands
   *         The commands object which designates which context the toolbox will debug
   * @param {Object}
   *        - {String} toolId
   *          The id of the tool to show
   *        - {Toolbox.HostType} hostType
   *          The type of host (bottom, window, left, right)
   *        - {object} hostOptions
   *          Options for host specifically
   *        - {Number} startTime
   *          Indicates the time at which the user event related to
   *          this toolbox opening started. This is a `Cu.now()` timing.
   *        - {string} reason
   *          Reason the tool was opened
   *        - {boolean} raise
   *          Whether we need to raise the toolbox or not.
   *
   * @return {Toolbox} toolbox
   *        The toolbox that was opened
   */
  async showToolbox(
    commands,
    {
      toolId,
      hostType,
      startTime,
      raise = true,
      reason = "toolbox_show",
      hostOptions,
    } = {}
  ) {
    let toolbox = this._toolboxesPerCommands.get(commands);

    if (toolbox) {
      if (hostType != null && toolbox.hostType != hostType) {
        await toolbox.switchHost(hostType);
      }

      if (toolId != null) {
        // selectTool will either select the tool if not currently selected, or wait for
        // the tool to be loaded if needed.
        await toolbox.selectTool(toolId, reason);
      }

      if (raise) {
        await toolbox.raise();
      }
    } else {
      // Toolbox creation is async, we have to be careful about races.
      // Check if we are already waiting for a Toolbox for the provided
      // commands before creating a new one.
      const promise = this._creatingToolboxes.get(commands);
      if (promise) {
        return promise;
      }
      const toolboxPromise = this._createToolbox(
        commands,
        toolId,
        hostType,
        hostOptions
      );
      this._creatingToolboxes.set(commands, toolboxPromise);
      toolbox = await toolboxPromise;
      this._creatingToolboxes.delete(commands);

      if (startTime) {
        this.logToolboxOpenTime(toolbox, startTime);
      }
      this._firstShowToolbox = false;
    }

    // We send the "enter" width here to ensure it is always sent *after*
    // the "open" event.
    const width = Math.ceil(toolbox.win.outerWidth / 50) * 50;
    const panelName = this.makeToolIdHumanReadable(
      toolId || toolbox.defaultToolId
    );
    this._telemetry.addEventProperty(
      toolbox,
      "enter",
      panelName,
      null,
      "width",
      width
    );

    return toolbox;
  },

  /**
   * Show the toolbox for a given tab. If a toolbox already exists for this tab
   * the existing toolbox will be raised. Otherwise a new toolbox is created.
   *
   * Relies on `showToolbox`, see its jsDoc for additional information and
   * arguments description.
   *
   * Also used by 3rd party tools (eg wptrunner) and exposed by
   * DevToolsShim.sys.mjs.
   *
   * @param {XULTab} tab
   *        The tab the toolbox will debug
   * @param {Object} options
   *        Various options that will be forwarded to `showToolbox`. See the
   *        JSDoc on this method.
   */
  async showToolboxForTab(
    tab,
    { toolId, hostType, startTime, raise, reason, hostOptions } = {}
  ) {
    // Popups are debugged via the toolbox of their opener document/tab.
    // So avoid opening dedicated toolbox for them.
    if (
      tab.linkedBrowser.browsingContext.opener &&
      Services.prefs.getBoolPref(POPUP_DEBUG_PREF)
    ) {
      const openerTab = tab.ownerGlobal.gBrowser.getTabForBrowser(
        tab.linkedBrowser.browsingContext.opener.embedderElement
      );
      const openerCommands = await LocalTabCommandsFactory.getCommandsForTab(
        openerTab
      );
      if (this.getToolboxForCommands(openerCommands)) {
        console.log(
          "Can't open a toolbox for this document as this is debugged from its opener tab"
        );
        return null;
      }
    }
    const commands = await LocalTabCommandsFactory.createCommandsForTab(tab);
    return this.showToolbox(commands, {
      toolId,
      hostType,
      startTime,
      raise,
      reason,
      hostOptions,
    });
  },

  /**
   * Open a Toolbox in a dedicated top-level window for debugging a local WebExtension.
   * This will re-open a previously opened toolbox if we try to re-debug the same extension.
   *
   * Note that this will spawn a new DevToolsClient.
   *
   * @param {String} extensionId
   *        ID of the extension to debug.
   * @param {Object} (optional)
   *        - {String} toolId
   *          The id of the tool to show
   */
  async showToolboxForWebExtension(extensionId, { toolId } = {}) {
    // Ensure spawning only one commands instance per extension at a time by caching its commands.
    // showToolbox will later reopen the previously opened toolbox if called with the same
    // commands.
    let commandsPromise = this._commandsPromiseByWebExtId.get(extensionId);
    if (!commandsPromise) {
      commandsPromise = CommandsFactory.forAddon(extensionId);
      this._commandsPromiseByWebExtId.set(extensionId, commandsPromise);
    }
    const commands = await commandsPromise;
    commands.client.once("closed").then(() => {
      this._commandsPromiseByWebExtId.delete(extensionId);
    });

    return this.showToolbox(commands, {
      hostType: Toolbox.HostType.WINDOW,
      hostOptions: {
        // The toolbox is always displayed on top so that we can keep
        // the DevTools visible while interacting with the Firefox window.
        alwaysOnTop: Services.prefs.getBoolPref(DEVTOOLS_ALWAYS_ON_TOP, false),
      },
      toolId,
    });
  },

  /**
   * Log telemetry related to toolbox opening.
   * Two distinct probes are logged. One for cold startup, when we open the very first
   * toolbox. This one includes devtools framework loading. And a second one for all
   * subsequent toolbox opening, which should all be faster.
   * These two probes are indexed by Tool ID.
   *
   * @param {String} toolbox
   *        Toolbox instance.
   * @param {Number} startTime
   *        Indicates the time at which the user event related to the toolbox
   *        opening started. This is a `Cu.now()` timing.
   */
  logToolboxOpenTime(toolbox, startTime) {
    const toolId = toolbox.currentToolId || toolbox.defaultToolId;
    const delay = Cu.now() - startTime;
    const panelName = this.makeToolIdHumanReadable(toolId);

    const telemetryKey = this._firstShowToolbox
      ? "DEVTOOLS_COLD_TOOLBOX_OPEN_DELAY_MS"
      : "DEVTOOLS_WARM_TOOLBOX_OPEN_DELAY_MS";
    this._telemetry.getKeyedHistogramById(telemetryKey).add(toolId, delay);

    const browserWin = toolbox.topWindow;
    this._telemetry.addEventProperty(
      browserWin,
      "open",
      "tools",
      null,
      "first_panel",
      panelName
    );
  },

  makeToolIdHumanReadable(toolId) {
    if (/^[0-9a-fA-F]{40}_temporary-addon/.test(toolId)) {
      return "temporary-addon";
    }

    let matches = toolId.match(
      /^_([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})_/
    );
    if (matches && matches.length === 2) {
      return matches[1];
    }

    matches = toolId.match(/^_?(.*)-\d+-\d+-devtools-panel$/);
    if (matches && matches.length === 2) {
      return matches[1];
    }

    return toolId;
  },

  /**
   * Unconditionally create a new Toolbox instance for the provided commands.
   * See `showToolbox` for the arguments' jsdoc.
   */
  async _createToolbox(commands, toolId, hostType, hostOptions) {
    const manager = new ToolboxHostManager(commands, hostType, hostOptions);

    const toolbox = await manager.create(toolId);

    this._toolboxesPerCommands.set(commands, toolbox);

    toolbox.once("destroy", () => {
      this.emit("toolbox-destroy", toolbox);
    });

    toolbox.once("destroyed", () => {
      this._toolboxesPerCommands.delete(commands);
      this.emit("toolbox-destroyed", toolbox);
    });

    await toolbox.open();
    this.emit("toolbox-ready", toolbox);

    return toolbox;
  },

  /**
   * Return the toolbox for a given commands object.
   *
   * @param  {Commands Object} commands
   *         Debugging context commands that owns this toolbox
   *
   * @return {Toolbox} toolbox
   *         The toolbox that is debugging the given context designated by the commands
   */
  getToolboxForCommands(commands) {
    return this._toolboxesPerCommands.get(commands);
  },

  /**
   * TabDescriptorFront requires a synchronous method and don't have a reference to its
   * related commands object. So expose something handcrafted just for this.
   */
  getToolboxForDescriptorFront(descriptorFront) {
    for (const [commands, toolbox] of this._toolboxesPerCommands) {
      if (commands.descriptorFront == descriptorFront) {
        return toolbox;
      }
    }
    return null;
  },

  /**
   * Retrieve an existing toolbox for the provided tab if it was created before.
   * Returns null otherwise.
   *
   * @param {XULTab} tab
   *        The browser tab.
   * @return {Toolbox}
   *        Returns tab's toolbox object.
   */
  getToolboxForTab(tab) {
    return this.getToolboxes().find(
      t => t.commands.descriptorFront.localTab === tab
    );
  },

  /**
   * Close the toolbox for a given tab.
   *
   * @return {Promise} Returns a promise that resolves either:
   *         - immediately if no Toolbox was found
   *         - or after toolbox.destroy() resolved if a Toolbox was found
   */
  async closeToolboxForTab(tab) {
    const commands = await LocalTabCommandsFactory.getCommandsForTab(tab);

    let toolbox = await this._creatingToolboxes.get(commands);
    if (!toolbox) {
      toolbox = this._toolboxesPerCommands.get(commands);
    }
    if (!toolbox) {
      return;
    }
    await toolbox.destroy();
  },

  /**
   * Compatibility layer for web-extensions. Used by DevToolsShim for
   * browser/components/extensions/ext-devtools.js
   *
   * web-extensions need to use dedicated instances of Commands and cannot reuse the
   * cached instances managed by DevTools.
   * Note that is will end up being cached in WebExtension codebase, via
   * DevToolsExtensionPageContextParent.getDevToolsCommands.
   */
  createCommandsForTabForWebExtension(tab) {
    return CommandsFactory.forTab(tab, { isWebExtension: true });
  },

  /**
   * Compatibility layer for web-extensions. Used by DevToolsShim for
   * toolkit/components/extensions/ext-c-toolkit.js
   */
  openBrowserConsole() {
    const {
      BrowserConsoleManager,
    } = require("resource://devtools/client/webconsole/browser-console-manager.js");
    BrowserConsoleManager.openBrowserConsoleOrFocus();
  },

  /**
   * Called from the DevToolsShim, used by nsContextMenu.js.
   *
   * @param {XULTab} tab
   *        The browser tab on which inspect node was used.
   * @param {ElementIdentifier} domReference
   *        Identifier generated by ContentDOMReference. It is a unique pair of
   *        BrowsingContext ID and a numeric ID.
   * @param {Number} startTime
   *        Optional, indicates the time at which the user event related to this node
   *        inspection started. This is a `Cu.now()` timing.
   * @return {Promise} a promise that resolves when the node is selected in the inspector
   *         markup view.
   */
  async inspectNode(tab, domReference, startTime) {
    const toolbox = await gDevTools.showToolboxForTab(tab, {
      toolId: "inspector",
      startTime,
      reason: "inspect_dom",
    });
    const inspector = toolbox.getCurrentPanel();

    const nodeFront =
      await inspector.inspectorFront.getNodeActorFromContentDomReference(
        domReference
      );
    if (!nodeFront) {
      return;
    }

    // "new-node-front" tells us when the node has been selected, whether the
    // browser is remote or not.
    const onNewNode = inspector.selection.once("new-node-front");
    // Select the final node
    inspector.selection.setNodeFront(nodeFront, {
      reason: "browser-context-menu",
    });

    await onNewNode;
    // Now that the node has been selected, wait until the inspector is
    // fully updated.
    await inspector.once("inspector-updated");
  },

  /**
   * Called from the DevToolsShim, used by nsContextMenu.js.
   *
   * @param {XULTab} tab
   *        The browser tab on which inspect accessibility was used.
   * @param {ElementIdentifier} domReference
   *        Identifier generated by ContentDOMReference. It is a unique pair of
   *        BrowsingContext ID and a numeric ID.
   * @param {Number} startTime
   *        Optional, indicates the time at which the user event related to this
   *        node inspection started. This is a `Cu.now()` timing.
   * @return {Promise} a promise that resolves when the accessible object is
   *         selected in the accessibility inspector.
   */
  async inspectA11Y(tab, domReference, startTime) {
    const toolbox = await gDevTools.showToolboxForTab(tab, {
      toolId: "accessibility",
      startTime,
    });
    const inspectorFront = await toolbox.target.getFront("inspector");
    const nodeFront = await inspectorFront.getNodeActorFromContentDomReference(
      domReference
    );
    if (!nodeFront) {
      return;
    }

    // Select the accessible object in the panel and wait for the event that
    // tells us it has been done.
    const a11yPanel = toolbox.getCurrentPanel();
    const onSelected = a11yPanel.once("new-accessible-front-selected");
    a11yPanel.selectAccessibleForNode(nodeFront, "browser-context-menu");
    await onSelected;
  },

  /**
   * Either the DevTools Loader has been destroyed or firefox is shutting down.
   * @param {boolean} shuttingDown
   *        True if firefox is currently shutting down. We may prevent doing
   *        some cleanups to speed it up. Otherwise everything need to be
   *        cleaned up in order to be able to load devtools again.
   */
  destroy({ shuttingDown }) {
    // Do not cleanup everything during firefox shutdown.
    if (!shuttingDown) {
      for (const [, toolbox] of this._toolboxesPerCommands) {
        toolbox.destroy();
      }
    }

    for (const [key] of this.getToolDefinitionMap()) {
      this.unregisterTool(key, true);
    }

    gDevTools.unregisterDefaults();

    removeThemeObserver(this._onThemeChanged);

    // Do not unregister devtools from the DevToolsShim if the destroy is caused by an
    // application shutdown. For instance SessionStore needs to save the Browser Toolbox
    // state on shutdown.
    if (!shuttingDown) {
      // Notify the DevToolsShim that DevTools are no longer available, particularly if
      // the destroy was caused by disabling/removing DevTools.
      DevToolsShim.unregister();
    }

    // Cleaning down the toolboxes: i.e.
    //   for (let [, toolbox] of this._toolboxesPerCommands) toolbox.destroy();
    // Is taken care of by the gDevToolsBrowser.forgetBrowserWindow
  },

  /**
   * Returns the array of the existing toolboxes.
   *
   * @return {Array<Toolbox>}
   *   An array of toolboxes.
   */
  getToolboxes() {
    return Array.from(this._toolboxesPerCommands.values());
  },

  /**
   * Returns whether the given tab has toolbox.
   *
   * @param {XULTab} tab
   *        The browser tab.
   * @return {boolean}
   *        Returns true if the tab has toolbox.
   */
  hasToolboxForTab(tab) {
    return this.getToolboxes().some(
      t => t.commands.descriptorFront.localTab === tab
    );
  },
};

const gDevTools = (exports.gDevTools = new DevTools());