blob: 8206ed882f728726298d9472a713b82507bb749f [file] [log] [blame]
Blink Reformat4c46d092018-04-07 15:32:371/*
2 * Copyright (C) 2006, 2007, 2008 Apple Inc. All rights reserved.
3 * Copyright (C) 2007 Matt Lilek ([email protected]).
4 * Copyright (C) 2009 Joseph Pecoraro
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
16 * its contributors may be used to endorse or promote products derived
17 * from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
20 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
23 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
24 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
26 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/**
32 * @unrestricted
33 */
34Main.Main = class {
35 /**
36 * @suppressGlobalPropertiesCheck
37 */
38 constructor() {
39 Main.Main._instanceForTest = this;
40 runOnWindowLoad(this._loaded.bind(this));
41 }
42
43 /**
44 * @param {string} label
45 */
46 static time(label) {
47 if (Host.isUnderTest())
48 return;
49 console.time(label);
50 }
51
52 /**
53 * @param {string} label
54 */
55 static timeEnd(label) {
56 if (Host.isUnderTest())
57 return;
58 console.timeEnd(label);
59 }
60
61 async _loaded() {
62 console.timeStamp('Main._loaded');
Pavel Feldman63e89eb2018-11-25 05:47:0963 await Runtime.appStarted();
Blink Reformat4c46d092018-04-07 15:32:3764 Runtime.setPlatform(Host.platform());
65 InspectorFrontendHost.getPreferences(this._gotPreferences.bind(this));
66 }
67
68 /**
69 * @param {!Object<string, string>} prefs
70 */
71 _gotPreferences(prefs) {
72 console.timeStamp('Main._gotPreferences');
73 if (Host.isUnderTest(prefs))
74 self.runtime.useTestBase();
75 this._createSettings(prefs);
76 this._createAppUI();
77 }
78
79 /**
80 * @param {!Object<string, string>} prefs
81 * Note: this function is called from testSettings in Tests.js.
82 */
83 _createSettings(prefs) {
84 this._initializeExperiments();
85 let storagePrefix = '';
86 if (Host.isCustomDevtoolsFrontend())
87 storagePrefix = '__custom__';
88 else if (!Runtime.queryParam('can_dock') && !!Runtime.queryParam('debugFrontend') && !Host.isUnderTest())
89 storagePrefix = '__bundled__';
90
91 let localStorage;
92 if (!Host.isUnderTest() && window.localStorage) {
93 localStorage = new Common.SettingsStorage(
94 window.localStorage, undefined, undefined, () => window.localStorage.clear(), storagePrefix);
95 } else {
96 localStorage = new Common.SettingsStorage({}, undefined, undefined, undefined, storagePrefix);
97 }
98 const globalStorage = new Common.SettingsStorage(
99 prefs, InspectorFrontendHost.setPreference, InspectorFrontendHost.removePreference,
100 InspectorFrontendHost.clearPreferences, storagePrefix);
101 Common.settings = new Common.Settings(globalStorage, localStorage);
102 if (!Host.isUnderTest())
103 new Common.VersionController().updateVersion();
104 }
105
106 _initializeExperiments() {
107 // Keep this sorted alphabetically: both keys and values.
108 Runtime.experiments.register('applyCustomStylesheet', 'Allow custom UI themes');
Alexei Filippovfdfefe02019-03-09 00:33:24109 Runtime.experiments.register('sourcesPrettyPrint', 'Automatically pretty print in the Sources Panel');
Rayan Kanso8fe8ee22019-03-04 14:58:46110 Runtime.experiments.register('backgroundServices', 'Background web platform feature events', true);
Blink Reformat4c46d092018-04-07 15:32:37111 Runtime.experiments.register('blackboxJSFramesOnTimeline', 'Blackbox JavaScript frames on Timeline', true);
Blink Reformat4c46d092018-04-07 15:32:37112 Runtime.experiments.register('emptySourceMapAutoStepping', 'Empty sourcemap auto-stepping');
113 Runtime.experiments.register('inputEventsOnTimelineOverview', 'Input events on Timeline overview', true);
Alexei Filippovfdfefe02019-03-09 00:33:24114 Runtime.experiments.register('liveHeapProfile', 'Live heap profile', true);
Blink Reformat4c46d092018-04-07 15:32:37115 Runtime.experiments.register('nativeHeapProfiler', 'Native memory sampling heap profiler', true);
Blink Reformat4c46d092018-04-07 15:32:37116 Runtime.experiments.register('protocolMonitor', 'Protocol Monitor');
Alexei Filippov6d2eb592018-10-25 21:48:56117 Runtime.experiments.register('samplingHeapProfilerTimeline', 'Sampling heap profiler timeline', true);
Blink Reformat4c46d092018-04-07 15:32:37118 Runtime.experiments.register('sourceDiff', 'Source diff');
Pavel Feldmanc9060ea2018-04-30 04:42:18119 Runtime.experiments.register('splitInDrawer', 'Split in drawer', true);
Joey Arharaef93562019-03-15 23:49:59120 Runtime.experiments.register('spotlight', 'Spotlight', true);
Blink Reformat4c46d092018-04-07 15:32:37121 Runtime.experiments.register('terminalInDrawer', 'Terminal in drawer', true);
122
123 // Timeline
124 Runtime.experiments.register('timelineEventInitiators', 'Timeline: event initiators');
125 Runtime.experiments.register('timelineFlowEvents', 'Timeline: flow events', true);
126 Runtime.experiments.register('timelineInvalidationTracking', 'Timeline: invalidation tracking', true);
Blink Reformat4c46d092018-04-07 15:32:37127 Runtime.experiments.register('timelineShowAllEvents', 'Timeline: show all events', true);
Blink Reformat4c46d092018-04-07 15:32:37128 Runtime.experiments.register('timelineV8RuntimeCallStats', 'Timeline: V8 Runtime Call Stats on Timeline', true);
Alexei Filippov57ccafb2018-08-14 20:59:05129 Runtime.experiments.register('timelineWebGL', 'Timeline: WebGL-based flamechart');
Blink Reformat4c46d092018-04-07 15:32:37130
131 Runtime.experiments.cleanUpStaleExperiments();
Pavel Feldmandb310912019-01-30 00:31:20132 Runtime.experiments.setDefaultExperiments([]);
Alexei Filippovfdfefe02019-03-09 00:33:24133
134 if (Host.isUnderTest() && Runtime.queryParam('test').includes('live-line-level-heap-profile.js'))
135 Runtime.experiments.enableForTest('liveHeapProfile');
Blink Reformat4c46d092018-04-07 15:32:37136 }
137
138 /**
139 * @suppressGlobalPropertiesCheck
140 */
141 async _createAppUI() {
142 Main.Main.time('Main._createAppUI');
143
144 UI.viewManager = new UI.ViewManager();
145
146 // Request filesystems early, we won't create connections until callback is fired. Things will happen in parallel.
147 Persistence.isolatedFileSystemManager = new Persistence.IsolatedFileSystemManager();
148
149 const themeSetting = Common.settings.createSetting('uiTheme', 'default');
150 UI.initializeUIUtils(document, themeSetting);
151 themeSetting.addChangeListener(Components.reload.bind(Components));
152
153 UI.installComponentRootStyles(/** @type {!Element} */ (document.body));
154
155 this._addMainEventListeners(document);
156
157 const canDock = !!Runtime.queryParam('can_dock');
158 UI.zoomManager = new UI.ZoomManager(window, InspectorFrontendHost);
159 UI.inspectorView = UI.InspectorView.instance();
160 UI.ContextMenu.initialize();
161 UI.ContextMenu.installHandler(document);
162 UI.Tooltip.installHandler(document);
163 Components.dockController = new Components.DockController(canDock);
164 SDK.consoleModel = new SDK.ConsoleModel();
165 SDK.multitargetNetworkManager = new SDK.MultitargetNetworkManager();
166 SDK.domDebuggerManager = new SDK.DOMDebuggerManager();
167 SDK.targetManager.addEventListener(
168 SDK.TargetManager.Events.SuspendStateChanged, this._onSuspendStateChanged.bind(this));
169
170 UI.shortcutsScreen = new UI.ShortcutsScreen();
171 // set order of some sections explicitly
172 UI.shortcutsScreen.section(Common.UIString('Elements Panel'));
173 UI.shortcutsScreen.section(Common.UIString('Styles Pane'));
174 UI.shortcutsScreen.section(Common.UIString('Debugger'));
175 UI.shortcutsScreen.section(Common.UIString('Console'));
176
177 Workspace.fileManager = new Workspace.FileManager();
178 Workspace.workspace = new Workspace.Workspace();
179
180 Bindings.networkProjectManager = new Bindings.NetworkProjectManager();
181 Bindings.resourceMapping = new Bindings.ResourceMapping(SDK.targetManager, Workspace.workspace);
182 new Bindings.PresentationConsoleMessageManager();
183 Bindings.cssWorkspaceBinding = new Bindings.CSSWorkspaceBinding(SDK.targetManager, Workspace.workspace);
184 Bindings.debuggerWorkspaceBinding = new Bindings.DebuggerWorkspaceBinding(SDK.targetManager, Workspace.workspace);
185 Bindings.breakpointManager =
186 new Bindings.BreakpointManager(Workspace.workspace, SDK.targetManager, Bindings.debuggerWorkspaceBinding);
187 Extensions.extensionServer = new Extensions.ExtensionServer();
188
189 new Persistence.FileSystemWorkspaceBinding(Persistence.isolatedFileSystemManager, Workspace.workspace);
190 Persistence.persistence = new Persistence.Persistence(Workspace.workspace, Bindings.breakpointManager);
191 Persistence.networkPersistenceManager = new Persistence.NetworkPersistenceManager(Workspace.workspace);
192
193 new Main.ExecutionContextSelector(SDK.targetManager, UI.context);
194 Bindings.blackboxManager = new Bindings.BlackboxManager(Bindings.debuggerWorkspaceBinding);
195
196 new Main.Main.PauseListener();
197
198 UI.actionRegistry = new UI.ActionRegistry();
199 UI.shortcutRegistry = new UI.ShortcutRegistry(UI.actionRegistry, document);
200 UI.ShortcutsScreen.registerShortcuts();
201 this._registerForwardedShortcuts();
202 this._registerMessageSinkListener();
203
204 Main.Main.timeEnd('Main._createAppUI');
205 this._showAppUI(await self.runtime.extension(Common.AppProvider).instance());
206 }
207
208 /**
209 * @param {!Object} appProvider
210 * @suppressGlobalPropertiesCheck
211 */
212 _showAppUI(appProvider) {
213 Main.Main.time('Main._showAppUI');
214 const app = /** @type {!Common.AppProvider} */ (appProvider).createApp();
215 // It is important to kick controller lifetime after apps are instantiated.
216 Components.dockController.initialize();
217 app.presentUI(document);
218
219 const toggleSearchNodeAction = UI.actionRegistry.action('elements.toggle-element-search');
220 // TODO: we should not access actions from other modules.
221 if (toggleSearchNodeAction) {
222 InspectorFrontendHost.events.addEventListener(
223 InspectorFrontendHostAPI.Events.EnterInspectElementMode,
224 toggleSearchNodeAction.execute.bind(toggleSearchNodeAction), this);
225 }
226 InspectorFrontendHost.events.addEventListener(
227 InspectorFrontendHostAPI.Events.RevealSourceLine, this._revealSourceLine, this);
228
229 UI.inspectorView.createToolbars();
230 InspectorFrontendHost.loadCompleted();
231
232 const extensions = self.runtime.extensions(Common.QueryParamHandler);
233 for (const extension of extensions) {
234 const value = Runtime.queryParam(extension.descriptor()['name']);
235 if (value !== null)
236 extension.instance().then(handleQueryParam.bind(null, value));
237 }
238
239 /**
240 * @param {string} value
241 * @param {!Common.QueryParamHandler} handler
242 */
243 function handleQueryParam(value, handler) {
244 handler.handleQueryParam(value);
245 }
246
247 // Allow UI cycles to repaint prior to creating connection.
248 setTimeout(this._initializeTarget.bind(this), 0);
249 Main.Main.timeEnd('Main._showAppUI');
250 }
251
252 async _initializeTarget() {
253 Main.Main.time('Main._initializeTarget');
254 const instances =
255 await Promise.all(self.runtime.extensions('early-initialization').map(extension => extension.instance()));
256 for (const instance of instances)
Pavel Feldman07ef9722018-12-13 23:52:22257 await /** @type {!Common.Runnable} */ (instance).run();
Blink Reformat4c46d092018-04-07 15:32:37258 // Used for browser tests.
259 InspectorFrontendHost.readyForTest();
260 // Asynchronously run the extensions.
261 setTimeout(this._lateInitialization.bind(this), 100);
262 Main.Main.timeEnd('Main._initializeTarget');
263 }
264
265 _lateInitialization() {
266 Main.Main.time('Main._lateInitialization');
267 this._registerShortcuts();
268 Extensions.extensionServer.initializeExtensions();
Alexei Filippov19be5102019-04-16 20:40:24269 const extensions = self.runtime.extensions('late-initialization');
270 const promises = [];
271 for (const extension of extensions) {
272 const setting = extension.descriptor()['setting'];
273 if (!setting || Common.settings.moduleSetting(setting).get()) {
274 promises.push(extension.instance().then(instance => (/** @type {!Common.Runnable} */ (instance)).run()));
275 continue;
276 }
277 /**
278 * @param {!Common.Event} event
279 */
280 async function changeListener(event) {
281 if (!event.data)
282 return;
283 Common.settings.moduleSetting(setting).removeChangeListener(changeListener);
284 (/** @type {!Common.Runnable} */ (await extension.instance())).run();
285 }
286 Common.settings.moduleSetting(setting).addChangeListener(changeListener);
287 }
288 this._lateInitDonePromise = Promise.all(promises);
Blink Reformat4c46d092018-04-07 15:32:37289 Main.Main.timeEnd('Main._lateInitialization');
290 }
291
Alexei Filippov19be5102019-04-16 20:40:24292 /**
293 * @return {!Promise}
294 */
295 lateInitDonePromiseForTest() {
296 return this._lateInitDonePromise;
297 }
298
Blink Reformat4c46d092018-04-07 15:32:37299 _registerForwardedShortcuts() {
300 /** @const */ const forwardedActions = [
301 'main.toggle-dock', 'debugger.toggle-breakpoints-active', 'debugger.toggle-pause', 'commandMenu.show',
302 'console.show'
303 ];
304 const actionKeys =
305 UI.shortcutRegistry.keysForActions(forwardedActions).map(UI.KeyboardShortcut.keyCodeAndModifiersFromKey);
306 InspectorFrontendHost.setWhitelistedShortcuts(JSON.stringify(actionKeys));
307 }
308
309 _registerMessageSinkListener() {
310 Common.console.addEventListener(Common.Console.Events.MessageAdded, messageAdded);
311
312 /**
313 * @param {!Common.Event} event
314 */
315 function messageAdded(event) {
316 const message = /** @type {!Common.Console.Message} */ (event.data);
317 if (message.show)
318 Common.console.show();
319 }
320 }
321
322 /**
323 * @param {!Common.Event} event
324 */
325 _revealSourceLine(event) {
326 const url = /** @type {string} */ (event.data['url']);
327 const lineNumber = /** @type {number} */ (event.data['lineNumber']);
328 const columnNumber = /** @type {number} */ (event.data['columnNumber']);
329
330 const uiSourceCode = Workspace.workspace.uiSourceCodeForURL(url);
331 if (uiSourceCode) {
332 Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber));
333 return;
334 }
335
336 /**
337 * @param {!Common.Event} event
338 */
339 function listener(event) {
340 const uiSourceCode = /** @type {!Workspace.UISourceCode} */ (event.data);
341 if (uiSourceCode.url() === url) {
342 Common.Revealer.reveal(uiSourceCode.uiLocation(lineNumber, columnNumber));
343 Workspace.workspace.removeEventListener(Workspace.Workspace.Events.UISourceCodeAdded, listener);
344 }
345 }
346
347 Workspace.workspace.addEventListener(Workspace.Workspace.Events.UISourceCodeAdded, listener);
348 }
349
350 _registerShortcuts() {
351 const shortcut = UI.KeyboardShortcut;
352 const section = UI.shortcutsScreen.section(Common.UIString('All Panels'));
353 let keys = [
354 shortcut.makeDescriptor('[', shortcut.Modifiers.CtrlOrMeta),
355 shortcut.makeDescriptor(']', shortcut.Modifiers.CtrlOrMeta)
356 ];
357 section.addRelatedKeys(keys, Common.UIString('Go to the panel to the left/right'));
358
359 const toggleConsoleLabel = Common.UIString('Show console');
360 section.addKey(shortcut.makeDescriptor(shortcut.Keys.Tilde, shortcut.Modifiers.Ctrl), toggleConsoleLabel);
361 section.addKey(shortcut.makeDescriptor(shortcut.Keys.Esc), Common.UIString('Toggle drawer'));
362 if (Components.dockController.canDock()) {
363 section.addKey(
364 shortcut.makeDescriptor('M', shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift),
365 Common.UIString('Toggle device mode'));
366 section.addKey(
367 shortcut.makeDescriptor('D', shortcut.Modifiers.CtrlOrMeta | shortcut.Modifiers.Shift),
368 Common.UIString('Toggle dock side'));
369 }
370 section.addKey(shortcut.makeDescriptor('f', shortcut.Modifiers.CtrlOrMeta), Common.UIString('Search'));
371
372 const advancedSearchShortcutModifier = Host.isMac() ?
373 UI.KeyboardShortcut.Modifiers.Meta | UI.KeyboardShortcut.Modifiers.Alt :
374 UI.KeyboardShortcut.Modifiers.Ctrl | UI.KeyboardShortcut.Modifiers.Shift;
375 const advancedSearchShortcut = shortcut.makeDescriptor('f', advancedSearchShortcutModifier);
376 section.addKey(advancedSearchShortcut, Common.UIString('Search across all sources'));
377
378 const inspectElementModeShortcuts =
379 UI.shortcutRegistry.shortcutDescriptorsForAction('elements.toggle-element-search');
380 if (inspectElementModeShortcuts.length)
381 section.addKey(inspectElementModeShortcuts[0], Common.UIString('Select node to inspect'));
382
383 const openResourceShortcut = UI.KeyboardShortcut.makeDescriptor('p', UI.KeyboardShortcut.Modifiers.CtrlOrMeta);
384 section.addKey(openResourceShortcut, Common.UIString('Go to source'));
385
386 if (Host.isMac()) {
387 keys = [
388 shortcut.makeDescriptor('g', shortcut.Modifiers.Meta),
389 shortcut.makeDescriptor('g', shortcut.Modifiers.Meta | shortcut.Modifiers.Shift)
390 ];
391 section.addRelatedKeys(keys, Common.UIString('Find next/previous'));
392 }
393 }
394
395 _postDocumentKeyDown(event) {
Joel Einbindera66e5bf2018-05-31 01:26:37396 if (!event.handled)
397 UI.shortcutRegistry.handleShortcut(event);
Blink Reformat4c46d092018-04-07 15:32:37398 }
399
400 /**
401 * @param {!Event} event
402 */
403 _redispatchClipboardEvent(event) {
404 const eventCopy = new CustomEvent('clipboard-' + event.type, {bubbles: true});
405 eventCopy['original'] = event;
406 const document = event.target && event.target.ownerDocument;
407 const target = document ? document.deepActiveElement() : null;
408 if (target)
409 target.dispatchEvent(eventCopy);
410 if (eventCopy.handled)
411 event.preventDefault();
412 }
413
414 _contextMenuEventFired(event) {
415 if (event.handled || event.target.classList.contains('popup-glasspane'))
416 event.preventDefault();
417 }
418
419 /**
420 * @param {!Document} document
421 */
422 _addMainEventListeners(document) {
423 document.addEventListener('keydown', this._postDocumentKeyDown.bind(this), false);
424 document.addEventListener('beforecopy', this._redispatchClipboardEvent.bind(this), true);
425 document.addEventListener('copy', this._redispatchClipboardEvent.bind(this), false);
426 document.addEventListener('cut', this._redispatchClipboardEvent.bind(this), false);
427 document.addEventListener('paste', this._redispatchClipboardEvent.bind(this), false);
428 document.addEventListener('contextmenu', this._contextMenuEventFired.bind(this), true);
429 }
430
431 _onSuspendStateChanged() {
432 const suspended = SDK.targetManager.allTargetsSuspended();
433 UI.inspectorView.onSuspendStateChanged(suspended);
434 }
435};
436
437/**
438 * @implements {UI.ActionDelegate}
439 * @unrestricted
440 */
441Main.Main.ZoomActionDelegate = class {
442 /**
443 * @override
444 * @param {!UI.Context} context
445 * @param {string} actionId
446 * @return {boolean}
447 */
448 handleAction(context, actionId) {
449 if (InspectorFrontendHost.isHostedMode())
450 return false;
451
452 switch (actionId) {
453 case 'main.zoom-in':
454 InspectorFrontendHost.zoomIn();
455 return true;
456 case 'main.zoom-out':
457 InspectorFrontendHost.zoomOut();
458 return true;
459 case 'main.zoom-reset':
460 InspectorFrontendHost.resetZoom();
461 return true;
462 }
463 return false;
464 }
465};
466
467/**
468 * @implements {UI.ActionDelegate}
469 * @unrestricted
470 */
471Main.Main.SearchActionDelegate = class {
472 /**
473 * @override
474 * @param {!UI.Context} context
475 * @param {string} actionId
476 * @return {boolean}
477 * @suppressGlobalPropertiesCheck
478 */
479 handleAction(context, actionId) {
480 const searchableView = UI.SearchableView.fromElement(document.deepActiveElement()) ||
481 UI.inspectorView.currentPanelDeprecated().searchableView();
482 if (!searchableView)
483 return false;
484 switch (actionId) {
485 case 'main.search-in-panel.find':
486 return searchableView.handleFindShortcut();
487 case 'main.search-in-panel.cancel':
488 return searchableView.handleCancelSearchShortcut();
489 case 'main.search-in-panel.find-next':
490 return searchableView.handleFindNextShortcut();
491 case 'main.search-in-panel.find-previous':
492 return searchableView.handleFindPreviousShortcut();
493 }
494 return false;
495 }
496};
497
498/**
499 * @implements {UI.ToolbarItem.Provider}
500 */
501Main.Main.MainMenuItem = class {
502 constructor() {
503 this._item = new UI.ToolbarMenuButton(this._handleContextMenu.bind(this), true);
504 this._item.setTitle(Common.UIString('Customize and control DevTools'));
505 }
506
507 /**
508 * @override
509 * @return {?UI.ToolbarItem}
510 */
511 item() {
512 return this._item;
513 }
514
515 /**
516 * @param {!UI.ContextMenu} contextMenu
517 */
518 _handleContextMenu(contextMenu) {
519 if (Components.dockController.canDock()) {
520 const dockItemElement = createElementWithClass('div', 'flex-centered flex-auto');
Joel Einbinder57b9fad2019-02-08 23:31:35521 dockItemElement.tabIndex = -1;
Blink Reformat4c46d092018-04-07 15:32:37522 const titleElement = dockItemElement.createChild('span', 'flex-auto');
523 titleElement.textContent = Common.UIString('Dock side');
524 const toggleDockSideShorcuts = UI.shortcutRegistry.shortcutDescriptorsForAction('main.toggle-dock');
525 titleElement.title = Common.UIString(
526 'Placement of DevTools relative to the page. (%s to restore last position)', toggleDockSideShorcuts[0].name);
527 dockItemElement.appendChild(titleElement);
528 const dockItemToolbar = new UI.Toolbar('', dockItemElement);
Joel Einbinder9a6bead2018-08-06 18:02:35529 if (Host.isMac() && !UI.themeSupport.hasTheme())
530 dockItemToolbar.makeBlueOnHover();
Blink Reformat4c46d092018-04-07 15:32:37531 const undock = new UI.ToolbarToggle(Common.UIString('Undock into separate window'), 'largeicon-undock');
532 const bottom = new UI.ToolbarToggle(Common.UIString('Dock to bottom'), 'largeicon-dock-to-bottom');
533 const right = new UI.ToolbarToggle(Common.UIString('Dock to right'), 'largeicon-dock-to-right');
534 const left = new UI.ToolbarToggle(Common.UIString('Dock to left'), 'largeicon-dock-to-left');
535 undock.addEventListener(UI.ToolbarButton.Events.MouseDown, event => event.data.consume());
536 bottom.addEventListener(UI.ToolbarButton.Events.MouseDown, event => event.data.consume());
537 right.addEventListener(UI.ToolbarButton.Events.MouseDown, event => event.data.consume());
538 left.addEventListener(UI.ToolbarButton.Events.MouseDown, event => event.data.consume());
539 undock.addEventListener(
Joel Einbinder57b9fad2019-02-08 23:31:35540 UI.ToolbarButton.Events.Click, setDockSide.bind(null, Components.DockController.State.Undocked));
Blink Reformat4c46d092018-04-07 15:32:37541 bottom.addEventListener(
Joel Einbinder57b9fad2019-02-08 23:31:35542 UI.ToolbarButton.Events.Click, setDockSide.bind(null, Components.DockController.State.DockedToBottom));
Blink Reformat4c46d092018-04-07 15:32:37543 right.addEventListener(
Joel Einbinder57b9fad2019-02-08 23:31:35544 UI.ToolbarButton.Events.Click, setDockSide.bind(null, Components.DockController.State.DockedToRight));
Blink Reformat4c46d092018-04-07 15:32:37545 left.addEventListener(
Joel Einbinder57b9fad2019-02-08 23:31:35546 UI.ToolbarButton.Events.Click, setDockSide.bind(null, Components.DockController.State.DockedToLeft));
Blink Reformat4c46d092018-04-07 15:32:37547 undock.setToggled(Components.dockController.dockSide() === Components.DockController.State.Undocked);
548 bottom.setToggled(Components.dockController.dockSide() === Components.DockController.State.DockedToBottom);
549 right.setToggled(Components.dockController.dockSide() === Components.DockController.State.DockedToRight);
550 left.setToggled(Components.dockController.dockSide() === Components.DockController.State.DockedToLeft);
551 dockItemToolbar.appendToolbarItem(undock);
552 dockItemToolbar.appendToolbarItem(left);
553 dockItemToolbar.appendToolbarItem(bottom);
554 dockItemToolbar.appendToolbarItem(right);
Joel Einbinder57b9fad2019-02-08 23:31:35555 dockItemElement.addEventListener('keydown', event => {
556 let dir = 0;
557 if (event.key === 'ArrowLeft')
558 dir = -1;
559 else if (event.key === 'ArrowRight')
560 dir = 1;
561 else
562 return;
563
564 const buttons = [undock, left, bottom, right];
565 let index = buttons.findIndex(button => button.element.hasFocus());
566 index = Number.constrain(index + dir, 0, buttons.length - 1);
567
568 buttons[index].element.focus();
569 event.consume(true);
570 });
Blink Reformat4c46d092018-04-07 15:32:37571 contextMenu.headerSection().appendCustomItem(dockItemElement);
572 }
573
574 /**
575 * @param {string} side
576 */
577 function setDockSide(side) {
578 Components.dockController.setDockSide(side);
579 contextMenu.discard();
580 }
581
582 if (Components.dockController.dockSide() === Components.DockController.State.Undocked &&
Dmitry Gozmanb24fcc22018-10-31 23:42:42583 SDK.targetManager.mainTarget() && SDK.targetManager.mainTarget().type() === SDK.Target.Type.Frame)
Blink Reformat4c46d092018-04-07 15:32:37584 contextMenu.defaultSection().appendAction('inspector_main.focus-debuggee', Common.UIString('Focus debuggee'));
585
586 contextMenu.defaultSection().appendAction(
587 'main.toggle-drawer',
588 UI.inspectorView.drawerVisible() ? Common.UIString('Hide console drawer') :
589 Common.UIString('Show console drawer'));
590 contextMenu.appendItemsAtLocation('mainMenu');
591 const moreTools = contextMenu.defaultSection().appendSubMenuItem(Common.UIString('More tools'));
592 const extensions = self.runtime.extensions('view', undefined, true);
593 for (const extension of extensions) {
594 const descriptor = extension.descriptor();
595 if (descriptor['persistence'] !== 'closeable')
596 continue;
597 if (descriptor['location'] !== 'drawer-view' && descriptor['location'] !== 'panel')
598 continue;
599 moreTools.defaultSection().appendItem(
600 extension.title(), UI.viewManager.showView.bind(UI.viewManager, descriptor['id']));
601 }
602
603 const helpSubMenu = contextMenu.footerSection().appendSubMenuItem(Common.UIString('Help'));
604 helpSubMenu.appendItemsAtLocation('mainMenuHelp');
605 }
606};
607
608/**
609 * @unrestricted
610 */
611Main.Main.PauseListener = class {
612 constructor() {
613 SDK.targetManager.addModelListener(
614 SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
615 }
616
617 /**
618 * @param {!Common.Event} event
619 */
620 _debuggerPaused(event) {
621 SDK.targetManager.removeModelListener(
622 SDK.DebuggerModel, SDK.DebuggerModel.Events.DebuggerPaused, this._debuggerPaused, this);
623 const debuggerModel = /** @type {!SDK.DebuggerModel} */ (event.data);
624 const debuggerPausedDetails = debuggerModel.debuggerPausedDetails();
625 UI.context.setFlavor(SDK.Target, debuggerModel.target());
626 Common.Revealer.reveal(debuggerPausedDetails);
627 }
628};
629
630/**
631 * @param {string} method
632 * @param {?Object} params
633 * @return {!Promise}
634 */
635Main.sendOverProtocol = function(method, params) {
636 return new Promise((resolve, reject) => {
Dmitry Gozman99d7a6c2018-11-12 17:55:11637 Protocol.test.sendRawMessage(method, params, (err, ...results) => {
Blink Reformat4c46d092018-04-07 15:32:37638 if (err)
639 return reject(err);
640 return resolve(results);
641 });
642 });
643};
644
645/**
646 * @implements {UI.ActionDelegate}
647 * @unrestricted
648 */
649Main.ReloadActionDelegate = class {
650 /**
651 * @override
652 * @param {!UI.Context} context
653 * @param {string} actionId
654 * @return {boolean}
655 */
656 handleAction(context, actionId) {
657 switch (actionId) {
658 case 'main.debug-reload':
659 Components.reload();
660 return true;
661 }
662 return false;
663 }
664};
665
666new Main.Main();