Upstream version 10.39.225.0
[platform/framework/web/crosswalk.git] / src / chrome / tools / test / reference_build / chrome_linux / resources / inspector / extensions / ExtensionServer.js
1 function defineCommonExtensionSymbols(apiPrivate)
2 {if(!apiPrivate.audits)
3 apiPrivate.audits={};apiPrivate.audits.Severity={Info:"info",Warning:"warning",Severe:"severe"};if(!apiPrivate.console)
4 apiPrivate.console={};apiPrivate.console.Severity={Debug:"debug",Log:"log",Warning:"warning",Error:"error"};if(!apiPrivate.panels)
5 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"};}
6 function injectedExtensionAPI(injectedScriptId)
7 {var apiPrivate={};defineCommonExtensionSymbols(apiPrivate);var commands=apiPrivate.Commands;var events=apiPrivate.Events;var userAction=false;function EventSinkImpl(type,customDispatch)
8 {this._type=type;this._listeners=[];this._customDispatch=customDispatch;}
9 EventSinkImpl.prototype={addListener:function(callback)
10 {if(typeof callback!=="function")
11 throw"addListener: callback is not a function";if(this._listeners.length===0)
12 extensionServer.sendRequest({command:commands.Subscribe,type:this._type});this._listeners.push(callback);extensionServer.registerHandler("notify-"+this._type,this._dispatch.bind(this));},removeListener:function(callback)
13 {var listeners=this._listeners;for(var i=0;i<listeners.length;++i){if(listeners[i]===callback){listeners.splice(i,1);break;}}
14 if(this._listeners.length===0)
15 extensionServer.sendRequest({command:commands.Unsubscribe,type:this._type});},_fire:function(vararg)
16 {var listeners=this._listeners.slice();for(var i=0;i<listeners.length;++i)
17 listeners[i].apply(null,arguments);},_dispatch:function(request)
18 {if(this._customDispatch)
19 this._customDispatch.call(this,request);else
20 this._fire.apply(this,request.arguments);}}
21 function InspectorExtensionAPI()
22 {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();}
23 function ConsoleAPI()
24 {this.onMessageAdded=new EventSink(events.ConsoleMessageAdded);}
25 ConsoleAPI.prototype={getMessages:function(callback)
26 {extensionServer.sendRequest({command:commands.GetConsoleMessages},callback);},addMessage:function(severity,text,url,line)
27 {extensionServer.sendRequest({command:commands.AddConsoleMessage,severity:severity,text:text,url:url,line:line});},get Severity()
28 {return apiPrivate.console.Severity;}}
29 function Network()
30 {function dispatchRequestEvent(message)
31 {var request=message.arguments[1];request.__proto__=new Request(message.arguments[0]);this._fire(request);}
32 this.onRequestFinished=new EventSink(events.NetworkRequestFinished,dispatchRequestEvent);defineDeprecatedProperty(this,"network","onFinished","onRequestFinished");this.onNavigated=new EventSink(events.InspectedURLChanged);}
33 Network.prototype={getHAR:function(callback)
34 {function callbackWrapper(result)
35 {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;}
36 callback(result);}
37 extensionServer.sendRequest({command:commands.GetHAR},callback&&callbackWrapper);},addRequestHeaders:function(headers)
38 {extensionServer.sendRequest({command:commands.AddRequestHeaders,headers:headers,extensionId:window.location.hostname});}}
39 function RequestImpl(id)
40 {this._id=id;}
41 RequestImpl.prototype={getContent:function(callback)
42 {function callbackWrapper(response)
43 {callback(response.content,response.encoding);}
44 extensionServer.sendRequest({command:commands.GetRequestContent,id:this._id},callback&&callbackWrapper);}}
45 function Panels()
46 {var panels={elements:new ElementsPanel(),sources:new SourcesPanel(),};function panelGetter(name)
47 {return panels[name];}
48 for(var panel in panels)
49 this.__defineGetter__(panel,panelGetter.bind(null,panel));this.applyStyleSheet=function(styleSheet){extensionServer.sendRequest({command:commands.ApplyStyleSheet,styleSheet:styleSheet});};}
50 Panels.prototype={create:function(title,icon,page,callback)
51 {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)
52 {var hadHandler=extensionServer.hasHandler(events.OpenResource);function callbackWrapper(message)
53 {userAction=true;try{callback.call(null,new Resource(message.resource),message.lineNumber);}finally{userAction=false;}}
54 if(!callback)
55 extensionServer.unregisterHandler(events.OpenResource);else
56 extensionServer.registerHandler(events.OpenResource,callbackWrapper);if(hadHandler===!callback)
57 extensionServer.sendRequest({command:commands.SetOpenResourceHandler,"handlerPresent":!!callback});},openResource:function(url,lineNumber,callback)
58 {extensionServer.sendRequest({command:commands.OpenResource,"url":url,"lineNumber":lineNumber},callback);},get SearchAction()
59 {return apiPrivate.panels.SearchAction;}}
60 function ExtensionViewImpl(id)
61 {this._id=id;function dispatchShowEvent(message)
62 {var frameIndex=message.arguments[0];if(typeof frameIndex==="number")
63 this._fire(window.parent.frames[frameIndex]);else
64 this._fire();}
65 if(id){this.onShown=new EventSink(events.ViewShown+id,dispatchShowEvent);this.onHidden=new EventSink(events.ViewHidden+id);}}
66 function PanelWithSidebarImpl(hostPanelName)
67 {ExtensionViewImpl.call(this,null);this._hostPanelName=hostPanelName;this.onSelectionChanged=new EventSink(events.PanelObjectSelected+hostPanelName);}
68 PanelWithSidebarImpl.prototype={createSidebarPane:function(title,callback)
69 {var id="extension-sidebar-"+extensionServer.nextObjectId();var request={command:commands.CreateSidebarPane,panel:this._hostPanelName,id:id,title:title};function callbackWrapper()
70 {callback(new ExtensionSidebarPane(id));}
71 extensionServer.sendRequest(request,callback&&callbackWrapper);},__proto__:ExtensionViewImpl.prototype}
72 function declareInterfaceClass(implConstructor)
73 {return function()
74 {var impl={__proto__:implConstructor.prototype};implConstructor.apply(impl,arguments);populateInterfaceClass(this,impl);}}
75 function defineDeprecatedProperty(object,className,oldName,newName)
76 {var warningGiven=false;function getter()
77 {if(!warningGiven){console.warn(className+"."+oldName+" is deprecated. Use "+className+"."+newName+" instead");warningGiven=true;}
78 return object[newName];}
79 object.__defineGetter__(oldName,getter);}
80 function extractCallbackArgument(args)
81 {var lastArgument=args[args.length-1];return typeof lastArgument==="function"?lastArgument:undefined;}
82 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()
83 {PanelWithSidebar.call(this,"elements");}
84 ElementsPanel.prototype={__proto__:PanelWithSidebar.prototype}
85 function SourcesPanel()
86 {PanelWithSidebar.call(this,"sources");}
87 SourcesPanel.prototype={__proto__:PanelWithSidebar.prototype}
88 function ExtensionPanelImpl(id)
89 {ExtensionViewImpl.call(this,id);this.onSearch=new EventSink(events.PanelSearch+id);}
90 ExtensionPanelImpl.prototype={createStatusBarButton:function(iconPath,tooltipText,disabled)
91 {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()
92 {if(!userAction)
93 return;var request={command:commands.ShowPanel,id:this._id};extensionServer.sendRequest(request);},__proto__:ExtensionViewImpl.prototype}
94 function ExtensionSidebarPaneImpl(id)
95 {ExtensionViewImpl.call(this,id);}
96 ExtensionSidebarPaneImpl.prototype={setHeight:function(height)
97 {extensionServer.sendRequest({command:commands.SetSidebarHeight,id:this._id,height:height});},setExpression:function(expression,rootTitle,evaluateOptions)
98 {var request={command:commands.SetSidebarContent,id:this._id,expression:expression,rootTitle:rootTitle,evaluateOnPage:true,};if(typeof evaluateOptions==="object")
99 request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,extractCallbackArgument(arguments));},setObject:function(jsonObject,rootTitle,callback)
100 {extensionServer.sendRequest({command:commands.SetSidebarContent,id:this._id,expression:jsonObject,rootTitle:rootTitle},callback);},setPage:function(page)
101 {extensionServer.sendRequest({command:commands.SetSidebarPage,id:this._id,page:page});},__proto__:ExtensionViewImpl.prototype}
102 function ButtonImpl(id)
103 {this._id=id;this.onClicked=new EventSink(events.ButtonClicked+id);}
104 ButtonImpl.prototype={update:function(iconPath,tooltipText,disabled)
105 {var request={command:commands.UpdateButton,id:this._id,icon:iconPath,tooltip:tooltipText,disabled:!!disabled};extensionServer.sendRequest(request);}};function Audits()
106 {}
107 Audits.prototype={addCategory:function(displayName,resultCount)
108 {var id="extension-audit-category-"+extensionServer.nextObjectId();if(typeof resultCount!=="undefined")
109 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);}}
110 function AuditCategoryImpl(id)
111 {function dispatchAuditEvent(request)
112 {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();}}
113 this._id=id;this.onAuditStarted=new EventSink(events.AuditStarted+id,dispatchAuditEvent);}
114 function AuditResultImpl(id)
115 {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");}
116 AuditResultImpl.prototype={addResult:function(displayName,description,severity,details)
117 {if(details&&!(details instanceof AuditResultNode))
118 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()
119 {return new AuditResultNode(Array.prototype.slice.call(arguments));},updateProgress:function(worked,totalWork)
120 {extensionServer.sendRequest({command:commands.UpdateAuditProgress,resultId:this._id,progress:worked/totalWork});},done:function()
121 {extensionServer.sendRequest({command:commands.StopAuditCategoryRun,resultId:this._id});},get Severity()
122 {return apiPrivate.audits.Severity;},createResourceLink:function(url,lineNumber)
123 {return{type:"resourceLink",arguments:[url,lineNumber&&lineNumber-1]};},_nodeFactory:function(type)
124 {return{type:type,arguments:Array.prototype.slice.call(arguments,1)};}}
125 function AuditResultNode(contents)
126 {this.contents=contents;this.children=[];this.expanded=false;}
127 AuditResultNode.prototype={addChild:function()
128 {var node=new AuditResultNode(Array.prototype.slice.call(arguments));this.children.push(node);return node;}};function InspectedWindow()
129 {function dispatchResourceEvent(message)
130 {this._fire(new Resource(message.arguments[0]));}
131 function dispatchResourceContentEvent(message)
132 {this._fire(new Resource(message.arguments[0]),message.arguments[1]);}
133 this.onResourceAdded=new EventSink(events.ResourceAdded,dispatchResourceEvent);this.onResourceContentCommitted=new EventSink(events.ResourceContentCommitted,dispatchResourceContentEvent);}
134 InspectedWindow.prototype={reload:function(optionsOrUserAgent)
135 {var options=null;if(typeof optionsOrUserAgent==="object")
136 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.");}
137 extensionServer.sendRequest({command:commands.Reload,options:options});},eval:function(expression,evaluateOptions)
138 {var callback=extractCallbackArgument(arguments);function callbackWrapper(result)
139 {if(result.isError||result.isException)
140 callback(undefined,result);else
141 callback(result.value);}
142 var request={command:commands.EvaluateOnInspectedPage,expression:expression};if(typeof evaluateOptions==="object")
143 request.evaluateOptions=evaluateOptions;extensionServer.sendRequest(request,callback&&callbackWrapper);return null;},getResources:function(callback)
144 {function wrapResource(resourceData)
145 {return new Resource(resourceData);}
146 function callbackWrapper(resources)
147 {callback(resources.map(wrapResource));}
148 extensionServer.sendRequest({command:commands.GetPageResources},callback&&callbackWrapper);}}
149 function ResourceImpl(resourceData)
150 {this._url=resourceData.url
151 this._type=resourceData.type;}
152 ResourceImpl.prototype={get url()
153 {return this._url;},get type()
154 {return this._type;},getContent:function(callback)
155 {function callbackWrapper(response)
156 {callback(response.content,response.encoding);}
157 extensionServer.sendRequest({command:commands.GetResourceContent,url:this._url},callback&&callbackWrapper);},setContent:function(content,commit,callback)
158 {extensionServer.sendRequest({command:commands.SetResourceContent,url:this._url,content:content,commit:commit},callback);}}
159 function TimelineImpl()
160 {this.onEventRecorded=new EventSink(events.TimelineEventRecorded);}
161 var keyboardEventRequestQueue=[];var forwardTimer=null;function forwardKeyboardEvent(event)
162 {const Esc="U+001B";if(!event.ctrlKey&&!event.altKey&&!event.metaKey&&!/^F\d+$/.test(event.keyIdentifier)&&event.keyIdentifier!==Esc)
163 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)
164 forwardTimer=setTimeout(forwardEventQueue,0);}
165 function forwardEventQueue()
166 {forwardTimer=null;var request={command:commands.ForwardKeyboardEvent,entries:keyboardEventRequestQueue};extensionServer.sendRequest(request);keyboardEventRequestQueue=[];}
167 document.addEventListener("keydown",forwardKeyboardEvent,false);document.addEventListener("keypress",forwardKeyboardEvent,false);function ExtensionServerClient()
168 {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],"*");}
169 ExtensionServerClient.prototype={sendRequest:function(message,callback)
170 {if(typeof callback==="function")
171 message.requestId=this._registerCallback(callback);this._port.postMessage(message);},hasHandler:function(command)
172 {return!!this._handlers[command];},registerHandler:function(command,handler)
173 {this._handlers[command]=handler;},unregisterHandler:function(command)
174 {delete this._handlers[command];},nextObjectId:function()
175 {return injectedScriptId+"_"+ ++this._lastObjectId;},_registerCallback:function(callback)
176 {var id=++this._lastRequestId;this._callbacks[id]=callback;return id;},_onCallback:function(request)
177 {if(request.requestId in this._callbacks){var callback=this._callbacks[request.requestId];delete this._callbacks[request.requestId];callback(request.result);}},_onMessage:function(event)
178 {var request=event.data;var handler=this._handlers[request.command];if(handler)
179 handler.call(this,request);}}
180 function populateInterfaceClass(interfaze,implementation)
181 {for(var member in implementation){if(member.charAt(0)==="_")
182 continue;var descriptor=null;for(var owner=implementation;owner&&!descriptor;owner=owner.__proto__)
183 descriptor=Object.getOwnPropertyDescriptor(owner,member);if(!descriptor)
184 continue;if(typeof descriptor.value==="function")
185 interfaze[member]=descriptor.value.bind(implementation);else if(typeof descriptor.get==="function")
186 interfaze.__defineGetter__(member,descriptor.get.bind(implementation));else
187 Object.defineProperty(interfaze,member,descriptor);}}
188 if(!extensionServer)
189 extensionServer=new ExtensionServerClient();return new InspectorExtensionAPI();}
190 function platformExtensionAPI(coreAPI)
191 {function getTabId()
192 {return tabId;}
193 chrome=window.chrome||{};var devtools_descriptor=Object.getOwnPropertyDescriptor(chrome,"devtools");if(!devtools_descriptor||devtools_descriptor.get)
194 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);}
195 chrome.experimental.devtools.inspectedWindow=chrome.devtools.inspectedWindow;}
196 if(extensionInfo.exposeWebInspectorNamespace)
197 window.webInspector=coreAPI;}
198 function buildPlatformExtensionAPI(extensionInfo)
199 {return"var extensionInfo = "+JSON.stringify(extensionInfo)+";"+"var tabId = "+WebInspector._inspectedTabId+";"+
200 platformExtensionAPI.toString();}
201 function buildExtensionAPIInjectedScript(extensionInfo)
202 {return"(function(injectedScriptId){ "+"var extensionServer;"+
203 defineCommonExtensionSymbols.toString()+";"+
204 injectedExtensionAPI.toString()+";"+
205 buildPlatformExtensionAPI(extensionInfo)+";"+"platformExtensionAPI(injectedExtensionAPI(injectedScriptId));"+"return {};"+"})";};if(!window.InspectorExtensionRegistry){WebInspector.InspectorExtensionRegistryStub=function()
206 {}
207 WebInspector.InspectorExtensionRegistryStub.prototype={getExtensionsAsync:function()
208 {}}
209 var InspectorExtensionRegistry=new WebInspector.InspectorExtensionRegistryStub();};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(target,requests,ruleResultCallback,categoryDoneCallback,progress)
214 {var results=new WebInspector.ExtensionAuditCategoryResults(this,target,ruleResultCallback,categoryDoneCallback,progress);WebInspector.extensionServer.startAuditRun(this,results);}}
215 WebInspector.ExtensionAuditCategoryResults=function(category,target,ruleResultCallback,categoryDoneCallback,progress)
216 {this._target=target;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=this._target.runtimeModel.createRemoteObject(result);callback(object);}
229 WebInspector.extensionServer.evaluate(expression,false,false,evaluateOptions,this._category._extensionOrigin,onEvaluate.bind(this));}}
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(node)
235 {if(!node)
236 return;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||WebInspector.inspectorView.hasPanel(id))
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(uiSourceCode.uiLocation(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.console.target(),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 {WebInspector.inspectorView.panel("network");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=uiSourceCodes.concat(WebInspector.workspace.uiSourceCodesForProjectType(WebInspector.projectTypes.ContentScripts));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(function(){});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);WebInspector.inspectorView.panel("network");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 context;var executionContexts=WebInspector.runtimeModel.executionContexts();if(contextSecurityOrigin){for(var i=0;i<executionContexts.length;++i){var executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.name===contextSecurityOrigin&&!executionContext.isMainWorldContext)
418 context=executionContext;}
419 if(!context){console.warn("The JavaScript context "+contextSecurityOrigin+" was not found in the frame "+frame.url)
420 return this._status.E_NOTFOUND(contextSecurityOrigin)}}else{for(var i=0;i<executionContexts.length;++i){var executionContext=executionContexts[i];if(executionContext.frameId===frame.id&&executionContext.isMainWorldContext)
421 context=executionContext;}
422 if(!context)
423 return this._status.E_FAILED(frame.url+" has no execution context");}
424 contextId=context.id;}
425 RuntimeAgent.evaluate(expression,"extension",exposeCommandLineAPI,true,contextId,returnByValue,false,callback);}}
426 WebInspector.ExtensionServerPanelDescriptor=function(name,title,panel)
427 {this._name=name;this._title=title;this._panel=panel;}
428 WebInspector.ExtensionServerPanelDescriptor.prototype={name:function()
429 {return this._name;},title:function()
430 {return this._title;},panel:function()
431 {return this._panel;}}
432 WebInspector.ExtensionStatus=function()
433 {function makeStatus(code,description)
434 {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));}
435 return status;}
436 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");}
437 WebInspector.ExtensionStatus.Record;WebInspector.extensionAPI={};defineCommonExtensionSymbols(WebInspector.extensionAPI);WebInspector.ExtensionPanel=function(id,pageURL)
438 {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());}
439 WebInspector.ExtensionPanel.prototype={defaultFocusedElement:function()
440 {return WebInspector.View.prototype.defaultFocusedElement.call(this);},addStatusBarItem:function(element)
441 {this._panelStatusBarElement.classList.remove("hidden");this._panelStatusBarElement.appendChild(element);},searchCanceled:function()
442 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.CancelSearch);this._searchableView.updateSearchMatchesCount(0);},searchableView:function()
443 {return this._searchableView;},performSearch:function(query,shouldJump,jumpBackwards)
444 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.PerformSearch,query);},jumpToNextSearchResult:function()
445 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.NextSearchResult);},jumpToPreviousSearchResult:function()
446 {WebInspector.extensionServer.notifySearchAction(this.name,WebInspector.extensionAPI.panels.SearchAction.PreviousSearchResult);},__proto__:WebInspector.Panel.prototype}
447 WebInspector.ExtensionButton=function(id,iconURL,tooltip,disabled)
448 {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);}
449 WebInspector.ExtensionButton.prototype={update:function(iconURL,tooltip,disabled)
450 {if(typeof iconURL==="string")
451 this.element.style.backgroundImage="url("+iconURL+")";if(typeof tooltip==="string")
452 this.element.title=tooltip;if(typeof disabled==="boolean")
453 this.element.disabled=disabled;},_onClicked:function()
454 {WebInspector.extensionServer.notifyButtonClicked(this._id);}}
455 WebInspector.ExtensionSidebarPane=function(title,id)
456 {WebInspector.SidebarPane.call(this,title);this.setHideOnDetach();this._id=id;}
457 WebInspector.ExtensionSidebarPane.prototype={setObject:function(object,title,callback)
458 {this._createObjectPropertiesView();this._setObject(WebInspector.RemoteObject.fromLocalObject(object),title,callback);},setExpression:function(expression,title,evaluateOptions,securityOrigin,callback)
459 {this._createObjectPropertiesView();WebInspector.extensionServer.evaluate(expression,true,false,evaluateOptions,securityOrigin,this._onEvaluate.bind(this,title,callback));},setPage:function(url)
460 {if(this._objectPropertiesView){this._objectPropertiesView.detach();delete this._objectPropertiesView;}
461 if(this._extensionView)
462 this._extensionView.detach(true);this._extensionView=new WebInspector.ExtensionView(this._id,url,"extension fill");this._extensionView.show(this.bodyElement);if(!this.bodyElement.style.height)
463 this.setHeight("150px");},setHeight:function(height)
464 {this.bodyElement.style.height=height;},_onEvaluate:function(title,callback,error,result,wasThrown)
465 {if(error)
466 callback(error.toString());else
467 this._setObject(WebInspector.runtimeModel.createRemoteObject(result),title,callback);},_createObjectPropertiesView:function()
468 {if(this._objectPropertiesView)
469 return;if(this._extensionView){this._extensionView.detach(true);delete this._extensionView;}
470 this._objectPropertiesView=new WebInspector.ExtensionNotifierView(this._id);this._objectPropertiesView.show(this.bodyElement);},_setObject:function(object,title,callback)
471 {if(!this._objectPropertiesView){callback("operation cancelled");return;}
472 this._objectPropertiesView.element.removeChildren();var section=new WebInspector.ObjectPropertiesSection(object,title);if(!title)
473 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)
474 {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);}
475 WebInspector.ExtensionView.prototype={wasShown:function()
476 {if(typeof this._frameIndex==="number")
477 WebInspector.extensionServer.notifyViewShown(this._id,this._frameIndex);},willHide:function()
478 {if(typeof this._frameIndex==="number")
479 WebInspector.extensionServer.notifyViewHidden(this._id);},_onLoad:function()
480 {var frames=(window.frames);this._frameIndex=Array.prototype.indexOf.call(frames,this._iframe.contentWindow);if(this.isShowing())
481 WebInspector.extensionServer.notifyViewShown(this._id,this._frameIndex);},__proto__:WebInspector.View.prototype}
482 WebInspector.ExtensionNotifierView=function(id)
483 {WebInspector.VBox.call(this);this._id=id;}
484 WebInspector.ExtensionNotifierView.prototype={wasShown:function()
485 {WebInspector.extensionServer.notifyViewShown(this._id);},willHide:function()
486 {WebInspector.extensionServer.notifyViewHidden(this._id);},__proto__:WebInspector.VBox.prototype};