devtools.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. const Services = require("Services");
  6. const promise = require("promise");
  7. const defer = require("devtools/shared/defer");
  8. // Load gDevToolsBrowser toolbox lazily as they need gDevTools to be fully initialized
  9. loader.lazyRequireGetter(this, "Toolbox", "devtools/client/framework/toolbox", true);
  10. loader.lazyRequireGetter(this, "ToolboxHostManager", "devtools/client/framework/toolbox-host-manager", true);
  11. loader.lazyRequireGetter(this, "gDevToolsBrowser", "devtools/client/framework/devtools-browser", true);
  12. const {defaultTools: DefaultTools, defaultThemes: DefaultThemes} =
  13. require("devtools/client/definitions");
  14. const EventEmitter = require("devtools/shared/event-emitter");
  15. const {JsonView} = require("devtools/client/jsonview/main");
  16. const AboutDevTools = require("devtools/client/framework/about-devtools-toolbox");
  17. const {when: unload} = require("sdk/system/unload");
  18. const {Task} = require("devtools/shared/task");
  19. const FORBIDDEN_IDS = new Set(["toolbox", ""]);
  20. const MAX_ORDINAL = 99;
  21. /**
  22. * DevTools is a class that represents a set of developer tools, it holds a
  23. * set of tools and keeps track of open toolboxes in the browser.
  24. */
  25. this.DevTools = function DevTools() {
  26. this._tools = new Map(); // Map<toolId, tool>
  27. this._themes = new Map(); // Map<themeId, theme>
  28. this._toolboxes = new Map(); // Map<target, toolbox>
  29. // List of toolboxes that are still in process of creation
  30. this._creatingToolboxes = new Map(); // Map<target, toolbox Promise>
  31. // destroy() is an observer's handler so we need to preserve context.
  32. this.destroy = this.destroy.bind(this);
  33. // JSON Viewer for 'application/json' documents.
  34. JsonView.initialize();
  35. AboutDevTools.register();
  36. EventEmitter.decorate(this);
  37. Services.obs.addObserver(this.destroy, "quit-application", false);
  38. // This is important step in initialization codepath where we are going to
  39. // start registering all default tools and themes: create menuitems, keys, emit
  40. // related events.
  41. this.registerDefaults();
  42. };
  43. DevTools.prototype = {
  44. // The windowtype of the main window, used in various tools. This may be set
  45. // to something different by other gecko apps.
  46. chromeWindowType: "navigator:browser",
  47. registerDefaults() {
  48. // Ensure registering items in the sorted order (getDefault* functions
  49. // return sorted lists)
  50. this.getDefaultTools().forEach(definition => this.registerTool(definition));
  51. this.getDefaultThemes().forEach(definition => this.registerTheme(definition));
  52. },
  53. unregisterDefaults() {
  54. for (let definition of this.getToolDefinitionArray()) {
  55. this.unregisterTool(definition.id);
  56. }
  57. for (let definition of this.getThemeDefinitionArray()) {
  58. this.unregisterTheme(definition.id);
  59. }
  60. },
  61. /**
  62. * Register a new developer tool.
  63. *
  64. * A definition is a light object that holds different information about a
  65. * developer tool. This object is not supposed to have any operational code.
  66. * See it as a "manifest".
  67. * The only actual code lives in the build() function, which will be used to
  68. * start an instance of this tool.
  69. *
  70. * Each toolDefinition has the following properties:
  71. * - id: Unique identifier for this tool (string|required)
  72. * - visibilityswitch: Property name to allow us to hide this tool from the
  73. * DevTools Toolbox.
  74. * A falsy value indicates that it cannot be hidden.
  75. * - icon: URL pointing to a graphic which will be used as the src for an
  76. * 16x16 img tag (string|required)
  77. * - invertIconForLightTheme: The icon can automatically have an inversion
  78. * filter applied (default is false). All builtin tools are true, but
  79. * addons may omit this to prevent unwanted changes to the `icon`
  80. * image. filter: invert(1) is applied to the image (boolean|optional)
  81. * - url: URL pointing to a XUL/XHTML document containing the user interface
  82. * (string|required)
  83. * - label: Localized name for the tool to be displayed to the user
  84. * (string|required)
  85. * - hideInOptions: Boolean indicating whether or not this tool should be
  86. shown in toolbox options or not. Defaults to false.
  87. * (boolean)
  88. * - build: Function that takes an iframe, which has been populated with the
  89. * markup from |url|, and also the toolbox containing the panel.
  90. * And returns an instance of ToolPanel (function|required)
  91. */
  92. registerTool: function DT_registerTool(toolDefinition) {
  93. let toolId = toolDefinition.id;
  94. if (!toolId || FORBIDDEN_IDS.has(toolId)) {
  95. throw new Error("Invalid definition.id");
  96. }
  97. // Make sure that additional tools will always be able to be hidden.
  98. // When being called from main.js, defaultTools has not yet been exported.
  99. // But, we can assume that in this case, it is a default tool.
  100. if (DefaultTools.indexOf(toolDefinition) == -1) {
  101. toolDefinition.visibilityswitch = "devtools." + toolId + ".enabled";
  102. }
  103. this._tools.set(toolId, toolDefinition);
  104. this.emit("tool-registered", toolId);
  105. },
  106. /**
  107. * Removes all tools that match the given |toolId|
  108. * Needed so that add-ons can remove themselves when they are deactivated
  109. *
  110. * @param {string|object} tool
  111. * Definition or the id of the tool to unregister. Passing the
  112. * tool id should be avoided as it is a temporary measure.
  113. * @param {boolean} isQuitApplication
  114. * true to indicate that the call is due to app quit, so we should not
  115. * cause a cascade of costly events
  116. */
  117. unregisterTool: function DT_unregisterTool(tool, isQuitApplication) {
  118. let toolId = null;
  119. if (typeof tool == "string") {
  120. toolId = tool;
  121. tool = this._tools.get(tool);
  122. }
  123. else {
  124. toolId = tool.id;
  125. }
  126. this._tools.delete(toolId);
  127. if (!isQuitApplication) {
  128. this.emit("tool-unregistered", tool);
  129. }
  130. },
  131. /**
  132. * Sorting function used for sorting tools based on their ordinals.
  133. */
  134. ordinalSort: function DT_ordinalSort(d1, d2) {
  135. let o1 = (typeof d1.ordinal == "number") ? d1.ordinal : MAX_ORDINAL;
  136. let o2 = (typeof d2.ordinal == "number") ? d2.ordinal : MAX_ORDINAL;
  137. return o1 - o2;
  138. },
  139. getDefaultTools: function DT_getDefaultTools() {
  140. return DefaultTools.sort(this.ordinalSort);
  141. },
  142. getAdditionalTools: function DT_getAdditionalTools() {
  143. let tools = [];
  144. for (let [key, value] of this._tools) {
  145. if (DefaultTools.indexOf(value) == -1) {
  146. tools.push(value);
  147. }
  148. }
  149. return tools.sort(this.ordinalSort);
  150. },
  151. getDefaultThemes() {
  152. return DefaultThemes.sort(this.ordinalSort);
  153. },
  154. /**
  155. * Get a tool definition if it exists and is enabled.
  156. *
  157. * @param {string} toolId
  158. * The id of the tool to show
  159. *
  160. * @return {ToolDefinition|null} tool
  161. * The ToolDefinition for the id or null.
  162. */
  163. getToolDefinition: function DT_getToolDefinition(toolId) {
  164. let tool = this._tools.get(toolId);
  165. if (!tool) {
  166. return null;
  167. } else if (!tool.visibilityswitch) {
  168. return tool;
  169. }
  170. let enabled = Services.prefs.getBoolPref(tool.visibilityswitch, true);
  171. return enabled ? tool : null;
  172. },
  173. /**
  174. * Allow ToolBoxes to get at the list of tools that they should populate
  175. * themselves with.
  176. *
  177. * @return {Map} tools
  178. * A map of the the tool definitions registered in this instance
  179. */
  180. getToolDefinitionMap: function DT_getToolDefinitionMap() {
  181. let tools = new Map();
  182. for (let [id, definition] of this._tools) {
  183. if (this.getToolDefinition(id)) {
  184. tools.set(id, definition);
  185. }
  186. }
  187. return tools;
  188. },
  189. /**
  190. * Tools have an inherent ordering that can't be represented in a Map so
  191. * getToolDefinitionArray provides an alternative representation of the
  192. * definitions sorted by ordinal value.
  193. *
  194. * @return {Array} tools
  195. * A sorted array of the tool definitions registered in this instance
  196. */
  197. getToolDefinitionArray: function DT_getToolDefinitionArray() {
  198. let definitions = [];
  199. for (let [id, definition] of this._tools) {
  200. if (this.getToolDefinition(id)) {
  201. definitions.push(definition);
  202. }
  203. }
  204. return definitions.sort(this.ordinalSort);
  205. },
  206. /**
  207. * Register a new theme for developer tools toolbox.
  208. *
  209. * A definition is a light object that holds various information about a
  210. * theme.
  211. *
  212. * Each themeDefinition has the following properties:
  213. * - id: Unique identifier for this theme (string|required)
  214. * - label: Localized name for the theme to be displayed to the user
  215. * (string|required)
  216. * - stylesheets: Array of URLs pointing to a CSS document(s) containing
  217. * the theme style rules (array|required)
  218. * - classList: Array of class names identifying the theme within a document.
  219. * These names are set to document element when applying
  220. * the theme (array|required)
  221. * - onApply: Function that is executed by the framework when the theme
  222. * is applied. The function takes the current iframe window
  223. * and the previous theme id as arguments (function)
  224. * - onUnapply: Function that is executed by the framework when the theme
  225. * is unapplied. The function takes the current iframe window
  226. * and the new theme id as arguments (function)
  227. */
  228. registerTheme: function DT_registerTheme(themeDefinition) {
  229. let themeId = themeDefinition.id;
  230. if (!themeId) {
  231. throw new Error("Invalid theme id");
  232. }
  233. if (this._themes.get(themeId)) {
  234. throw new Error("Theme with the same id is already registered");
  235. }
  236. this._themes.set(themeId, themeDefinition);
  237. this.emit("theme-registered", themeId);
  238. },
  239. /**
  240. * Removes an existing theme from the list of registered themes.
  241. * Needed so that add-ons can remove themselves when they are deactivated
  242. *
  243. * @param {string|object} theme
  244. * Definition or the id of the theme to unregister.
  245. */
  246. unregisterTheme: function DT_unregisterTheme(theme) {
  247. let themeId = null;
  248. if (typeof theme == "string") {
  249. themeId = theme;
  250. theme = this._themes.get(theme);
  251. }
  252. else {
  253. themeId = theme.id;
  254. }
  255. let currTheme = Services.prefs.getCharPref("devtools.theme");
  256. // Note that we can't check if `theme` is an item
  257. // of `DefaultThemes` as we end up reloading definitions
  258. // module and end up with different theme objects
  259. let isCoreTheme = DefaultThemes.some(t => t.id === themeId);
  260. // Reset the theme if an extension theme that's currently applied
  261. // is being removed.
  262. // Ignore shutdown since addons get disabled during that time.
  263. if (!Services.startup.shuttingDown &&
  264. !isCoreTheme &&
  265. theme.id == currTheme) {
  266. Services.prefs.setCharPref("devtools.theme", "light");
  267. let data = {
  268. pref: "devtools.theme",
  269. newValue: "light",
  270. oldValue: currTheme
  271. };
  272. this.emit("pref-changed", data);
  273. this.emit("theme-unregistered", theme);
  274. }
  275. this._themes.delete(themeId);
  276. },
  277. /**
  278. * Get a theme definition if it exists.
  279. *
  280. * @param {string} themeId
  281. * The id of the theme
  282. *
  283. * @return {ThemeDefinition|null} theme
  284. * The ThemeDefinition for the id or null.
  285. */
  286. getThemeDefinition: function DT_getThemeDefinition(themeId) {
  287. let theme = this._themes.get(themeId);
  288. if (!theme) {
  289. return null;
  290. }
  291. return theme;
  292. },
  293. /**
  294. * Get map of registered themes.
  295. *
  296. * @return {Map} themes
  297. * A map of the the theme definitions registered in this instance
  298. */
  299. getThemeDefinitionMap: function DT_getThemeDefinitionMap() {
  300. let themes = new Map();
  301. for (let [id, definition] of this._themes) {
  302. if (this.getThemeDefinition(id)) {
  303. themes.set(id, definition);
  304. }
  305. }
  306. return themes;
  307. },
  308. /**
  309. * Get registered themes definitions sorted by ordinal value.
  310. *
  311. * @return {Array} themes
  312. * A sorted array of the theme definitions registered in this instance
  313. */
  314. getThemeDefinitionArray: function DT_getThemeDefinitionArray() {
  315. let definitions = [];
  316. for (let [id, definition] of this._themes) {
  317. if (this.getThemeDefinition(id)) {
  318. definitions.push(definition);
  319. }
  320. }
  321. return definitions.sort(this.ordinalSort);
  322. },
  323. /**
  324. * Show a Toolbox for a target (either by creating a new one, or if a toolbox
  325. * already exists for the target, by bring to the front the existing one)
  326. * If |toolId| is specified then the displayed toolbox will have the
  327. * specified tool selected.
  328. * If |hostType| is specified then the toolbox will be displayed using the
  329. * specified HostType.
  330. *
  331. * @param {Target} target
  332. * The target the toolbox will debug
  333. * @param {string} toolId
  334. * The id of the tool to show
  335. * @param {Toolbox.HostType} hostType
  336. * The type of host (bottom, window, side)
  337. * @param {object} hostOptions
  338. * Options for host specifically
  339. *
  340. * @return {Toolbox} toolbox
  341. * The toolbox that was opened
  342. */
  343. showToolbox: Task.async(function* (target, toolId, hostType, hostOptions) {
  344. let toolbox = this._toolboxes.get(target);
  345. if (toolbox) {
  346. if (hostType != null && toolbox.hostType != hostType) {
  347. yield toolbox.switchHost(hostType);
  348. }
  349. if (toolId != null && toolbox.currentToolId != toolId) {
  350. yield toolbox.selectTool(toolId);
  351. }
  352. toolbox.raise();
  353. } else {
  354. // As toolbox object creation is async, we have to be careful about races
  355. // Check for possible already in process of loading toolboxes before
  356. // actually trying to create a new one.
  357. let promise = this._creatingToolboxes.get(target);
  358. if (promise) {
  359. return yield promise;
  360. }
  361. let toolboxPromise = this.createToolbox(target, toolId, hostType, hostOptions);
  362. this._creatingToolboxes.set(target, toolboxPromise);
  363. toolbox = yield toolboxPromise;
  364. this._creatingToolboxes.delete(target);
  365. }
  366. return toolbox;
  367. }),
  368. createToolbox: Task.async(function* (target, toolId, hostType, hostOptions) {
  369. let manager = new ToolboxHostManager(target, hostType, hostOptions);
  370. let toolbox = yield manager.create(toolId);
  371. this._toolboxes.set(target, toolbox);
  372. this.emit("toolbox-created", toolbox);
  373. toolbox.once("destroy", () => {
  374. this.emit("toolbox-destroy", target);
  375. });
  376. toolbox.once("destroyed", () => {
  377. this._toolboxes.delete(target);
  378. this.emit("toolbox-destroyed", target);
  379. });
  380. yield toolbox.open();
  381. this.emit("toolbox-ready", toolbox);
  382. return toolbox;
  383. }),
  384. /**
  385. * Return the toolbox for a given target.
  386. *
  387. * @param {object} target
  388. * Target value e.g. the target that owns this toolbox
  389. *
  390. * @return {Toolbox} toolbox
  391. * The toolbox that is debugging the given target
  392. */
  393. getToolbox: function DT_getToolbox(target) {
  394. return this._toolboxes.get(target);
  395. },
  396. /**
  397. * Close the toolbox for a given target
  398. *
  399. * @return promise
  400. * This promise will resolve to false if no toolbox was found
  401. * associated to the target. true, if the toolbox was successfully
  402. * closed.
  403. */
  404. closeToolbox: Task.async(function* (target) {
  405. let toolbox = yield this._creatingToolboxes.get(target);
  406. if (!toolbox) {
  407. toolbox = this._toolboxes.get(target);
  408. }
  409. if (!toolbox) {
  410. return false;
  411. }
  412. yield toolbox.destroy();
  413. return true;
  414. }),
  415. /**
  416. * Called to tear down a tools provider.
  417. */
  418. _teardown: function DT_teardown() {
  419. for (let [target, toolbox] of this._toolboxes) {
  420. toolbox.destroy();
  421. }
  422. AboutDevTools.unregister();
  423. },
  424. /**
  425. * All browser windows have been closed, tidy up remaining objects.
  426. */
  427. destroy: function () {
  428. Services.obs.removeObserver(this.destroy, "quit-application");
  429. for (let [key, tool] of this.getToolDefinitionMap()) {
  430. this.unregisterTool(key, true);
  431. }
  432. JsonView.destroy();
  433. gDevTools.unregisterDefaults();
  434. // Cleaning down the toolboxes: i.e.
  435. // for (let [target, toolbox] of this._toolboxes) toolbox.destroy();
  436. // Is taken care of by the gDevToolsBrowser.forgetBrowserWindow
  437. },
  438. /**
  439. * Iterator that yields each of the toolboxes.
  440. */
  441. *[Symbol.iterator ]() {
  442. for (let toolbox of this._toolboxes) {
  443. yield toolbox;
  444. }
  445. }
  446. };
  447. const gDevTools = exports.gDevTools = new DevTools();
  448. // Watch for module loader unload. Fires when the tools are reloaded.
  449. unload(function () {
  450. gDevTools._teardown();
  451. });