Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / chrome / tools / test / reference_build / chrome_linux / resources / inspector / ExtensionServer.js
1 if(!window.InspectorExtensionRegistry){WebInspector.InspectorExtensionRegistryStub=function()
2 {}
3 WebInspector.InspectorExtensionRegistryStub.prototype={getExtensionsAsync:function()
4 {}}
5 var InspectorExtensionRegistry=new WebInspector.InspectorExtensionRegistryStub();};function defineCommonExtensionSymbols(apiPrivate)
6 {if(!apiPrivate.audits)
7 apiPrivate.audits={};apiPrivate.audits.Severity={Info:"info",Warning:"warning",Severe:"severe"};if(!apiPrivate.console)
8 apiPrivate.console={};apiPrivate.console.Severity={Debug:"debug",Log:"log",Warning:"warning",Error:"error"};if(!apiPrivate.panels)
9 apiPrivate.panels={};apiPrivate.panels.SearchAction={CancelSearch:"cancelSearch",PerformSearch:"performSearch",NextSearchResult:"nextSearchResult",PreviousSearchResult:"previousSearchResult"};apiPrivate.Events={AuditStarted:"audit-started-",ButtonClicked:"button-clicked-",ConsoleMessageAdded:"console-message-added",PanelObjectSelected:"panel-objectSelected-",NetworkRequestFinished:"network-request-finished",OpenResource:"open-resource",PanelSearch:"panel-search-",ResourceAdded:"resource-added",ResourceContentCommitted:"resource-content-committed",TimelineEventRecorded:"timeline-event-recorded",ViewShown:"view-shown-",ViewHidden:"view-hidden-"};apiPrivate.Commands={AddAuditCategory:"addAuditCategory",AddAuditResult:"addAuditResult",AddConsoleMessage:"addConsoleMessage",AddRequestHeaders:"addRequestHeaders",ApplyStyleSheet:"applyStyleSheet",CreatePanel:"createPanel",CreateSidebarPane:"createSidebarPane",CreateStatusBarButton:"createStatusBarButton",EvaluateOnInspectedPage:"evaluateOnInspectedPage",ForwardKeyboardEvent:"_forwardKeyboardEvent",GetConsoleMessages:"getConsoleMessages",GetHAR:"getHAR",GetPageResources:"getPageResources",GetRequestContent:"getRequestContent",GetResourceContent:"getResourceContent",InspectedURLChanged:"inspectedURLChanged",OpenResource:"openResource",Reload:"Reload",Subscribe:"subscribe",SetOpenResourceHandler:"setOpenResourceHandler",SetResourceContent:"setResourceContent",SetSidebarContent:"setSidebarContent",SetSidebarHeight:"setSidebarHeight",SetSidebarPage:"setSidebarPage",ShowPanel:"showPanel",StopAuditCategoryRun:"stopAuditCategoryRun",Unsubscribe:"unsubscribe",UpdateAuditProgress:"updateAuditProgress",UpdateButton:"updateButton"};}
10 function injectedExtensionAPI(injectedScriptId)
11 {var apiPrivate={};defineCommonExtensionSymbols(apiPrivate);var commands=apiPrivate.Commands;var events=apiPrivate.Events;var userAction=false;function EventSinkImpl(type,customDispatch)
12 {this._type=type;this._listeners=[];this._customDispatch=customDispatch;}
13 EventSinkImpl.prototype={addListener:function(callback)
14 {if(typeof callback!=="function")
15 throw"addListener: callback is not a function";if(this._listeners.length===0)
16 extensionServer.sendRequest({command:commands.Subscribe,type:this._type});this._listeners.push(callback);extensionServer.registerHandler("notify-"+this._type,this._dispatch.bind(this));},removeListener:function(callback)
17 {var listeners=this._listeners;for(var i=0;i<listeners.length;++i){if(listeners[i]===callback){listeners.splice(i,1);break;}}
18 if(this._listeners.length===0)
19 extensionServer.sendRequest({command:commands.Unsubscribe,type:this._type});},_fire:function(vararg)
20 {var listeners=this._listeners.slice();for(var i=0;i<listeners.length;++i)
21 listeners[i].apply(null,arguments);},_dispatch:function(request)
22 {if(this._customDispatch)
23 this._customDispatch.call(this,request);else
24 this._fire.apply(this,request.arguments);}}
25 function InspectorExtensionAPI()
26 {this.audits=new Audits();this.inspectedWindow=new InspectedWindow();this.panels=new Panels();this.network=new Network();defineDeprecatedProperty(this,"webInspector","resources","network");this.timeline=new Timeline();this.console=new ConsoleAPI();}
27 function ConsoleAPI()
28 {this.onMessageAdded=new EventSink(events.ConsoleMessageAdded);}
29 ConsoleAPI.prototype={getMessages:function(callback)
30 {extensionServer.sendRequest({command:commands.GetConsoleMessages},callback);},addMessage:function(severity,text,url,line)
31 {extensionServer.sendRequest({command:commands.AddConsoleMessage,severity:severity,text:text,url:url,line:line});},get Severity()
32 {return apiPrivate.console.Severity;}}
33 function Network()
34 {function dispatchRequestEvent(message)
35 {var request=message.arguments[1];request.__proto__=new Request(message.arguments[0]);this._fire(request);}
36 this.onRequestFinished=new EventSink(events.NetworkRequestFinished,dispatchRequestEvent);defineDeprecatedProperty(this,"network","onFinished","onRequestFinished");this.onNavigated=new EventSink(events.InspectedURLChanged);}
37 Network.prototype={getHAR:function(callback)
38 {function callbackWrapper(result)
39 {var entries=(result&&result.entries)||[];for(var i=0;i<entries.length;++i){entries[i].__proto__=new Request(entries[i]._requestId);delete entries[i]._requestId;}
40 callback(result);}
41 extensionServer.sendRequest({command:commands.GetHAR},callback&&callbackWrapper);},addRequestHeaders:function(headers)
42 {extensionServer.sendRequest({command:commands.AddRequestHeaders,headers:headers,extensionId:window.location.hostname});}}
43 function RequestImpl(id)
44 {this._id=id;}
45 RequestImpl.prototype={getContent:function(callback)
46 {function callbackWrapper(response)
47 {callback(response.content,response.encoding);}
48 extensionServer.sendRequest({command:commands.GetRequestContent,id:this._id},callback&&callbackWrapper);}}
49 function Panels()
50 {var panels={elements:new ElementsPanel(),sources:new SourcesPanel(),};function panelGetter(name)
51 {return panels[name];}
52 for(var panel in panels)
53 this.__defineGetter__(panel,panelGetter.bind(null,panel));this.applyStyleSheet=function(styleSheet){extensionServer.sendRequest({command:commands.ApplyStyleSheet,styleSheet:styleSheet});};}
54 Panels.prototype={create:function(title,icon,page,callback)
55 {var id="extension-panel-"+extensionServer.nextObjectId();var request={command:commands.CreatePanel,id:id,title:title,icon:icon,page:page};extensionServer.sendRequest(request,callback&&callback.bind(this,new ExtensionPanel(id)));},setOpenResourceHandler:function(callback)
56 {var hadHandler=extensionServer.hasHandler(events.OpenResource);function callbackWrapper(message)
57 {userAction=true;try{callback.call(null,new Resource(message.resource),message.lineNumber);}finally{userAction=false;}}
58 if(!callback)
59 extensionServer.unregisterHandler(events.OpenResource);else
60 extensionServer.registerHandler(events.OpenResource,callbackWrapper);if(hadHandler===!callback)
61 extensionServer.sendRequest({command:commands.SetOpenResourceHandler,"handlerPresent":!!callback});},openResource:function(url,lineNumber,callback)
62 {extensionServer.sendRequest({command:commands.OpenResource,"url":url,"lineNumber":lineNumber},callback);},get SearchAction()
63 {return apiPrivate.panels.SearchAction;}}
64 function ExtensionViewImpl(id)
65 {this._id=id;function dispatchShowEvent(message)
66 {var frameIndex=message.arguments[0];if(typeof frameIndex==="number")
67 this._fire(window.parent.frames[frameIndex]);else
68 this._fire();}
69 if(id){this.onShown=new EventSink(events.ViewShown+id,dispatchShowEvent);this.onHidden=new EventSink(events.ViewHidden+id);}}
70 function PanelWithSidebarImpl(hostPanelName)
71 {ExtensionViewImpl.call(this,null);this._hostPanelName=hostPanelName;this.onSelectionChanged=new EventSink(events.PanelObjectSelected+hostPanelName);}
72 PanelWithSidebarImpl.prototype={createSidebarPane:function(title,callback)
73 {var id="extension-sidebar-"+extensionServer.nextObjectId();var request={command:commands.CreateSidebarPane,panel:this._hostPanelName,id:id,title:title};function callbackWrapper()
74 {callback(new ExtensionSidebarPane(id));}
75 extensionServer.sendRequest(request,callback&&callbackWrapper);},__proto__:ExtensionViewImpl.prototype}
76 function declareInterfaceClass(implConstructor)
77 {return function()
78 {var impl={__proto__:implConstructor.prototype};implConstructor.apply(impl,arguments);populateInterfaceClass(this,impl);}}
79 function defineDeprecatedProperty(object,className,oldName,newName)
80 {var warningGiven=false;function getter()
81 {if(!warningGiven){console.warn(className+"."+oldName+" is deprecated. Use "+className+"."+newName+" instead");warningGiven=true;}
82 return object[newName];}
83 object.__defineGetter__(oldName,getter);}
84 function extractCallbackArgument(args)
85 {var lastArgument=args[args.length-1];return typeof lastArgument==="function"?lastArgument:undefined;}
86 var AuditCategory=declareInterfaceClass(AuditCategoryImpl);var AuditResult=declareInterfaceClass(AuditResultImpl);var Button=declareInterfaceClass(ButtonImpl);var EventSink=declareInterfaceClass(EventSinkImpl);var ExtensionPanel=declareInterfaceClass(ExtensionPanelImpl);var ExtensionSidebarPane=declareInterfaceClass(ExtensionSidebarPaneImpl);var PanelWithSidebar=declareInterfaceClass(PanelWithSidebarImpl);var Request=declareInterfaceClass(RequestImpl);var Resource=declareInterfaceClass(ResourceImpl);var Timeline=declareInterfaceClass(TimelineImpl);function ElementsPanel()
87 {PanelWithSidebar.call(this,"elements");}
88 ElementsPanel.prototype={__proto__:PanelWithSidebar.prototype}
89 function SourcesPanel()
90 {PanelWithSidebar.call(this,"sources");}
91 SourcesPanel.prototype={__proto__:PanelWithSidebar.prototype}
92 function ExtensionPanelImpl(id)
93 {ExtensionViewImpl.call(this,id);this.onSearch=new EventSink(events.PanelSearch+id);}
94 ExtensionPanelImpl.prototype={createStatusBarButton:function(iconPath,tooltipText,disabled)
95 {var id="button-"+extensionServer.nextObjectId();var request={command:commands.CreateStatusBarButton,panel:this._id,id:id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);return new Button(id);},show:function()
96 {if(!userAction)
97 return;var request={command:commands.ShowPanel,id:this._id};extensionServer.sendRequest(request);},__proto__:ExtensionViewImpl.prototype}
98 function ExtensionSidebarPaneImpl(id)
99 {ExtensionViewImpl.call(this,id);}
100 ExtensionSidebarPaneImpl.prototype={setHeight:function(height)
101 {extensionServer.sendRequest({command:commands.SetSidebarHeight,id:this._id,height:height});},setExpression:function(expression,rootTitle,evaluateOptions)
102 {var request={command:commands.SetSidebarContent,id:this._id,expression:expression,rootTitle:rootTitle,evaluateOnPage:true,};if(typeof evaluateOptions==="object")
103 request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,extractCallbackArgument(arguments));},setObject:function(jsonObject,rootTitle,callback)
104 {extensionServer.sendRequest({command:commands.SetSidebarContent,id:this._id,expression:jsonObject,rootTitle:rootTitle},callback);},setPage:function(page)
105 {extensionServer.sendRequest({command:commands.SetSidebarPage,id:this._id,page:page});},__proto__:ExtensionViewImpl.prototype}
106 function ButtonImpl(id)
107 {this._id=id;this.onClicked=new EventSink(events.ButtonClicked+id);}
108 ButtonImpl.prototype={update:function(iconPath,tooltipText,disabled)
109 {var request={command:commands.UpdateButton,id:this._id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);}};function Audits()
110 {}
111 Audits.prototype={addCategory:function(displayName,resultCount)
112 {var id="extension-audit-category-"+extensionServer.nextObjectId();if(typeof resultCount!=="undefined")
113 console.warn("Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead.");extensionServer.sendRequest({command:commands.AddAuditCategory,id:id,displayName:displayName,resultCount:resultCount});return new AuditCategory(id);}}
114 function AuditCategoryImpl(id)
115 {function dispatchAuditEvent(request)
116 {var auditResult=new AuditResult(request.arguments[0]);try{this._fire(auditResult);}catch(e){console.error("Uncaught exception in extension audit event handler: "+e);auditResult.done();}}
117 this._id=id;this.onAuditStarted=new EventSink(events.AuditStarted+id,dispatchAuditEvent);}
118 function AuditResultImpl(id)
119 {this._id=id;this.createURL=this._nodeFactory.bind(this,"url");this.createSnippet=this._nodeFactory.bind(this,"snippet");this.createText=this._nodeFactory.bind(this,"text");this.createObject=this._nodeFactory.bind(this,"object");this.createNode=this._nodeFactory.bind(this,"node");}
120 AuditResultImpl.prototype={addResult:function(displayName,description,severity,details)
121 {if(details&&!(details instanceof AuditResultNode))
122 details=new AuditResultNode(details instanceof Array?details:[details]);var request={command:commands.AddAuditResult,resultId:this._id,displayName:displayName,description:description,severity:severity,details:details};extensionServer.sendRequest(request);},createResult:function()
123 {return new AuditResultNode(Array.prototype.slice.call(arguments));},updateProgress:function(worked,totalWork)
124 {extensionServer.sendRequest({command:commands.UpdateAuditProgress,resultId:this._id,progress:worked/totalWork});},done:function()
125 {extensionServer.sendRequest({command:commands.StopAuditCategoryRun,resultId:this._id});},get Severity()
126 {return apiPrivate.audits.Severity;},createResourceLink:function(url,lineNumber)
127 {return{type:"resourceLink",arguments:[url,lineNumber&&lineNumber-1]};},_nodeFactory:function(type)
128 {return{type:type,arguments:Array.prototype.slice.call(arguments,1)};}}
129 function AuditResultNode(contents)
130 {this.contents=contents;this.children=[];this.expanded=false;}
131 AuditResultNode.prototype={addChild:function()
132 {var node=new AuditResultNode(Array.prototype.slice.call(arguments));this.children.push(node);return node;}};function InspectedWindow()
133 {function dispatchResourceEvent(message)
134 {this._fire(new Resource(message.arguments[0]));}
135 function dispatchResourceContentEvent(message)
136 {this._fire(new Resource(message.arguments[0]),message.arguments[1]);}
137 this.onResourceAdded=new EventSink(events.ResourceAdded,dispatchResourceEvent);this.onResourceContentCommitted=new EventSink(events.ResourceContentCommitted,dispatchResourceContentEvent);}
138 InspectedWindow.prototype={reload:function(optionsOrUserAgent)
139 {var options=null;if(typeof optionsOrUserAgent==="object")
140 options=optionsOrUserAgent;else if(typeof optionsOrUserAgent==="string"){options={userAgent:optionsOrUserAgent};console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. "+"Use inspectedWindow.reload({ userAgent: value}) instead.");}
141 extensionServer.sendRequest({command:commands.Reload,options:options});},eval:function(expression,evaluateOptions)
142 {var callback=extractCallbackArgument(arguments);function callbackWrapper(result)
143 {if(result.isError||result.isException)
144 callback(undefined,result);else
145 callback(result.value);}
146 var request={command:commands.EvaluateOnInspectedPage,expression:expression};if(typeof evaluateOptions==="object")
147 request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,callback&&callbackWrapper);return null;},getResources:function(callback)
148 {function wrapResource(resourceData)
149 {return new Resource(resourceData);}
150 function callbackWrapper(resources)
151 {callback(resources.map(wrapResource));}
152 extensionServer.sendRequest({command:commands.GetPageResources},callback&&callbackWrapper);}}
153 function ResourceImpl(resourceData)
154 {this._url=resourceData.url
155 this._type=resourceData.type;}
156 ResourceImpl.prototype={get url()
157 {return this._url;},get type()
158 {return this._type;},getContent:function(callback)
159 {function callbackWrapper(response)
160 {callback(response.content,response.encoding);}
161 extensionServer.sendRequest({command:commands.GetResourceContent,url:this._url},callback&&callbackWrapper);},setContent:function(content,commit,callback)
162 {extensionServer.sendRequest({command:commands.SetResourceContent,url:this._url,content:content,commit:commit},callback);}}
163 function TimelineImpl()
164 {this.onEventRecorded=new EventSink(events.TimelineEventRecorded);}
165 var keyboardEventRequestQueue=[];var forwardTimer=null;function forwardKeyboardEvent(event)
166 {const Esc="U+001B";if(!event.ctrlKey&&!event.altKey&&!event.metaKey&&!/^F\d+$/.test(event.keyIdentifier)&&event.keyIdentifier!==Esc)
167 return;var requestPayload={eventType:event.type,ctrlKey:event.ctrlKey,altKey:event.altKey,metaKey:event.metaKey,keyIdentifier:event.keyIdentifier,location:event.location,keyCode:event.keyCode};keyboardEventRequestQueue.push(requestPayload);if(!forwardTimer)
168 forwardTimer=setTimeout(forwardEventQueue,0);}
169 function forwardEventQueue()
170 {forwardTimer=null;var request={command:commands.ForwardKeyboardEvent,entries:keyboardEventRequestQueue};extensionServer.sendRequest(request);keyboardEventRequestQueue=[];}
171 document.addEventListener("keydown",forwardKeyboardEvent,false);document.addEventListener("keypress",forwardKeyboardEvent,false);function ExtensionServerClient()
172 {this._callbacks={};this._handlers={};this._lastRequestId=0;this._lastObjectId=0;this.registerHandler("callback",this._onCallback.bind(this));var channel=new MessageChannel();this._port=channel.port1;this._port.addEventListener("message",this._onMessage.bind(this),false);this._port.start();window.parent.postMessage("registerExtension",[channel.port2],"*");}
173 ExtensionServerClient.prototype={sendRequest:function(message,callback)
174 {if(typeof callback==="function")
175 message.requestId=this._registerCallback(callback);this._port.postMessage(message);},hasHandler:function(command)
176 {return!!this._handlers[command];},registerHandler:function(command,handler)
177 {this._handlers[command]=handler;},unregisterHandler:function(command)
178 {delete this._handlers[command];},nextObjectId:function()
179 {return injectedScriptId+"_"+ ++this._lastObjectId;},_registerCallback:function(callback)
180 {var id=++this._lastRequestId;this._callbacks[id]=callback;return id;},_onCallback:function(request)
181 {if(request.requestId in this._callbacks){var callback=this._callbacks[request.requestId];delete this._callbacks[request.requestId];callback(request.result);}},_onMessage:function(event)
182 {var request=event.data;var handler=this._handlers[request.command];if(handler)
183 handler.call(this,request);}}
184 function populateInterfaceClass(interface,implementation)
185 {for(var member in implementation){if(member.charAt(0)==="_")
186 continue;var descriptor=null;for(var owner=implementation;owner&&!descriptor;owner=owner.__proto__)
187 descriptor=Object.getOwnPropertyDescriptor(owner,member);if(!descriptor)
188 continue;if(typeof descriptor.value==="function")
189 interface[member]=descriptor.value.bind(implementation);else if(typeof descriptor.get==="function")
190 interface.__defineGetter__(member,descriptor.get.bind(implementation));else
191 Object.defineProperty(interface,member,descriptor);}}
192 if(!extensionServer)
193 extensionServer=new ExtensionServerClient();return new InspectorExtensionAPI();}
194 function platformExtensionAPI(coreAPI)
195 {function getTabId()
196 {return tabId;}
197 chrome=window.chrome||{};var devtools_descriptor=Object.getOwnPropertyDescriptor(chrome,"devtools");if(!devtools_descriptor||devtools_descriptor.get)
198 Object.defineProperty(chrome,"devtools",{value:{},enumerable:true});chrome.devtools.inspectedWindow={};chrome.devtools.inspectedWindow.__defineGetter__("tabId",getTabId);chrome.devtools.inspectedWindow.__proto__=coreAPI.inspectedWindow;chrome.devtools.network=coreAPI.network;chrome.devtools.panels=coreAPI.panels;if(extensionInfo.exposeExperimentalAPIs!==false){chrome.experimental=chrome.experimental||{};chrome.experimental.devtools=chrome.experimental.devtools||{};var properties=Object.getOwnPropertyNames(coreAPI);for(var i=0;i<properties.length;++i){var descriptor=Object.getOwnPropertyDescriptor(coreAPI,properties[i]);Object.defineProperty(chrome.experimental.devtools,properties[i],descriptor);}
199 chrome.experimental.devtools.inspectedWindow=chrome.devtools.inspectedWindow;}
200 if(extensionInfo.exposeWebInspectorNamespace)
201 window.webInspector=coreAPI;}
202 function buildPlatformExtensionAPI(extensionInfo)
203 {return"var extensionInfo = "+JSON.stringify(extensionInfo)+";"+"var tabId = "+WebInspector._inspectedTabId+";"+
204 platformExtensionAPI.toString();}
205 function buildExtensionAPIInjectedScript(extensionInfo)
206 {return"(function(injectedScriptId){ "+"var extensionServer;"+
207 defineCommonExtensionSymbols.toString()+";"+
208 injectedExtensionAPI.toString()+";"+
209 buildPlatformExtensionAPI(extensionInfo)+";"+"platformExtensionAPI(injectedExtensionAPI(injectedScriptId));"+"return {};"+"})";};WebInspector.ExtensionAuditCategory=function(extensionOrigin,id,displayName,ruleCount)
210 {this._extensionOrigin=extensionOrigin;this._id=id;this._displayName=displayName;this._ruleCount=ruleCount;}
211 WebInspector.ExtensionAuditCategory.prototype={get id()
212 {return this._id;},get displayName()
213 {return this._displayName;},run:function(requests,ruleResultCallback,categoryDoneCallback,progress)
214 {var results=new WebInspector.ExtensionAuditCategoryResults(this,ruleResultCallback,categoryDoneCallback,progress);WebInspector.extensionServer.startAuditRun(this,results);}}
215 WebInspector.ExtensionAuditCategoryResults=function(category,ruleResultCallback,categoryDoneCallback,progress)
216 {this._category=category;this._ruleResultCallback=ruleResultCallback;this._categoryDoneCallback=categoryDoneCallback;this._progress=progress;this._progress.setTotalWork(1);this._expectedResults=category._ruleCount;this._actualResults=0;this.id=category.id+"-"+ ++WebInspector.ExtensionAuditCategoryResults._lastId;}
217 WebInspector.ExtensionAuditCategoryResults.prototype={done:function()
218 {WebInspector.extensionServer.stopAuditRun(this);this._progress.done();this._categoryDoneCallback();},addResult:function(displayName,description,severity,details)
219 {var result=new WebInspector.AuditRuleResult(displayName);result.addChild(description);result.severity=severity;if(details)
220 this._addNode(result,details);this._addResult(result);},_addNode:function(parent,node)
221 {var contents=WebInspector.auditFormatters.partiallyApply(WebInspector.ExtensionAuditFormatters,this,node.contents);var addedNode=parent.addChild(contents,node.expanded);if(node.children){for(var i=0;i<node.children.length;++i)
222 this._addNode(addedNode,node.children[i]);}},_addResult:function(result)
223 {this._ruleResultCallback(result);++this._actualResults;if(typeof this._expectedResults==="number"){this._progress.setWorked(this._actualResults/this._expectedResults);if(this._actualResults===this._expectedResults)
224 this.done();}},updateProgress:function(progress)
225 {this._progress.setWorked(progress);},evaluate:function(expression,evaluateOptions,callback)
226 {function onEvaluate(error,result,wasThrown)
227 {if(wasThrown)
228 return;var object=WebInspector.RemoteObject.fromPayload(result);callback(object);}
229 WebInspector.extensionServer.evaluate(expression,false,false,evaluateOptions,this._category._extensionOrigin,onEvaluate);}}
230 WebInspector.ExtensionAuditFormatters={object:function(expression,title,evaluateOptions)
231 {var parentElement=document.createElement("div");function onEvaluate(remoteObject)
232 {var section=new WebInspector.ObjectPropertiesSection(remoteObject,title);section.expanded=true;section.editable=false;parentElement.appendChild(section.element);}
233 this.evaluate(expression,evaluateOptions,onEvaluate);return parentElement;},node:function(expression,evaluateOptions)
234 {var parentElement=document.createElement("div");function onNodeAvailable(nodeId)
235 {if(!nodeId)
236 return;var node=WebInspector.domModel.nodeForId(nodeId);var renderer=WebInspector.moduleManager.instance(WebInspector.Renderer,node);if(renderer)
237 parentElement.appendChild(renderer.render(node));else
238 console.error("No renderer for node found");}
239 function onEvaluate(remoteObject)
240 {remoteObject.pushNodeToFrontend(onNodeAvailable);}
241 this.evaluate(expression,evaluateOptions,onEvaluate);return parentElement;}}
242 WebInspector.ExtensionAuditCategoryResults._lastId=0;;WebInspector.ExtensionServer=function()
243 {this._clientObjects={};this._handlers={};this._subscribers={};this._subscriptionStartHandlers={};this._subscriptionStopHandlers={};this._extraHeaders={};this._requests={};this._lastRequestId=0;this._registeredExtensions={};this._status=new WebInspector.ExtensionStatus();var commands=WebInspector.extensionAPI.Commands;this._registerHandler(commands.AddAuditCategory,this._onAddAuditCategory.bind(this));this._registerHandler(commands.AddAuditResult,this._onAddAuditResult.bind(this));this._registerHandler(commands.AddConsoleMessage,this._onAddConsoleMessage.bind(this));this._registerHandler(commands.AddRequestHeaders,this._onAddRequestHeaders.bind(this));this._registerHandler(commands.ApplyStyleSheet,this._onApplyStyleSheet.bind(this));this._registerHandler(commands.CreatePanel,this._onCreatePanel.bind(this));this._registerHandler(commands.CreateSidebarPane,this._onCreateSidebarPane.bind(this));this._registerHandler(commands.CreateStatusBarButton,this._onCreateStatusBarButton.bind(this));this._registerHandler(commands.EvaluateOnInspectedPage,this._onEvaluateOnInspectedPage.bind(this));this._registerHandler(commands.ForwardKeyboardEvent,this._onForwardKeyboardEvent.bind(this));this._registerHandler(commands.GetHAR,this._onGetHAR.bind(this));this._registerHandler(commands.GetConsoleMessages,this._onGetConsoleMessages.bind(this));this._registerHandler(commands.GetPageResources,this._onGetPageResources.bind(this));this._registerHandler(commands.GetRequestContent,this._onGetRequestContent.bind(this));this._registerHandler(commands.GetResourceContent,this._onGetResourceContent.bind(this));this._registerHandler(commands.Reload,this._onReload.bind(this));this._registerHandler(commands.SetOpenResourceHandler,this._onSetOpenResourceHandler.bind(this));this._registerHandler(commands.SetResourceContent,this._onSetResourceContent.bind(this));this._registerHandler(commands.SetSidebarHeight,this._onSetSidebarHeight.bind(this));this._registerHandler(commands.SetSidebarContent,this._onSetSidebarContent.bind(this));this._registerHandler(commands.SetSidebarPage,this._onSetSidebarPage.bind(this));this._registerHandler(commands.ShowPanel,this._onShowPanel.bind(this));this._registerHandler(commands.StopAuditCategoryRun,this._onStopAuditCategoryRun.bind(this));this._registerHandler(commands.Subscribe,this._onSubscribe.bind(this));this._registerHandler(commands.OpenResource,this._onOpenResource.bind(this));this._registerHandler(commands.Unsubscribe,this._onUnsubscribe.bind(this));this._registerHandler(commands.UpdateButton,this._onUpdateButton.bind(this));this._registerHandler(commands.UpdateAuditProgress,this._onUpdateAuditProgress.bind(this));window.addEventListener("message",this._onWindowMessage.bind(this),false);this._initExtensions();}
244 WebInspector.ExtensionServer.prototype={hasExtensions:function()
245 {return!!Object.keys(this._registeredExtensions).length;},notifySearchAction:function(panelId,action,searchString)
246 {this._postNotification(WebInspector.extensionAPI.Events.PanelSearch+panelId,action,searchString);},notifyViewShown:function(identifier,frameIndex)
247 {this._postNotification(WebInspector.extensionAPI.Events.ViewShown+identifier,frameIndex);},notifyViewHidden:function(identifier)
248 {this._postNotification(WebInspector.extensionAPI.Events.ViewHidden+identifier);},notifyButtonClicked:function(identifier)
249 {this._postNotification(WebInspector.extensionAPI.Events.ButtonClicked+identifier);},_inspectedURLChanged:function(event)
250 {this._requests={};var url=event.data;this._postNotification(WebInspector.extensionAPI.Events.InspectedURLChanged,url);},startAuditRun:function(category,auditRun)
251 {this._clientObjects[auditRun.id]=auditRun;this._postNotification("audit-started-"+category.id,auditRun.id);},stopAuditRun:function(auditRun)
252 {delete this._clientObjects[auditRun.id];},hasSubscribers:function(type)
253 {return!!this._subscribers[type];},_postNotification:function(type,vararg)
254 {var subscribers=this._subscribers[type];if(!subscribers)
255 return;var message={command:"notify-"+type,arguments:Array.prototype.slice.call(arguments,1)};for(var i=0;i<subscribers.length;++i)
256 subscribers[i].postMessage(message);},_onSubscribe:function(message,port)
257 {var subscribers=this._subscribers[message.type];if(subscribers)
258 subscribers.push(port);else{this._subscribers[message.type]=[port];if(this._subscriptionStartHandlers[message.type])
259 this._subscriptionStartHandlers[message.type]();}},_onUnsubscribe:function(message,port)
260 {var subscribers=this._subscribers[message.type];if(!subscribers)
261 return;subscribers.remove(port);if(!subscribers.length){delete this._subscribers[message.type];if(this._subscriptionStopHandlers[message.type])
262 this._subscriptionStopHandlers[message.type]();}},_onAddRequestHeaders:function(message)
263 {var id=message.extensionId;if(typeof id!=="string")
264 return this._status.E_BADARGTYPE("extensionId",typeof id,"string");var extensionHeaders=this._extraHeaders[id];if(!extensionHeaders){extensionHeaders={};this._extraHeaders[id]=extensionHeaders;}
265 for(var name in message.headers)
266 extensionHeaders[name]=message.headers[name];var allHeaders=({});for(var extension in this._extraHeaders){var headers=this._extraHeaders[extension];for(name in headers){if(typeof headers[name]==="string")
267 allHeaders[name]=headers[name];}}
268 NetworkAgent.setExtraHTTPHeaders(allHeaders);},_onApplyStyleSheet:function(message)
269 {if(!WebInspector.experimentsSettings.applyCustomStylesheet.isEnabled())
270 return;var styleSheet=document.createElement("style");styleSheet.textContent=message.styleSheet;document.head.appendChild(styleSheet);},_onCreatePanel:function(message,port)
271 {var id=message.id;if(id in this._clientObjects||id in WebInspector.panels)
272 return this._status.E_EXISTS(id);var page=this._expandResourcePath(port._extensionOrigin,message.page);var panelDescriptor=new WebInspector.ExtensionServerPanelDescriptor(id,message.title,new WebInspector.ExtensionPanel(id,page));this._clientObjects[id]=panelDescriptor.panel();WebInspector.inspectorView.addPanel(panelDescriptor);return this._status.OK();},_onShowPanel:function(message)
273 {WebInspector.inspectorView.showPanel(message.id);},_onCreateStatusBarButton:function(message,port)
274 {var panel=this._clientObjects[message.panel];if(!panel||!(panel instanceof WebInspector.ExtensionPanel))
275 return this._status.E_NOTFOUND(message.panel);var button=new WebInspector.ExtensionButton(message.id,this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);this._clientObjects[message.id]=button;panel.addStatusBarItem(button.element);return this._status.OK();},_onUpdateButton:function(message,port)
276 {var button=this._clientObjects[message.id];if(!button||!(button instanceof WebInspector.ExtensionButton))
277 return this._status.E_NOTFOUND(message.id);button.update(this._expandResourcePath(port._extensionOrigin,message.icon),message.tooltip,message.disabled);return this._status.OK();},_onCreateSidebarPane:function(message)
278 {var panel=WebInspector.inspectorView.panel(message.panel);if(!panel)
279 return this._status.E_NOTFOUND(message.panel);if(!panel.addExtensionSidebarPane)
280 return this._status.E_NOTSUPPORTED();var id=message.id;var sidebar=new WebInspector.ExtensionSidebarPane(message.title,id);this._clientObjects[id]=sidebar;panel.addExtensionSidebarPane(id,sidebar);return this._status.OK();},_onSetSidebarHeight:function(message)
281 {var sidebar=this._clientObjects[message.id];if(!sidebar)
282 return this._status.E_NOTFOUND(message.id);sidebar.setHeight(message.height);return this._status.OK();},_onSetSidebarContent:function(message,port)
283 {var sidebar=this._clientObjects[message.id];if(!sidebar)
284 return this._status.E_NOTFOUND(message.id);function callback(error)
285 {var result=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,result);}
286 if(message.evaluateOnPage)
287 return sidebar.setExpression(message.expression,message.rootTitle,message.evaluateOptions,port._extensionOrigin,callback.bind(this));sidebar.setObject(message.expression,message.rootTitle,callback.bind(this));},_onSetSidebarPage:function(message,port)
288 {var sidebar=this._clientObjects[message.id];if(!sidebar)
289 return this._status.E_NOTFOUND(message.id);sidebar.setPage(this._expandResourcePath(port._extensionOrigin,message.page));},_onOpenResource:function(message)
290 {var uiSourceCode=WebInspector.workspace.uiSourceCodeForURL(message.url);if(uiSourceCode){WebInspector.Revealer.reveal(new WebInspector.UILocation(uiSourceCode,message.lineNumber,0));return this._status.OK();}
291 var resource=WebInspector.resourceForURL(message.url);if(resource){WebInspector.Revealer.reveal(resource,message.lineNumber);return this._status.OK();}
292 var request=WebInspector.networkLog.requestForURL(message.url);if(request){WebInspector.Revealer.reveal(request);return this._status.OK();}
293 return this._status.E_NOTFOUND(message.url);},_onSetOpenResourceHandler:function(message,port)
294 {var name=this._registeredExtensions[port._extensionOrigin].name||("Extension "+port._extensionOrigin);if(message.handlerPresent)
295 WebInspector.openAnchorLocationRegistry.registerHandler(name,this._handleOpenURL.bind(this,port));else
296 WebInspector.openAnchorLocationRegistry.unregisterHandler(name);},_handleOpenURL:function(port,details)
297 {var url=(details.url);var contentProvider=WebInspector.workspace.uiSourceCodeForOriginURL(url)||WebInspector.resourceForURL(url);if(!contentProvider)
298 return false;var lineNumber=details.lineNumber;if(typeof lineNumber==="number")
299 lineNumber+=1;port.postMessage({command:"open-resource",resource:this._makeResource(contentProvider),lineNumber:lineNumber});return true;},_onReload:function(message)
300 {var options=(message.options||{});NetworkAgent.setUserAgentOverride(typeof options.userAgent==="string"?options.userAgent:"");var injectedScript;if(options.injectedScript)
301 injectedScript="(function(){"+options.injectedScript+"})()";var preprocessingScript=options.preprocessingScript;WebInspector.resourceTreeModel.reloadPage(!!options.ignoreCache,injectedScript,preprocessingScript);return this._status.OK();},_onEvaluateOnInspectedPage:function(message,port)
302 {function callback(error,resultPayload,wasThrown)
303 {var result;if(error||!resultPayload)
304 result=this._status.E_PROTOCOLERROR(error.toString());else if(wasThrown)
305 result={isException:true,value:resultPayload.description};else
306 result={value:resultPayload.value};this._dispatchCallback(message.requestId,port,result);}
307 return this.evaluate(message.expression,true,true,message.evaluateOptions,port._extensionOrigin,callback.bind(this));},_onGetConsoleMessages:function()
308 {return WebInspector.console.messages.map(this._makeConsoleMessage);},_onAddConsoleMessage:function(message)
309 {function convertSeverity(level)
310 {switch(level){case WebInspector.extensionAPI.console.Severity.Log:return WebInspector.ConsoleMessage.MessageLevel.Log;case WebInspector.extensionAPI.console.Severity.Warning:return WebInspector.ConsoleMessage.MessageLevel.Warning;case WebInspector.extensionAPI.console.Severity.Error:return WebInspector.ConsoleMessage.MessageLevel.Error;case WebInspector.extensionAPI.console.Severity.Debug:return WebInspector.ConsoleMessage.MessageLevel.Debug;}}
311 var level=convertSeverity(message.severity);if(!level)
312 return this._status.E_BADARG("message.severity",message.severity);var consoleMessage=new WebInspector.ConsoleMessage(WebInspector.ConsoleMessage.MessageSource.JS,level,message.text,WebInspector.ConsoleMessage.MessageType.Log,message.url,message.line);WebInspector.console.addMessage(consoleMessage);},_makeConsoleMessage:function(message)
313 {function convertLevel(level)
314 {if(!level)
315 return;switch(level){case WebInspector.ConsoleMessage.MessageLevel.Log:return WebInspector.extensionAPI.console.Severity.Log;case WebInspector.ConsoleMessage.MessageLevel.Warning:return WebInspector.extensionAPI.console.Severity.Warning;case WebInspector.ConsoleMessage.MessageLevel.Error:return WebInspector.extensionAPI.console.Severity.Error;case WebInspector.ConsoleMessage.MessageLevel.Debug:return WebInspector.extensionAPI.console.Severity.Debug;default:return WebInspector.extensionAPI.console.Severity.Log;}}
316 var result={severity:convertLevel(message.level),text:message.messageText,};if(message.url)
317 result.url=message.url;if(message.line)
318 result.line=message.line;return result;},_onGetHAR:function()
319 {var requests=WebInspector.networkLog.requests;var harLog=(new WebInspector.HARLog(requests)).build();for(var i=0;i<harLog.entries.length;++i)
320 harLog.entries[i]._requestId=this._requestId(requests[i]);return harLog;},_makeResource:function(contentProvider)
321 {return{url:contentProvider.contentURL(),type:contentProvider.contentType().name()};},_onGetPageResources:function()
322 {var resources={};function pushResourceData(contentProvider)
323 {if(!resources[contentProvider.contentURL()])
324 resources[contentProvider.contentURL()]=this._makeResource(contentProvider);}
325 var uiSourceCodes=WebInspector.workspace.uiSourceCodesForProjectType(WebInspector.projectTypes.Network);uiSourceCodes.forEach(pushResourceData.bind(this));WebInspector.resourceTreeModel.forAllResources(pushResourceData.bind(this));return Object.values(resources);},_getResourceContent:function(contentProvider,message,port)
326 {function onContentAvailable(content)
327 {var response={encoding:(content===null)||contentProvider.contentType().isTextType()?"":"base64",content:content};this._dispatchCallback(message.requestId,port,response);}
328 contentProvider.requestContent(onContentAvailable.bind(this));},_onGetRequestContent:function(message,port)
329 {var request=this._requestById(message.id);if(!request)
330 return this._status.E_NOTFOUND(message.id);this._getResourceContent(request,message,port);},_onGetResourceContent:function(message,port)
331 {var url=(message.url);var contentProvider=WebInspector.workspace.uiSourceCodeForOriginURL(url)||WebInspector.resourceForURL(url);if(!contentProvider)
332 return this._status.E_NOTFOUND(url);this._getResourceContent(contentProvider,message,port);},_onSetResourceContent:function(message,port)
333 {function callbackWrapper(error)
334 {var response=error?this._status.E_FAILED(error):this._status.OK();this._dispatchCallback(message.requestId,port,response);}
335 var url=(message.url);var uiSourceCode=WebInspector.workspace.uiSourceCodeForOriginURL(url);if(!uiSourceCode){var resource=WebInspector.resourceTreeModel.resourceForURL(url);if(!resource)
336 return this._status.E_NOTFOUND(url);return this._status.E_NOTSUPPORTED("Resource is not editable")}
337 uiSourceCode.setWorkingCopy(message.content);if(message.commit)
338 uiSourceCode.commitWorkingCopy(callbackWrapper.bind(this));else
339 callbackWrapper.call(this,null);},_requestId:function(request)
340 {if(!request._extensionRequestId){request._extensionRequestId=++this._lastRequestId;this._requests[request._extensionRequestId]=request;}
341 return request._extensionRequestId;},_requestById:function(id)
342 {return this._requests[id];},_onAddAuditCategory:function(message,port)
343 {var category=new WebInspector.ExtensionAuditCategory(port._extensionOrigin,message.id,message.displayName,message.resultCount);if(WebInspector.inspectorView.panel("audits").getCategory(category.id))
344 return this._status.E_EXISTS(category.id);this._clientObjects[message.id]=category;WebInspector.inspectorView.panel("audits").addCategory(category);},_onAddAuditResult:function(message)
345 {var auditResult=this._clientObjects[message.resultId];if(!auditResult)
346 return this._status.E_NOTFOUND(message.resultId);try{auditResult.addResult(message.displayName,message.description,message.severity,message.details);}catch(e){return e;}
347 return this._status.OK();},_onUpdateAuditProgress:function(message)
348 {var auditResult=this._clientObjects[message.resultId];if(!auditResult)
349 return this._status.E_NOTFOUND(message.resultId);auditResult.updateProgress(Math.min(Math.max(0,message.progress),1));},_onStopAuditCategoryRun:function(message)
350 {var auditRun=this._clientObjects[message.resultId];if(!auditRun)
351 return this._status.E_NOTFOUND(message.resultId);auditRun.done();},_onForwardKeyboardEvent:function(message)
352 {const Esc="U+001B";message.entries.forEach(handleEventEntry);function handleEventEntry(entry)
353 {if(!entry.ctrlKey&&!entry.altKey&&!entry.metaKey&&!/^F\d+$/.test(entry.keyIdentifier)&&entry.keyIdentifier!==Esc)
354 return;var event=new window.KeyboardEvent(entry.eventType,{keyIdentifier:entry.keyIdentifier,location:entry.location,ctrlKey:entry.ctrlKey,altKey:entry.altKey,shiftKey:entry.shiftKey,metaKey:entry.metaKey});event.__keyCode=keyCodeForEntry(entry);document.dispatchEvent(event);}
355 function keyCodeForEntry(entry)
356 {var keyCode=entry.keyCode;if(!keyCode){var match=entry.keyIdentifier.match(/^U\+([\dA-Fa-f]+)$/);if(match)
357 keyCode=parseInt(match[1],16);}
358 return keyCode||0;}},_dispatchCallback:function(requestId,port,result)
359 {if(requestId)
360 port.postMessage({command:"callback",requestId:requestId,result:result});},_initExtensions:function()
361 {this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ConsoleMessageAdded,WebInspector.console,WebInspector.ConsoleModel.Events.MessageAdded,this._notifyConsoleMessageAdded);this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.NetworkRequestFinished,WebInspector.networkManager,WebInspector.NetworkManager.EventTypes.RequestFinished,this._notifyRequestFinished);this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceAdded,WebInspector.workspace,WebInspector.Workspace.Events.UISourceCodeAdded,this._notifyResourceAdded);function onElementsSubscriptionStarted()
362 {WebInspector.notifications.addEventListener(WebInspector.NotificationService.Events.SelectedNodeChanged,this._notifyElementsSelectionChanged,this);}
363 function onElementsSubscriptionStopped()
364 {WebInspector.notifications.removeEventListener(WebInspector.NotificationService.Events.SelectedNodeChanged,this._notifyElementsSelectionChanged,this);}
365 this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.PanelObjectSelected+"elements",onElementsSubscriptionStarted.bind(this),onElementsSubscriptionStopped.bind(this));this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.PanelObjectSelected+"sources",WebInspector.notifications,WebInspector.SourceFrame.Events.SelectionChanged,this._notifySourceFrameSelectionChanged);this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted);function onTimelineSubscriptionStarted()
366 {WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded,this._notifyTimelineEventRecorded,this);WebInspector.timelineManager.start();}
367 function onTimelineSubscriptionStopped()
368 {WebInspector.timelineManager.stop();WebInspector.timelineManager.removeEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded,this._notifyTimelineEventRecorded,this);}
369 this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.TimelineEventRecorded,onTimelineSubscriptionStarted.bind(this),onTimelineSubscriptionStopped.bind(this));WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged,this._inspectedURLChanged,this);InspectorExtensionRegistry.getExtensionsAsync();},_makeSourceSelection:function(textRange)
370 {var sourcesPanel=WebInspector.inspectorView.panel("sources");var selection={startLine:textRange.startLine,startColumn:textRange.startColumn,endLine:textRange.endLine,endColumn:textRange.endColumn,url:sourcesPanel.sourcesView().currentUISourceCode().uri()};return selection;},_notifySourceFrameSelectionChanged:function(event)
371 {this._postNotification(WebInspector.extensionAPI.Events.PanelObjectSelected+"sources",this._makeSourceSelection(event.data));},_notifyConsoleMessageAdded:function(event)
372 {this._postNotification(WebInspector.extensionAPI.Events.ConsoleMessageAdded,this._makeConsoleMessage(event.data));},_notifyResourceAdded:function(event)
373 {var uiSourceCode=(event.data);this._postNotification(WebInspector.extensionAPI.Events.ResourceAdded,this._makeResource(uiSourceCode));},_notifyUISourceCodeContentCommitted:function(event)
374 {var uiSourceCode=(event.data.uiSourceCode);var content=(event.data.content);this._postNotification(WebInspector.extensionAPI.Events.ResourceContentCommitted,this._makeResource(uiSourceCode),content);},_notifyRequestFinished:function(event)
375 {var request=(event.data);this._postNotification(WebInspector.extensionAPI.Events.NetworkRequestFinished,this._requestId(request),(new WebInspector.HAREntry(request)).build());},_notifyElementsSelectionChanged:function()
376 {this._postNotification(WebInspector.extensionAPI.Events.PanelObjectSelected+"elements");},_notifyTimelineEventRecorded:function(event)
377 {this._postNotification(WebInspector.extensionAPI.Events.TimelineEventRecorded,event.data);},addExtensions:function(extensionInfos)
378 {extensionInfos.forEach(this._addExtension,this);},_addExtension:function(extensionInfo)
379 {const urlOriginRegExp=new RegExp("([^:]+:\/\/[^/]*)\/");var startPage=extensionInfo.startPage;var name=extensionInfo.name;try{var originMatch=urlOriginRegExp.exec(startPage);if(!originMatch){console.error("Skipping extension with invalid URL: "+startPage);return false;}
380 var extensionOrigin=originMatch[1];if(!this._registeredExtensions[extensionOrigin]){InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin,buildExtensionAPIInjectedScript(extensionInfo));this._registeredExtensions[extensionOrigin]={name:name};}
381 var iframe=document.createElement("iframe");iframe.src=startPage;iframe.style.display="none";document.body.appendChild(iframe);}catch(e){console.error("Failed to initialize extension "+startPage+":"+e);return false;}
382 return true;},_registerExtension:function(origin,port)
383 {if(!this._registeredExtensions.hasOwnProperty(origin)){if(origin!==window.location.origin)
384 console.error("Ignoring unauthorized client request from "+origin);return;}
385 port._extensionOrigin=origin;port.addEventListener("message",this._onmessage.bind(this),false);port.start();},_onWindowMessage:function(event)
386 {if(event.data==="registerExtension")
387 this._registerExtension(event.origin,event.ports[0]);},_onmessage:function(event)
388 {var message=event.data;var result;if(message.command in this._handlers)
389 result=this._handlers[message.command](message,event.target);else
390 result=this._status.E_NOTSUPPORTED(message.command);if(result&&message.requestId)
391 this._dispatchCallback(message.requestId,event.target,result);},_registerHandler:function(command,callback)
392 {console.assert(command);this._handlers[command]=callback;},_registerSubscriptionHandler:function(eventTopic,onSubscribeFirst,onUnsubscribeLast)
393 {this._subscriptionStartHandlers[eventTopic]=onSubscribeFirst;this._subscriptionStopHandlers[eventTopic]=onUnsubscribeLast;},_registerAutosubscriptionHandler:function(eventTopic,eventTarget,frontendEventType,handler)
394 {this._registerSubscriptionHandler(eventTopic,eventTarget.addEventListener.bind(eventTarget,frontendEventType,handler,this),eventTarget.removeEventListener.bind(eventTarget,frontendEventType,handler,this));},_registerResourceContentCommittedHandler:function(handler)
395 {function addFirstEventListener()
396 {WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted,handler,this);WebInspector.workspace.setHasResourceContentTrackingExtensions(true);}
397 function removeLastEventListener()
398 {WebInspector.workspace.setHasResourceContentTrackingExtensions(false);WebInspector.workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted,handler,this);}
399 this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.ResourceContentCommitted,addFirstEventListener.bind(this),removeLastEventListener.bind(this));},_expandResourcePath:function(extensionPath,resourcePath)
400 {if(!resourcePath)
401 return;return extensionPath+this._normalizePath(resourcePath);},_normalizePath:function(path)
402 {var source=path.split("/");var result=[];for(var i=0;i<source.length;++i){if(source[i]===".")
403 continue;if(source[i]==="")
404 continue;if(source[i]==="..")
405 result.pop();else
406 result.push(source[i]);}
407 return"/"+result.join("/");},evaluate:function(expression,exposeCommandLineAPI,returnByValue,options,securityOrigin,callback)
408 {var contextId;function resolveURLToFrame(url)
409 {var found;function hasMatchingURL(frame)
410 {found=(frame.url===url)?frame:null;return found;}
411 WebInspector.resourceTreeModel.frames().some(hasMatchingURL);return found;}
412 if(typeof options==="object"){var frame=options.frameURL?resolveURLToFrame(options.frameURL):WebInspector.resourceTreeModel.mainFrame;if(!frame){if(options.frameURL)
413 console.warn("evaluate: there is no frame with URL "+options.frameURL);else
414 console.warn("evaluate: the main frame is not yet available");return this._status.E_NOTFOUND(options.frameURL||"<top>");}
415 var contextSecurityOrigin;if(options.useContentScriptContext)
416 contextSecurityOrigin=securityOrigin;else if(options.scriptExecutionContext)
417 contextSecurityOrigin=options.scriptExecutionContext;var frameContextList=WebInspector.runtimeModel.contextListByFrame(frame);var context;if(contextSecurityOrigin){context=frameContextList.contextBySecurityOrigin(contextSecurityOrigin);if(!context){console.warn("The JavaScript context "+contextSecurityOrigin+" was not found in the frame "+frame.url)
418 return this._status.E_NOTFOUND(contextSecurityOrigin)}}else{context=frameContextList.mainWorldContext();if(!context)
419 return this._status.E_FAILED(frame.url+" has no execution context");}
420 contextId=context.id;}
421 RuntimeAgent.evaluate(expression,"extension",exposeCommandLineAPI,true,contextId,returnByValue,false,callback);}}
422 WebInspector.ExtensionServerPanelDescriptor=function(name,title,panel)
423 {this._name=name;this._title=title;this._panel=panel;}
424 WebInspector.ExtensionServerPanelDescriptor.prototype={name:function()
425 {return this._name;},title:function()
426 {return this._title;},panel:function()
427 {return this._panel;}}
428 WebInspector.ExtensionStatus=function()
429 {function makeStatus(code,description)
430 {var details=Array.prototype.slice.call(arguments,2);var status={code:code,description:description,details:details};if(code!=="OK"){status.isError=true;console.log("Extension server error: "+String.vsprintf(description,details));}
431 return status;}
432 this.OK=makeStatus.bind(null,"OK","OK");this.E_EXISTS=makeStatus.bind(null,"E_EXISTS","Object already exists: %s");this.E_BADARG=makeStatus.bind(null,"E_BADARG","Invalid argument %s: %s");this.E_BADARGTYPE=makeStatus.bind(null,"E_BADARGTYPE","Invalid type for argument %s: got %s, expected %s");this.E_NOTFOUND=makeStatus.bind(null,"E_NOTFOUND","Object not found: %s");this.E_NOTSUPPORTED=makeStatus.bind(null,"E_NOTSUPPORTED","Object does not support requested operation: %s");this.E_PROTOCOLERROR=makeStatus.bind(null,"E_PROTOCOLERROR","Inspector protocol error: %s");this.E_FAILED=makeStatus.bind(null,"E_FAILED","Operation failed: %s");}
433 WebInspector.ExtensionStatus.Record;WebInspector.extensionAPI={};defineCommonExtensionSymbols(WebInspector.extensionAPI);WebInspector.ExtensionPanel=function(id,pageURL)
434 {WebInspector.Panel.call(this,id);this.setHideOnDetach();this.element.classList.add("extension-panel");this._panelStatusBarElement=this.element.createChild("div","panel-status-bar hidden");this._searchableView=new WebInspector.SearchableView(this);this._searchableView.show(this.element);var extensionView=new WebInspector.ExtensionView(id,pageURL,"extension panel");extensionView.show(this._searchableView.element);this.setDefaultFocusedElement(extensionView.defaultFocusedElement());}
435 WebInspector.ExtensionPanel.prototype={defaultFocusedElement:function()
436 {return WebInspector.View.prototype.defaultFocusedElement.call(this);},addStatusBarItem:function(element)
437 {this._panelStatusBarElement.classList.remove("hidden");this._panelStatusBarElement.appendChild(element);},searchCanceled:function()
438 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.CancelSearch);this._searchableView.updateSearchMatchesCount(0);},searchableView:function()
439 {return this._searchableView;},performSearch:function(query,shouldJump)
440 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.PerformSearch,query);},jumpToNextSearchResult:function()
441 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.NextSearchResult);},jumpToPreviousSearchResult:function()
442 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.PreviousSearchResult);},__proto__:WebInspector.Panel.prototype}
443 WebInspector.ExtensionButton=function(id,iconURL,tooltip,disabled)
444 {this._id=id;this.element=document.createElement("button");this.element.className="status-bar-item extension";this.element.addEventListener("click",this._onClicked.bind(this),false);this.update(iconURL,tooltip,disabled);}
445 WebInspector.ExtensionButton.prototype={update:function(iconURL,tooltip,disabled)
446 {if(typeof iconURL==="string")
447 this.element.style.backgroundImage="url("+iconURL+")";if(typeof tooltip==="string")
448 this.element.title=tooltip;if(typeof disabled==="boolean")
449 this.element.disabled=disabled;},_onClicked:function()
450 {WebInspector.extensionServer.notifyButtonClicked(this._id);}}
451 WebInspector.ExtensionSidebarPane=function(title,id)
452 {WebInspector.SidebarPane.call(this,title);this.setHideOnDetach();this._id=id;}
453 WebInspector.ExtensionSidebarPane.prototype={setObject:function(object,title,callback)
454 {this._createObjectPropertiesView();this._setObject(WebInspector.RemoteObject.fromLocalObject(object),title,callback);},setExpression:function(expression,title,evaluateOptions,securityOrigin,callback)
455 {this._createObjectPropertiesView();WebInspector.extensionServer.evaluate(expression,true,false,evaluateOptions,securityOrigin,this._onEvaluate.bind(this,title,callback));},setPage:function(url)
456 {if(this._objectPropertiesView){this._objectPropertiesView.detach();delete this._objectPropertiesView;}
457 if(this._extensionView)
458 this._extensionView.detach(true);this._extensionView=new WebInspector.ExtensionView(this._id,url,"extension fill");this._extensionView.show(this.bodyElement);if(!this.bodyElement.style.height)
459 this.setHeight("150px");},setHeight:function(height)
460 {this.bodyElement.style.height=height;},_onEvaluate:function(title,callback,error,result,wasThrown)
461 {if(error)
462 callback(error.toString());else
463 this._setObject(WebInspector.RemoteObject.fromPayload(result),title,callback);},_createObjectPropertiesView:function()
464 {if(this._objectPropertiesView)
465 return;if(this._extensionView){this._extensionView.detach(true);delete this._extensionView;}
466 this._objectPropertiesView=new WebInspector.ExtensionNotifierView(this._id);this._objectPropertiesView.show(this.bodyElement);},_setObject:function(object,title,callback)
467 {if(!this._objectPropertiesView){callback("operation cancelled");return;}
468 this._objectPropertiesView.element.removeChildren();var section=new WebInspector.ObjectPropertiesSection(object,title);if(!title)
469 section.headerElement.classList.add("hidden");section.expanded=true;section.editable=false;this._objectPropertiesView.element.appendChild(section.element);callback();},__proto__:WebInspector.SidebarPane.prototype};WebInspector.ExtensionView=function(id,src,className)
470 {WebInspector.View.call(this);this.element.className="extension-view fill";this._id=id;this._iframe=document.createElement("iframe");this._iframe.addEventListener("load",this._onLoad.bind(this),false);this._iframe.src=src;this._iframe.className=className;this.setDefaultFocusedElement(this._iframe);this.element.appendChild(this._iframe);}
471 WebInspector.ExtensionView.prototype={wasShown:function()
472 {if(typeof this._frameIndex==="number")
473 WebInspector.extensionServer.notifyViewShown(this._id,this._frameIndex);},willHide:function()
474 {if(typeof this._frameIndex==="number")
475 WebInspector.extensionServer.notifyViewHidden(this._id);},_onLoad:function()
476 {var frames=(window.frames);this._frameIndex=Array.prototype.indexOf.call(frames,this._iframe.contentWindow);if(this.isShowing())
477 WebInspector.extensionServer.notifyViewShown(this._id,this._frameIndex);},__proto__:WebInspector.View.prototype}
478 WebInspector.ExtensionNotifierView=function(id)
479 {WebInspector.VBox.call(this);this._id=id;}
480 WebInspector.ExtensionNotifierView.prototype={wasShown:function()
481 {WebInspector.extensionServer.notifyViewShown(this._id);},willHide:function()
482 {WebInspector.extensionServer.notifyViewHidden(this._id);},__proto__:WebInspector.VBox.prototype};