forked from ChromeDevTools/devtools-frontend
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathInspectorMain.ts
More file actions
351 lines (304 loc) · 14.1 KB
/
Copy pathInspectorMain.ts
File metadata and controls
351 lines (304 loc) · 14.1 KB
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
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Root from '../../core/root/root.js';
import * as SDK from '../../core/sdk/sdk.js';
import type * as Protocol from '../../generated/protocol.js';
import * as MobileThrottling from '../../panels/mobile_throttling/mobile_throttling.js';
import * as Security from '../../panels/security/security.js';
import * as Components from '../../ui/legacy/components/utils/utils.js';
import * as UI from '../../ui/legacy/legacy.js';
import nodeIconStyles from './nodeIcon.css.js';
const MS_BETWEEN_ROUNDTRIP_MEASUREMENTS = 3000;
const MS_MAX_LOW_ROUNDTRIP = 200;
const UIStrings = {
/**
* @description Text that refers to the main target. The main target is the primary webpage that
* DevTools is connected to. This text is used in various places in the UI as a label/name to inform
* the user which target/webpage they are currently connected to, as DevTools may connect to multiple
* targets at the same time in some scenarios.
*/
main: 'Main',
/**
* @description Text that refers to the tab target. The tab target is the Chrome tab that
* DevTools is connected to. This text is used in various places in the UI as a label/name to inform
* the user which target they are currently connected to, as DevTools may connect to multiple
* targets at the same time in some scenarios.
* @meaning Tab target that's different than the "Tab" of Chrome. (See b/343009012)
*/
tab: 'Tab',
/**
* @description A warning shown to the user when JavaScript is disabled on the webpage that
* DevTools is connected to.
*/
javascriptIsDisabled: 'JavaScript is disabled',
/**
* @description A message that prompts the user to open devtools for a specific environment (Node.js)
*/
openDedicatedTools: 'Open dedicated DevTools for `Node.js`',
} as const;
const str_ = i18n.i18n.registerUIStrings('entrypoints/inspector_main/InspectorMain.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
let inspectorMainImplInstance: InspectorMainImpl;
export class InspectorMainImpl implements Common.Runnable.Runnable {
#consecutiveLowRoundtrips = 0;
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): InspectorMainImpl {
const {forceNew} = opts;
if (!inspectorMainImplInstance || forceNew) {
inspectorMainImplInstance = new InspectorMainImpl();
}
return inspectorMainImplInstance;
}
async #measureMainConnectionRoundtrip(debuggerModel: SDK.DebuggerModel.DebuggerModel): Promise<void> {
if (!debuggerModel.debuggerEnabled()) {
return;
}
const startMs = Date.now();
// Issues and waits for a response from a simple "Debugger.enable" when the debugger is enabled
// which noops and retuns a truthy response:
// https://github.com/facebook/hermes/blob/ae235193b9329867afaa2838183cbffa34aca098/API/hermes/cdp/DebuggerDomainAgent.cpp#L224-L228
// https://github.com/facebook/hermes/blob/ae235193b9329867afaa2838183cbffa34aca098/API/hermes/cdp/DebuggerDomainAgent.cpp#L183-L185
// It measures the round trip time for CDP message after being queued in the CDP queue in each direction.
await debuggerModel.syncDebuggerId();
const roundtripTime = Date.now() - startMs;
if (roundtripTime > MS_MAX_LOW_ROUNDTRIP) {
this.#consecutiveLowRoundtrips = 0;
} else {
this.#consecutiveLowRoundtrips++;
}
let reportedLowRoundrip = false;
if (this.#consecutiveLowRoundtrips >= 2) {
reportedLowRoundrip = Host.rnPerfMetrics.tryReportingCdpLowRoundtrip(
Math.round(performance.now() - ((this.#consecutiveLowRoundtrips - 1) * MS_BETWEEN_ROUNDTRIP_MEASUREMENTS))
);
}
if (!reportedLowRoundrip) {
setTimeout(() => {
void this.#measureMainConnectionRoundtrip(debuggerModel);
}, MS_BETWEEN_ROUNDTRIP_MEASUREMENTS);
}
}
async run(): Promise<void> {
let firstCall = true;
await SDK.Connections.initMainConnection(async () => {
const type = Root.Runtime.Runtime.queryParam('v8only') ?
SDK.Target.Type.NODE :
(Root.Runtime.Runtime.queryParam('targetType') === 'tab' ? SDK.Target.Type.TAB : SDK.Target.Type.FRAME);
// TODO(crbug.com/1348385): support waiting for debugger with tab target.
const waitForDebuggerInPage =
type === SDK.Target.Type.FRAME && Root.Runtime.Runtime.queryParam('panel') === 'sources';
const name = type === SDK.Target.Type.FRAME ? i18nString(UIStrings.main) : i18nString(UIStrings.tab);
const target = SDK.TargetManager.TargetManager.instance().createTarget(
'main', name, type, null, undefined, waitForDebuggerInPage);
const waitForPrimaryPageTarget = (): Promise<SDK.Target.Target> => {
return new Promise(resolve => {
const targetManager = SDK.TargetManager.TargetManager.instance();
targetManager.observeTargets({
targetAdded: (target: SDK.Target.Target): void => {
if (target === targetManager.primaryPageTarget()) {
target.setName(i18nString(UIStrings.main));
resolve(target);
}
},
targetRemoved: (_: unknown): void => {},
});
});
};
await waitForPrimaryPageTarget();
// Only resume target during the first connection,
// subsequent connections are due to connection hand-over,
// there is no need to pause in debugger.
if (!firstCall) {
return;
}
firstCall = false;
const debuggerModel = target.model(SDK.DebuggerModel.DebuggerModel);
if (debuggerModel) {
void this.#measureMainConnectionRoundtrip(debuggerModel);
if (waitForDebuggerInPage) {
if (!debuggerModel.isReadyToPause()) {
await debuggerModel.once(SDK.DebuggerModel.Events.DebuggerIsReadyToPause);
}
debuggerModel.pause();
}
}
if (type !== SDK.Target.Type.TAB) {
void target.runtimeAgent().invoke_runIfWaitingForDebugger();
}
}, Components.TargetDetachedDialog.TargetDetachedDialog.connectionLost);
new SourcesPanelIndicator();
new BackendSettingsSync();
new MobileThrottling.NetworkPanelIndicator.NetworkPanelIndicator();
Host.InspectorFrontendHost.InspectorFrontendHostInstance.events.addEventListener(
Host.InspectorFrontendHostAPI.Events.ReloadInspectedPage, ({data: hard}) => {
SDK.ResourceTreeModel.ResourceTreeModel.reloadAllPages(hard);
});
// Skip possibly showing the cookie control reload banner if devtools UI is not enabled or if there is an enterprise policy blocking third party cookies
if (!Root.Runtime.hostConfig.devToolsPrivacyUI?.enabled ||
Root.Runtime.hostConfig.thirdPartyCookieControls?.managedBlockThirdPartyCookies === true) {
return;
}
// Third party cookie control settings according to the browser
const browserCookieControls = Root.Runtime.hostConfig.thirdPartyCookieControls;
// Devtools cookie controls settings
const cookieControlOverrideSetting =
Common.Settings.Settings.instance().createSetting('cookie-control-override-enabled', undefined);
const gracePeriodMitigationDisabledSetting =
Common.Settings.Settings.instance().createSetting('grace-period-mitigation-disabled', undefined);
const heuristicMitigationDisabledSetting =
Common.Settings.Settings.instance().createSetting('heuristic-mitigation-disabled', undefined);
// If there are saved cookie control settings, check to see if they differ from the browser config. If they do, prompt a page reload so the user will see the cookie controls behavior.
if (cookieControlOverrideSetting.get() !== undefined) {
if (browserCookieControls?.thirdPartyCookieRestrictionEnabled !== cookieControlOverrideSetting.get()) {
Security.CookieControlsView.showInfobar();
return;
}
// If the devtools third-party cookie control is active, we also need to check if there's a discrepancy in the mitigation behavior.
if (cookieControlOverrideSetting.get()) {
if (browserCookieControls?.thirdPartyCookieMetadataEnabled === gracePeriodMitigationDisabledSetting.get()) {
Security.CookieControlsView.showInfobar();
return;
}
if (browserCookieControls?.thirdPartyCookieHeuristicsEnabled === heuristicMitigationDisabledSetting.get()) {
Security.CookieControlsView.showInfobar();
return;
}
}
}
}
}
Common.Runnable.registerEarlyInitializationRunnable(InspectorMainImpl.instance);
export class ReloadActionDelegate implements UI.ActionRegistration.ActionDelegate {
handleAction(_context: UI.Context.Context, actionId: string): boolean {
const isReactNative = Root.Runtime.experiments.isEnabled(
Root.Runtime.ExperimentName.REACT_NATIVE_SPECIFIC_UI,
);
// [RN] Fork reload handling. React Native targets do not initialize
// ResourceTreeModel (Capability.DOM), and there is no hard reload concept.
if (isReactNative) {
switch (actionId) {
case 'inspector-main.reload':
case 'inspector-main.hard-reload': {
const mainTarget = SDK.TargetManager.TargetManager.instance().primaryPageTarget();
if (!mainTarget) {
return false;
}
void mainTarget.pageAgent().invoke_reload({ignoreCache: true});
return true;
}
}
}
switch (actionId) {
case 'inspector-main.reload':
SDK.ResourceTreeModel.ResourceTreeModel.reloadAllPages(false);
return true;
case 'inspector-main.hard-reload':
SDK.ResourceTreeModel.ResourceTreeModel.reloadAllPages(true);
return true;
}
return false;
}
}
export class FocusDebuggeeActionDelegate implements UI.ActionRegistration.ActionDelegate {
handleAction(_context: UI.Context.Context, _actionId: string): boolean {
const mainTarget = SDK.TargetManager.TargetManager.instance().primaryPageTarget();
if (!mainTarget) {
return false;
}
void mainTarget.pageAgent().invoke_bringToFront();
return true;
}
}
let nodeIndicatorInstance: NodeIndicator;
export class NodeIndicator implements UI.Toolbar.Provider {
readonly #element: Element;
readonly #button: UI.Toolbar.ToolbarItem;
private constructor() {
const element = document.createElement('div');
const shadowRoot = UI.UIUtils.createShadowRootWithCoreStyles(element, {cssFile: nodeIconStyles});
this.#element = shadowRoot.createChild('div', 'node-icon');
element.addEventListener(
'click', () => Host.InspectorFrontendHost.InspectorFrontendHostInstance.openNodeFrontend(), false);
this.#button = new UI.Toolbar.ToolbarItem(element);
this.#button.setTitle(i18nString(UIStrings.openDedicatedTools));
SDK.TargetManager.TargetManager.instance().addEventListener(
SDK.TargetManager.Events.AVAILABLE_TARGETS_CHANGED, event => this.#update(event.data));
this.#button.setVisible(false);
this.#update([]);
}
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): NodeIndicator {
const {forceNew} = opts;
if (!nodeIndicatorInstance || forceNew) {
nodeIndicatorInstance = new NodeIndicator();
}
return nodeIndicatorInstance;
}
#update(targetInfos: Protocol.Target.TargetInfo[]): void {
const hasNode = Boolean(targetInfos.find(target => target.type === 'node' && !target.attached));
this.#element.classList.toggle('inactive', !hasNode);
if (hasNode) {
this.#button.setVisible(true);
}
}
item(): UI.Toolbar.ToolbarItem|null {
return this.#button;
}
}
export class SourcesPanelIndicator {
constructor() {
Common.Settings.Settings.instance()
.moduleSetting('java-script-disabled')
.addChangeListener(javaScriptDisabledChanged);
javaScriptDisabledChanged();
function javaScriptDisabledChanged(): void {
const warnings = [];
if (Common.Settings.Settings.instance().moduleSetting('java-script-disabled').get()) {
warnings.push(i18nString(UIStrings.javascriptIsDisabled));
}
UI.InspectorView.InspectorView.instance().setPanelWarnings('sources', warnings);
}
}
}
export class BackendSettingsSync implements SDK.TargetManager.Observer {
readonly #autoAttachSetting: Common.Settings.Setting<boolean>;
readonly #adBlockEnabledSetting: Common.Settings.Setting<boolean>;
readonly #emulatePageFocusSetting: Common.Settings.Setting<boolean>;
constructor() {
this.#autoAttachSetting = Common.Settings.Settings.instance().moduleSetting('auto-attach-to-created-pages');
this.#autoAttachSetting.addChangeListener(this.#updateAutoAttach, this);
this.#updateAutoAttach();
this.#adBlockEnabledSetting = Common.Settings.Settings.instance().moduleSetting('network.ad-blocking-enabled');
this.#adBlockEnabledSetting.addChangeListener(this.#update, this);
this.#emulatePageFocusSetting = Common.Settings.Settings.instance().moduleSetting('emulate-page-focus');
this.#emulatePageFocusSetting.addChangeListener(this.#update, this);
SDK.TargetManager.TargetManager.instance().observeTargets(this);
}
#updateTarget(target: SDK.Target.Target): void {
if (target.type() !== SDK.Target.Type.FRAME || target.parentTarget()?.type() === SDK.Target.Type.FRAME) {
return;
}
void target.pageAgent().invoke_setAdBlockingEnabled({enabled: this.#adBlockEnabledSetting.get()});
void target.emulationAgent().invoke_setFocusEmulationEnabled({enabled: this.#emulatePageFocusSetting.get()});
}
#updateAutoAttach(): void {
Host.InspectorFrontendHost.InspectorFrontendHostInstance.setOpenNewWindowForPopups(this.#autoAttachSetting.get());
}
#update(): void {
for (const target of SDK.TargetManager.TargetManager.instance().targets()) {
this.#updateTarget(target);
}
}
targetAdded(target: SDK.Target.Target): void {
this.#updateTarget(target);
}
targetRemoved(_target: SDK.Target.Target): void {
}
}
SDK.ChildTargetManager.ChildTargetManager.install();