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