local-tab-commands-factory.js (2300B)
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 5 "use strict"; 6 7 loader.lazyRequireGetter( 8 this, 9 "CommandsFactory", 10 "resource://devtools/shared/commands/commands-factory.js", 11 true 12 ); 13 14 // Map of existing Commands objects, keyed by XULTab. 15 const commandsMap = new WeakMap(); 16 17 /** 18 * Functions for creating unique Commands for Local Tabs. 19 */ 20 exports.LocalTabCommandsFactory = { 21 /** 22 * Create a unique commands object for the given tab. 23 * 24 * If a commands was already created by this factory for the provided tab, 25 * it will be returned and no new commands created. 26 * 27 * Otherwise, this will automatically: 28 * - spawn a DevToolsServer in the parent process, 29 * - create a DevToolsClient 30 * - connect the DevToolsClient to the DevToolsServer 31 * - call RootActor's `getTab` request to retrieve the WindowGlobalTargetActor's form 32 * 33 * @param {XULTab} tab 34 * The tab to use in creating a new commands. 35 * 36 * @return {Commands object} The commands object for the provided tab. 37 */ 38 async createCommandsForTab(tab) { 39 let commands = commandsMap.get(tab); 40 if (commands) { 41 // Keep in mind that commands can be either a promise 42 // or a commands object. 43 return commands; 44 } 45 46 const promise = CommandsFactory.forTab(tab); 47 // Immediately set the commands's promise in cache to prevent race 48 commandsMap.set(tab, promise); 49 commands = await promise; 50 // Then replace the promise with the commands object 51 commandsMap.set(tab, commands); 52 53 commands.descriptorFront.once("descriptor-destroyed", () => { 54 commandsMap.delete(tab); 55 }); 56 return commands; 57 }, 58 59 /** 60 * Retrieve an existing commands created by this factory for the provided 61 * tab. Returns null if no commands was created yet. 62 * 63 * @param {XULTab} tab 64 * The tab for which the commands should be retrieved 65 */ 66 async getCommandsForTab(tab) { 67 // commandsMap.get(tab) can either return an initialized commands, a promise 68 // which will resolve a commands, or null if no commands was ever created 69 // for this tab. 70 return commandsMap.get(tab); 71 }, 72 };