f8370f97b565929c6c14ba269976e0245a565b84
[WebKit-https.git] / Source / WebInspectorUI / UserInterface / Views / ContextMenuUtilities.js
1 /*
2  * Copyright (C) 2016 Devin Rousso <webkit@devinrousso.com>. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 WI.addMouseDownContextMenuHandlers = function(element, populateContextMenuCallback)
27 {
28     let ignoreMouseDown = false;
29     element.addEventListener("mousedown", (event) => {
30         if (event.button !== 0)
31             return;
32
33         event.stop();
34
35         if (ignoreMouseDown)
36             return;
37
38         ignoreMouseDown = true;
39
40         let contextMenu = WI.ContextMenu.createFromEvent(event);
41         contextMenu.addBeforeShowCallback(() => {
42             ignoreMouseDown = false;
43         });
44
45         populateContextMenuCallback(contextMenu, event);
46
47         contextMenu.show();
48     });
49
50     element.addEventListener("contextmenu", (event) => {
51         let contextMenu = WI.ContextMenu.createFromEvent(event);
52         populateContextMenuCallback(contextMenu, event);
53     });
54 };
55
56 WI.appendContextMenuItemsForSourceCode = function(contextMenu, sourceCodeOrLocation)
57 {
58     console.assert(contextMenu instanceof WI.ContextMenu);
59     if (!(contextMenu instanceof WI.ContextMenu))
60         return;
61
62     let sourceCode = sourceCodeOrLocation;
63     let location = null;
64     if (sourceCodeOrLocation instanceof WI.SourceCodeLocation) {
65         sourceCode = sourceCodeOrLocation.sourceCode;
66         location = sourceCodeOrLocation;
67     }
68
69     console.assert(sourceCode instanceof WI.SourceCode);
70     if (!(sourceCode instanceof WI.SourceCode))
71         return;
72
73     contextMenu.appendSeparator();
74
75     WI.appendContextMenuItemsForURL(contextMenu, sourceCode.url, {sourceCode, location});
76
77     if (sourceCode instanceof WI.Resource) {
78         if (sourceCode.urlComponents.scheme !== "data") {
79             contextMenu.appendItem(WI.UIString("Copy as cURL"), () => {
80                 InspectorFrontendHost.copyText(sourceCode.generateCURLCommand());
81             });
82
83             contextMenu.appendSeparator();
84
85             contextMenu.appendItem(WI.UIString("Copy HTTP Request"), () => {
86                 InspectorFrontendHost.copyText(sourceCode.stringifyHTTPRequest());
87             });
88
89             if (sourceCode.hasResponse()) {
90                 contextMenu.appendItem(WI.UIString("Copy HTTP Response"), () => {
91                     InspectorFrontendHost.copyText(sourceCode.stringifyHTTPResponse());
92                 });
93             }
94
95             contextMenu.appendSeparator();
96         }
97     }
98
99     contextMenu.appendItem(WI.UIString("Save File"), () => {
100         sourceCode.requestContent().then(() => {
101             const forceSaveAs = true;
102             WI.FileUtilities.save({
103                 url: sourceCode.url || "",
104                 content: sourceCode.content
105             }, forceSaveAs);
106         });
107     });
108
109     contextMenu.appendSeparator();
110
111     if (location && (sourceCode instanceof WI.Script || (sourceCode instanceof WI.Resource && sourceCode.type === WI.Resource.Type.Script))) {
112         let existingBreakpoint = WI.debuggerManager.breakpointForSourceCodeLocation(location);
113         if (existingBreakpoint) {
114             contextMenu.appendItem(WI.UIString("Delete Breakpoint"), () => {
115                 WI.debuggerManager.removeBreakpoint(existingBreakpoint);
116             });
117         } else {
118             contextMenu.appendItem(WI.UIString("Add Breakpoint"), () => {
119                 WI.debuggerManager.addBreakpoint(new WI.Breakpoint(location));
120             });
121         }
122
123         contextMenu.appendSeparator();
124     }
125 };
126
127 WI.appendContextMenuItemsForURL = function(contextMenu, url, options = {})
128 {
129     if (!url)
130         return;
131
132     function showResourceWithOptions(options) {
133         if (options.location)
134             WI.showSourceCodeLocation(options.location, options);
135         else if (options.sourceCode)
136             WI.showSourceCode(options.sourceCode, options);
137         else
138             WI.openURL(url, options.frame, options);
139     }
140
141     if (!url.startsWith("javascript:") && !url.startsWith("data:")) {
142         contextMenu.appendItem(WI.UIString("Open in New Tab"), () => {
143             const frame = null;
144             WI.openURL(url, frame, {alwaysOpenExternally: true});
145         });
146     }
147
148     if (WI.networkManager.resourceForURL(url)) {
149         if (WI.settings.experimentalEnableSourcesTab.value) {
150             if (!WI.isShowingSourcesTab()) {
151                 contextMenu.appendItem(WI.UIString("Reveal in Sources Tab"), () => {
152                     showResourceWithOptions({preferredTabType: WI.SourcesTabContentView.Type});
153                 });
154             }
155         } else {
156             if (!WI.isShowingResourcesTab()) {
157                 contextMenu.appendItem(WI.UIString("Reveal in Resources Tab"), () => {
158                     showResourceWithOptions({preferredTabType: WI.ResourcesTabContentView.Type});
159                 });
160             }
161         }
162         if (!WI.isShowingNetworkTab()) {
163             contextMenu.appendItem(WI.UIString("Reveal in Network Tab"), () => {
164                 showResourceWithOptions({preferredTabType: WI.NetworkTabContentView.Type});
165             });
166         }
167     }
168
169     contextMenu.appendSeparator();
170
171     contextMenu.appendItem(WI.UIString("Copy Link"), () => {
172         InspectorFrontendHost.copyText(url);
173     });
174 };
175
176 WI.appendContextMenuItemsForDOMNode = function(contextMenu, domNode, options = {})
177 {
178     console.assert(contextMenu instanceof WI.ContextMenu);
179     if (!(contextMenu instanceof WI.ContextMenu))
180         return;
181
182     console.assert(domNode instanceof WI.DOMNode);
183     if (!(domNode instanceof WI.DOMNode))
184         return;
185
186     let copySubMenu = options.copySubMenu || contextMenu.appendSubMenuItem(WI.UIString("Copy"));
187
188     let isElement = domNode.nodeType() === Node.ELEMENT_NODE;
189     let attached = domNode.attached;
190
191     if (isElement && attached) {
192         copySubMenu.appendItem(WI.UIString("Selector Path"), () => {
193             let cssPath = WI.cssPath(domNode);
194             InspectorFrontendHost.copyText(cssPath);
195         });
196     }
197
198     if (!domNode.isPseudoElement() && attached) {
199         copySubMenu.appendItem(WI.UIString("XPath"), () => {
200             let xpath = WI.xpath(domNode);
201             InspectorFrontendHost.copyText(xpath);
202         });
203     }
204
205     contextMenu.appendSeparator();
206
207     if (domNode.isCustomElement()) {
208         contextMenu.appendItem(WI.UIString("Jump to Definition"), () => {
209             function didGetFunctionDetails(error, response) {
210                 if (error)
211                     return;
212
213                 let location = response.location;
214                 let sourceCode = WI.debuggerManager.scriptForIdentifier(location.scriptId, WI.mainTarget);
215                 if (!sourceCode)
216                     return;
217
218                 let sourceCodeLocation = sourceCode.createSourceCodeLocation(location.lineNumber, location.columnNumber || 0);
219                 WI.showSourceCodeLocation(sourceCodeLocation, {
220                     ignoreNetworkTab: true,
221                     ignoreSearchTab: true,
222                 });
223             }
224
225             WI.RemoteObject.resolveNode(domNode).then((remoteObject) => {
226                 remoteObject.getProperty("constructor", (error, result, wasThrown) => {
227                     if (error)
228                         return;
229                     if (result.type === "function")
230                         remoteObject.target.DebuggerAgent.getFunctionDetails(result.objectId, didGetFunctionDetails);
231                     result.release();
232                 });
233                 remoteObject.release();
234             });
235         });
236
237         contextMenu.appendSeparator();
238     }
239
240     if (WI.cssManager.canForcePseudoClasses() && domNode.attached) {
241         contextMenu.appendSeparator();
242
243         let pseudoSubMenu = contextMenu.appendSubMenuItem(WI.UIString("Forced Pseudo-Classes", "A context menu item to force (override) a DOM node's pseudo-classes"));
244
245         let enabledPseudoClasses = domNode.enabledPseudoClasses;
246         WI.CSSManager.ForceablePseudoClasses.forEach((pseudoClass) => {
247             let enabled = enabledPseudoClasses.includes(pseudoClass);
248             pseudoSubMenu.appendCheckboxItem(pseudoClass.capitalize(), () => {
249                 domNode.setPseudoClassEnabled(pseudoClass, !enabled);
250             }, enabled);
251         });
252     }
253
254     if (WI.domDebuggerManager.supported && isElement && !domNode.isPseudoElement() && attached) {
255         contextMenu.appendSeparator();
256
257         WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu, domNode, options);
258     }
259
260     contextMenu.appendSeparator();
261
262     if (!options.excludeLogElement && !domNode.isInUserAgentShadowTree() && !domNode.isPseudoElement()) {
263         let label = isElement ? WI.UIString("Log Element", "Log (print) DOM element to Console") : WI.UIString("Log Node", "Log (print) DOM node to Console");
264         contextMenu.appendItem(label, () => {
265             WI.RemoteObject.resolveNode(domNode, WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject) => {
266                 let text = isElement ? WI.UIString("Selected Element", "Selected DOM element") : WI.UIString("Selected Node", "Selected DOM node");
267                 const addSpecialUserLogClass = true;
268                 WI.consoleLogViewController.appendImmediateExecutionWithResult(text, remoteObject, addSpecialUserLogClass);
269             });
270         });
271     }
272
273     if (!options.excludeRevealElement && window.DOMAgent && attached) {
274         contextMenu.appendItem(WI.repeatedUIString.revealInDOMTree(), () => {
275             WI.domManager.inspectElement(domNode.id);
276         });
277     }
278
279     if (WI.settings.experimentalEnableLayersTab.value && window.LayerTreeAgent && attached) {
280         contextMenu.appendItem(WI.UIString("Reveal in Layers Tab", "Open Layers tab and select the layer corresponding to this node"), () => {
281             WI.showLayersTab({nodeToSelect: domNode});
282         });
283     }
284
285     if (window.PageAgent && attached) {
286         contextMenu.appendItem(WI.UIString("Capture Screenshot", "Capture screenshot of the selected DOM node"), () => {
287             PageAgent.snapshotNode(domNode.id, (error, dataURL) => {
288                 if (error) {
289                     const target = WI.mainTarget;
290                     const source = WI.ConsoleMessage.MessageSource.Other;
291                     const level = WI.ConsoleMessage.MessageLevel.Error;
292                     let consoleMessage = new WI.ConsoleMessage(target, source, level, error);
293                     consoleMessage.shouldRevealConsole = true;
294
295                     WI.consoleLogViewController.appendConsoleMessage(consoleMessage);
296                     return;
297                 }
298
299                 WI.FileUtilities.save({
300                     url: WI.FileUtilities.inspectorURLForFilename(WI.FileUtilities.screenshotString() + ".png"),
301                     content: parseDataURL(dataURL).data,
302                     base64Encoded: true,
303                 });
304             });
305         });
306     }
307
308     if (isElement && attached) {
309         contextMenu.appendItem(WI.UIString("Scroll into View", "Scroll selected DOM node into view on the inspected web page"), () => {
310             domNode.scrollIntoView();
311         });
312     }
313
314     contextMenu.appendSeparator();
315 };
316
317 WI.appendContextMenuItemsForDOMNodeBreakpoints = function(contextMenu, domNode, options = {})
318 {
319     if (contextMenu.__domBreakpointItemsAdded)
320         return;
321
322     contextMenu.__domBreakpointItemsAdded = true;
323
324     let breakpoints = WI.domDebuggerManager.domBreakpointsForNode(domNode);
325
326     contextMenu.appendSeparator();
327
328     let subMenu = contextMenu.appendSubMenuItem(WI.UIString("Break on"));
329
330     for (let type of Object.values(WI.DOMBreakpoint.Type)) {
331         let label = WI.DOMBreakpointTreeElement.displayNameForType(type);
332         let breakpoint = breakpoints.find((breakpoint) => breakpoint.type === type);
333
334         subMenu.appendCheckboxItem(label, function() {
335             if (breakpoint)
336                 WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);
337             else
338                 WI.domDebuggerManager.addDOMBreakpoint(new WI.DOMBreakpoint(domNode, type));
339         }, !!breakpoint);
340     }
341
342     contextMenu.appendSeparator();
343
344     if (breakpoints.length) {
345         let shouldEnable = breakpoints.some((breakpoint) => breakpoint.disabled);
346         contextMenu.appendItem(shouldEnable ? WI.UIString("Enable Breakpoint") : WI.UIString("Disable Breakpoint"), () => {
347             for (let breakpoint of breakpoints)
348                 breakpoint.disabled = !shouldEnable;
349         });
350
351         contextMenu.appendItem(WI.UIString("Delete Breakpoint"), () => {
352             for (let breakpoint of breakpoints)
353                 WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);
354         });
355
356         contextMenu.appendSeparator();
357     }
358
359     let subtreeBreakpoints = WI.domDebuggerManager.domBreakpointsInSubtree(domNode);
360     if (subtreeBreakpoints.length) {
361         if (options.revealDescendantBreakpointsMenuItemHandler)
362             contextMenu.appendItem(WI.UIString("Reveal Descendant Breakpoints"), options.revealDescendantBreakpointsMenuItemHandler);
363
364         let subtreeShouldEnable = subtreeBreakpoints.some((breakpoint) => breakpoint.disabled);
365         contextMenu.appendItem(subtreeShouldEnable ? WI.UIString("Enable Descendant Breakpoints") : WI.UIString("Disable Descendant Breakpoints"), () => {
366             for (let subtreeBreakpoint of subtreeBreakpoints)
367                 subtreeBreakpoint.disabled = !subtreeShouldEnable;
368         });
369
370         contextMenu.appendItem(WI.UIString("Delete Descendant Breakpoints"), () => {
371             for (let subtreeBreakpoint of subtreeBreakpoints)
372                 WI.domDebuggerManager.removeDOMBreakpoint(subtreeBreakpoint);
373         });
374
375         contextMenu.appendSeparator();
376     }
377 };