Web Inspector: add context menu items to copy a resource's HTTP request/response...
[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.appendContextMenuItemsForSourceCode = function(contextMenu, sourceCodeOrLocation)
27 {
28     console.assert(contextMenu instanceof WI.ContextMenu);
29     if (!(contextMenu instanceof WI.ContextMenu))
30         return;
31
32     let sourceCode = sourceCodeOrLocation;
33     let location = null;
34     if (sourceCodeOrLocation instanceof WI.SourceCodeLocation) {
35         sourceCode = sourceCodeOrLocation.sourceCode;
36         location = sourceCodeOrLocation;
37     }
38
39     console.assert(sourceCode instanceof WI.SourceCode);
40     if (!(sourceCode instanceof WI.SourceCode))
41         return;
42
43     contextMenu.appendSeparator();
44
45     WI.appendContextMenuItemsForURL(contextMenu, sourceCode.url, {sourceCode, location});
46
47     if (sourceCode instanceof WI.Resource) {
48         if (sourceCode.urlComponents.scheme !== "data") {
49             contextMenu.appendItem(WI.UIString("Copy as cURL"), () => {
50                 InspectorFrontendHost.copyText(sourceCode.generateCURLCommand());
51             });
52
53             contextMenu.appendSeparator();
54
55             contextMenu.appendItem(WI.UIString("Copy HTTP Request"), () => {
56                 InspectorFrontendHost.copyText(sourceCode.stringifyHTTPRequest());
57             });
58
59             if (sourceCode.hasResponse()) {
60                 contextMenu.appendItem(WI.UIString("Copy HTTP Response"), () => {
61                     InspectorFrontendHost.copyText(sourceCode.stringifyHTTPResponse());
62                 });
63             }
64
65             contextMenu.appendSeparator();
66         }
67     }
68
69     contextMenu.appendItem(WI.UIString("Save File"), () => {
70         sourceCode.requestContent().then(() => {
71             const forceSaveAs = true;
72             WI.FileUtilities.save({
73                 url: sourceCode.url || "",
74                 content: sourceCode.content
75             }, forceSaveAs);
76         });
77     });
78
79     contextMenu.appendSeparator();
80
81     if (location && (sourceCode instanceof WI.Script || (sourceCode instanceof WI.Resource && sourceCode.type === WI.Resource.Type.Script))) {
82         let existingBreakpoint = WI.debuggerManager.breakpointForSourceCodeLocation(location);
83         if (existingBreakpoint) {
84             contextMenu.appendItem(WI.UIString("Delete Breakpoint"), () => {
85                 WI.debuggerManager.removeBreakpoint(existingBreakpoint);
86             });
87         } else {
88             contextMenu.appendItem(WI.UIString("Add Breakpoint"), () => {
89                 WI.debuggerManager.addBreakpoint(new WI.Breakpoint(location));
90             });
91         }
92
93         contextMenu.appendSeparator();
94     }
95 };
96
97 WI.appendContextMenuItemsForURL = function(contextMenu, url, options = {})
98 {
99     if (!url)
100         return;
101
102     function showResourceWithOptions(options) {
103         if (options.location)
104             WI.showSourceCodeLocation(options.location, options);
105         else if (options.sourceCode)
106             WI.showSourceCode(options.sourceCode, options);
107         else
108             WI.openURL(url, options.frame, options);
109     }
110
111     if (!url.startsWith("javascript:") && !url.startsWith("data:")) {
112         contextMenu.appendItem(WI.UIString("Open in New Tab"), () => {
113             const frame = null;
114             WI.openURL(url, frame, {alwaysOpenExternally: true});
115         });
116     }
117
118     if (WI.networkManager.resourceForURL(url)) {
119         if (!WI.isShowingResourcesTab()) {
120             contextMenu.appendItem(WI.UIString("Reveal in Resources Tab"), () => {
121                 showResourceWithOptions({ignoreNetworkTab: true, ignoreSearchTab: true});
122             });
123         }
124         if (!WI.isShowingNetworkTab()) {
125             contextMenu.appendItem(WI.UIString("Reveal in Network Tab"), () => {
126                 showResourceWithOptions({ignoreResourcesTab: true, ignoreDebuggerTab: true, ignoreSearchTab: true});
127             });
128         }
129     }
130
131     contextMenu.appendSeparator();
132
133     contextMenu.appendItem(WI.UIString("Copy Link"), () => {
134         InspectorFrontendHost.copyText(url);
135     });
136 };
137
138 WI.appendContextMenuItemsForDOMNode = function(contextMenu, domNode, options = {})
139 {
140     console.assert(contextMenu instanceof WI.ContextMenu);
141     if (!(contextMenu instanceof WI.ContextMenu))
142         return;
143
144     console.assert(domNode instanceof WI.DOMNode);
145     if (!(domNode instanceof WI.DOMNode))
146         return;
147
148     let copySubMenu = options.copySubMenu || contextMenu.appendSubMenuItem(WI.UIString("Copy"));
149
150     let isElement = domNode.nodeType() === Node.ELEMENT_NODE;
151     if (domNode.ownerDocument && isElement) {
152         copySubMenu.appendItem(WI.UIString("Selector Path"), () => {
153             let cssPath = WI.cssPath(domNode);
154             InspectorFrontendHost.copyText(cssPath);
155         });
156     }
157
158     if (domNode.ownerDocument && !domNode.isPseudoElement()) {
159         copySubMenu.appendItem(WI.UIString("XPath"), () => {
160             let xpath = WI.xpath(domNode);
161             InspectorFrontendHost.copyText(xpath);
162         });
163     }
164
165     contextMenu.appendSeparator();
166
167     if (domNode.isCustomElement()) {
168         contextMenu.appendItem(WI.UIString("Jump to Definition"), () => {
169             function didGetFunctionDetails(error, response) {
170                 if (error)
171                     return;
172
173                 let location = response.location;
174                 let sourceCode = WI.debuggerManager.scriptForIdentifier(location.scriptId, WI.mainTarget);
175                 if (!sourceCode)
176                     return;
177
178                 let sourceCodeLocation = sourceCode.createSourceCodeLocation(location.lineNumber, location.columnNumber || 0);
179                 WI.showSourceCodeLocation(sourceCodeLocation, {
180                     ignoreNetworkTab: true,
181                     ignoreSearchTab: true,
182                 });
183             }
184
185             WI.RemoteObject.resolveNode(domNode).then((remoteObject) => {
186                 remoteObject.getProperty("constructor", (error, result, wasThrown) => {
187                     if (error)
188                         return;
189                     if (result.type === "function")
190                         remoteObject.target.DebuggerAgent.getFunctionDetails(result.objectId, didGetFunctionDetails);
191                     result.release();
192                 });
193                 remoteObject.release();
194             });
195         });
196
197         contextMenu.appendSeparator();
198     }
199
200     if (WI.domDebuggerManager.supported && isElement && !domNode.isPseudoElement() && domNode.ownerDocument) {
201         contextMenu.appendSeparator();
202
203         WI.appendContextMenuItemsForDOMNodeBreakpoints(contextMenu, domNode);
204     }
205
206     contextMenu.appendSeparator();
207
208     if (!options.excludeLogElement && !domNode.isInUserAgentShadowTree() && !domNode.isPseudoElement()) {
209         let label = isElement ? WI.UIString("Log Element") : WI.UIString("Log Node");
210         contextMenu.appendItem(label, () => {
211             WI.RemoteObject.resolveNode(domNode, WI.RuntimeManager.ConsoleObjectGroup).then((remoteObject) => {
212                 let text = isElement ? WI.UIString("Selected Element") : WI.UIString("Selected Node");
213                 const addSpecialUserLogClass = true;
214                 WI.consoleLogViewController.appendImmediateExecutionWithResult(text, remoteObject, addSpecialUserLogClass);
215             });
216         });
217     }
218
219     if (!options.excludeRevealElement && window.DOMAgent && domNode.ownerDocument) {
220         contextMenu.appendItem(WI.UIString("Reveal in DOM Tree"), () => {
221             WI.domManager.inspectElement(domNode.id);
222         });
223     }
224
225     if (!options.excludeRevealLayer && window.LayerTreeAgent && domNode.parentNode) {
226         contextMenu.appendItem(WI.UIString("Reveal in Layers Tab"), () => {
227             WI.showLayersTab({nodeToSelect: domNode});
228         });
229     }
230
231     if (window.PageAgent) {
232         contextMenu.appendItem(WI.UIString("Capture Screenshot"), () => {
233             PageAgent.snapshotNode(domNode.id, (error, dataURL) => {
234                 if (error) {
235                     const target = WI.mainTarget;
236                     const source = WI.ConsoleMessage.MessageSource.Other;
237                     const level = WI.ConsoleMessage.MessageLevel.Error;
238                     let consoleMessage = new WI.ConsoleMessage(target, source, level, error);
239                     consoleMessage.shouldRevealConsole = true;
240
241                     WI.consoleLogViewController.appendConsoleMessage(consoleMessage);
242                     return;
243                 }
244
245                 let date = new Date;
246                 let values = [
247                     date.getFullYear(),
248                     Number.zeroPad(date.getMonth() + 1, 2),
249                     Number.zeroPad(date.getDate(), 2),
250                     Number.zeroPad(date.getHours(), 2),
251                     Number.zeroPad(date.getMinutes(), 2),
252                     Number.zeroPad(date.getSeconds(), 2),
253                 ];
254                 let filename = WI.UIString("Screen Shot %s-%s-%s at %s.%s.%s").format(...values);
255                 WI.FileUtilities.save({
256                     url: encodeURI(`web-inspector:///${filename}.png`),
257                     content: parseDataURL(dataURL).data,
258                     base64Encoded: true,
259                 });
260             });
261         });
262     }
263
264     if (isElement) {
265         contextMenu.appendItem(WI.UIString("Scroll Into View"), () => {
266             domNode.scrollIntoView();
267         });
268     }
269
270     contextMenu.appendSeparator();
271 };
272
273 WI.appendContextMenuItemsForDOMNodeBreakpoints = function(contextMenu, domNode, {allowEditing} = {})
274 {
275     if (contextMenu.__domBreakpointItemsAdded)
276         return;
277
278     contextMenu.__domBreakpointItemsAdded = true;
279
280     let subMenu = contextMenu.appendSubMenuItem(WI.UIString("Break on\u2026"));
281
282     let breakpoints = WI.domDebuggerManager.domBreakpointsForNode(domNode);
283     let keyValuePairs = breakpoints.map((breakpoint) => [breakpoint.type, breakpoint]);
284     let breakpointsByType = new Map(keyValuePairs);
285
286     for (let type of Object.values(WI.DOMBreakpoint.Type)) {
287         let label = WI.DOMBreakpointTreeElement.displayNameForType(type);
288         let breakpoint = breakpointsByType.get(type);
289
290         subMenu.appendCheckboxItem(label, function() {
291             if (breakpoint)
292                 WI.domDebuggerManager.removeDOMBreakpoint(breakpoint);
293             else
294                 WI.domDebuggerManager.addDOMBreakpoint(new WI.DOMBreakpoint(domNode, type));
295         }, !!breakpoint, false);
296     }
297
298     if (allowEditing) {
299         contextMenu.appendSeparator();
300
301         let shouldEnable = breakpoints.some((breakpoint) => breakpoint.disabled);
302         let label = shouldEnable ? WI.UIString("Enable Breakpoints") : WI.UIString("Disable Breakpoints");
303         contextMenu.appendItem(label, () => {
304             breakpoints.forEach((breakpoint) => breakpoint.disabled = !shouldEnable);
305         });
306
307         contextMenu.appendItem(WI.UIString("Delete Breakpoints"), function() {
308             WI.domDebuggerManager.removeDOMBreakpointsForNode(domNode);
309         });
310     }
311 };