Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / chrome / tools / test / reference_build / chrome_linux / resources / inspector / ProfilesPanel.js
1 WebInspector.ProfileType=function(id,name)
2 {WebInspector.Object.call(this);this._id=id;this._name=name;this._profiles=[];this._profileBeingRecorded=null;this._nextProfileUid=1;window.addEventListener("unload",this._clearTempStorage.bind(this),false);}
3 WebInspector.ProfileType.Events={AddProfileHeader:"add-profile-header",RemoveProfileHeader:"remove-profile-header",ViewUpdated:"view-updated"}
4 WebInspector.ProfileType.prototype={hasTemporaryView:function()
5 {return false;},fileExtension:function()
6 {return null;},get statusBarItems()
7 {return[];},get buttonTooltip()
8 {return"";},get id()
9 {return this._id;},get treeItemTitle()
10 {return this._name;},get name()
11 {return this._name;},buttonClicked:function()
12 {return false;},get description()
13 {return"";},isInstantProfile:function()
14 {return false;},isEnabled:function()
15 {return true;},getProfiles:function()
16 {function isFinished(profile)
17 {return this._profileBeingRecorded!==profile;}
18 return this._profiles.filter(isFinished.bind(this));},decorationElement:function()
19 {return null;},getProfile:function(uid)
20 {for(var i=0;i<this._profiles.length;++i){if(this._profiles[i].uid===uid)
21 return this._profiles[i];}
22 return null;},loadFromFile:function(file)
23 {var name=file.name;if(name.endsWith(this.fileExtension()))
24 name=name.substr(0,name.length-this.fileExtension().length);var profile=this.createProfileLoadedFromFile(name);profile.setFromFile();this._profileBeingRecorded=profile;this.addProfile(profile);profile.loadFromFile(file);},createProfileLoadedFromFile:function(title)
25 {throw new Error("Needs implemented.");},addProfile:function(profile)
26 {this._profiles.push(profile);this.dispatchEventToListeners(WebInspector.ProfileType.Events.AddProfileHeader,profile);},removeProfile:function(profile)
27 {var index=this._profiles.indexOf(profile);if(index===-1)
28 return;this._profiles.splice(index,1);this._disposeProfile(profile);},_clearTempStorage:function()
29 {for(var i=0;i<this._profiles.length;++i)
30 this._profiles[i].removeTempFile();},profileBeingRecorded:function()
31 {return this._profileBeingRecorded;},profileBeingRecordedRemoved:function()
32 {},_reset:function()
33 {var profiles=this._profiles.slice(0);for(var i=0;i<profiles.length;++i)
34 this._disposeProfile(profiles[i]);this._profiles=[];this._nextProfileUid=1;},_disposeProfile:function(profile)
35 {this.dispatchEventToListeners(WebInspector.ProfileType.Events.RemoveProfileHeader,profile);profile.dispose();if(this._profileBeingRecorded===profile){this.profileBeingRecordedRemoved();this._profileBeingRecorded=null;}},__proto__:WebInspector.Object.prototype}
36 WebInspector.ProfileHeader=function(profileType,title)
37 {this._profileType=profileType;this.title=title;this.uid=profileType._nextProfileUid++;this._fromFile=false;}
38 WebInspector.ProfileHeader.StatusUpdate=function(subtitle,wait)
39 {this.subtitle=subtitle;this.wait=wait;}
40 WebInspector.ProfileHeader.Events={UpdateStatus:"UpdateStatus",ProfileReceived:"ProfileReceived"}
41 WebInspector.ProfileHeader.prototype={profileType:function()
42 {return this._profileType;},updateStatus:function(subtitle,wait)
43 {this.dispatchEventToListeners(WebInspector.ProfileHeader.Events.UpdateStatus,new WebInspector.ProfileHeader.StatusUpdate(subtitle,wait));},createSidebarTreeElement:function()
44 {throw new Error("Needs implemented.");},createView:function()
45 {throw new Error("Not implemented.");},removeTempFile:function()
46 {if(this._tempFile)
47 this._tempFile.remove();},dispose:function()
48 {},load:function(callback)
49 {},canSaveToFile:function()
50 {return false;},saveToFile:function()
51 {throw new Error("Needs implemented");},loadFromFile:function(file)
52 {throw new Error("Needs implemented");},fromFile:function()
53 {return this._fromFile;},setFromFile:function()
54 {this._fromFile=true;},__proto__:WebInspector.Object.prototype}
55 WebInspector.ProfilesPanel=function()
56 {WebInspector.PanelWithSidebarTree.call(this,"profiles");this.registerRequiredCSS("panelEnablerView.css");this.registerRequiredCSS("heapProfiler.css");this.registerRequiredCSS("profilesPanel.css");this._searchableView=new WebInspector.SearchableView(this);var mainView=new WebInspector.VBox();this._searchableView.show(mainView.element);mainView.show(this.mainElement());this.profilesItemTreeElement=new WebInspector.ProfilesSidebarTreeElement(this);this.sidebarTree.appendChild(this.profilesItemTreeElement);this.profileViews=document.createElement("div");this.profileViews.id="profile-views";this.profileViews.classList.add("vbox");this._searchableView.element.appendChild(this.profileViews);var statusBarContainer=document.createElementWithClass("div","profiles-status-bar");mainView.element.insertBefore(statusBarContainer,mainView.element.firstChild);this._statusBarElement=statusBarContainer.createChild("div","status-bar");this.sidebarElement().classList.add("profiles-sidebar-tree-box");var statusBarContainerLeft=document.createElementWithClass("div","profiles-status-bar");this.sidebarElement().insertBefore(statusBarContainerLeft,this.sidebarElement().firstChild);this._statusBarButtons=statusBarContainerLeft.createChild("div","status-bar");this.recordButton=new WebInspector.StatusBarButton("","record-profile-status-bar-item");this.recordButton.addEventListener("click",this.toggleRecordButton,this);this._statusBarButtons.appendChild(this.recordButton.element);this.clearResultsButton=new WebInspector.StatusBarButton(WebInspector.UIString("Clear all profiles."),"clear-status-bar-item");this.clearResultsButton.addEventListener("click",this._reset,this);this._statusBarButtons.appendChild(this.clearResultsButton.element);this._profileTypeStatusBarItemsContainer=this._statusBarElement.createChild("div");this._profileViewStatusBarItemsContainer=this._statusBarElement.createChild("div");this._profileGroups={};this._launcherView=new WebInspector.MultiProfileLauncherView(this);this._launcherView.addEventListener(WebInspector.MultiProfileLauncherView.EventTypes.ProfileTypeSelected,this._onProfileTypeSelected,this);this._profileToView=[];this._typeIdToSidebarSection={};var types=WebInspector.ProfileTypeRegistry.instance.profileTypes();for(var i=0;i<types.length;i++)
57 this._registerProfileType(types[i]);this._launcherView.restoreSelectedProfileType();this.profilesItemTreeElement.select();this._showLauncherView();this._createFileSelectorElement();this.element.addEventListener("contextmenu",this._handleContextMenuEvent.bind(this),true);this._registerShortcuts();this._configureCpuProfilerSamplingInterval();WebInspector.settings.highResolutionCpuProfiling.addChangeListener(this._configureCpuProfilerSamplingInterval,this);}
58 WebInspector.ProfileTypeRegistry=function(){this._profileTypes=[];this.cpuProfileType=new WebInspector.CPUProfileType();this._addProfileType(this.cpuProfileType);this.heapSnapshotProfileType=new WebInspector.HeapSnapshotProfileType();this._addProfileType(this.heapSnapshotProfileType);this.trackingHeapSnapshotProfileType=new WebInspector.TrackingHeapSnapshotProfileType();this._addProfileType(this.trackingHeapSnapshotProfileType);HeapProfilerAgent.enable();if(Capabilities.isMainFrontend&&WebInspector.experimentsSettings.canvasInspection.isEnabled()){this.canvasProfileType=new WebInspector.CanvasProfileType();this._addProfileType(this.canvasProfileType);}}
59 WebInspector.ProfileTypeRegistry.prototype={_addProfileType:function(profileType)
60 {this._profileTypes.push(profileType);},profileTypes:function()
61 {return this._profileTypes;}}
62 WebInspector.ProfilesPanel.prototype={searchableView:function()
63 {return this._searchableView;},_createFileSelectorElement:function()
64 {if(this._fileSelectorElement)
65 this.element.removeChild(this._fileSelectorElement);this._fileSelectorElement=WebInspector.createFileSelectorElement(this._loadFromFile.bind(this));this.element.appendChild(this._fileSelectorElement);},_findProfileTypeByExtension:function(fileName)
66 {var types=WebInspector.ProfileTypeRegistry.instance.profileTypes();for(var i=0;i<types.length;i++){var type=types[i];var extension=type.fileExtension();if(!extension)
67 continue;if(fileName.endsWith(type.fileExtension()))
68 return type;}
69 return null;},_registerShortcuts:function()
70 {this.registerShortcuts(WebInspector.ShortcutsScreen.ProfilesPanelShortcuts.StartStopRecording,this.toggleRecordButton.bind(this));},_configureCpuProfilerSamplingInterval:function()
71 {var intervalUs=WebInspector.settings.highResolutionCpuProfiling.get()?100:1000;ProfilerAgent.setSamplingInterval(intervalUs,didChangeInterval);function didChangeInterval(error)
72 {if(error)
73 WebInspector.console.showErrorMessage(error);}},_loadFromFile:function(file)
74 {this._createFileSelectorElement();var profileType=this._findProfileTypeByExtension(file.name);if(!profileType){var extensions=[];var types=WebInspector.ProfileTypeRegistry.instance.profileTypes();for(var i=0;i<types.length;i++){var extension=types[i].fileExtension();if(!extension)
75 continue;extensions.push(extension);}
76 WebInspector.console.log(WebInspector.UIString("Can't load file. Only files with extensions '%s' can be loaded.",extensions.join("', '")));return;}
77 if(!!profileType.profileBeingRecorded()){WebInspector.console.log(WebInspector.UIString("Can't load profile when other profile is recording."));return;}
78 profileType.loadFromFile(file);},toggleRecordButton:function()
79 {var type=this._selectedProfileType;var isProfiling=type.buttonClicked();this.recordButton.toggled=isProfiling;this.recordButton.title=type.buttonTooltip;if(isProfiling){this._launcherView.profileStarted();if(type.hasTemporaryView())
80 this.showProfile(type.profileBeingRecorded());}else{this._launcherView.profileFinished();}
81 return true;},_profileBeingRecordedRemoved:function()
82 {this.recordButton.toggled=false;this.recordButton.title=this._selectedProfileType.buttonTooltip;this._launcherView.profileFinished();},_onProfileTypeSelected:function(event)
83 {this._selectedProfileType=(event.data);this._updateProfileTypeSpecificUI();},_updateProfileTypeSpecificUI:function()
84 {this.recordButton.title=this._selectedProfileType.buttonTooltip;this._launcherView.updateProfileType(this._selectedProfileType);this._profileTypeStatusBarItemsContainer.removeChildren();var statusBarItems=this._selectedProfileType.statusBarItems;if(statusBarItems){for(var i=0;i<statusBarItems.length;++i)
85 this._profileTypeStatusBarItemsContainer.appendChild(statusBarItems[i]);}},_reset:function()
86 {WebInspector.Panel.prototype.reset.call(this);var types=WebInspector.ProfileTypeRegistry.instance.profileTypes();for(var i=0;i<types.length;i++)
87 types[i]._reset();delete this.visibleView;delete this.currentQuery;this.searchCanceled();this._profileGroups={};this.recordButton.toggled=false;if(this._selectedProfileType)
88 this.recordButton.title=this._selectedProfileType.buttonTooltip;this._launcherView.profileFinished();this.sidebarTree.element.classList.remove("some-expandable");this._launcherView.detach();this.profileViews.removeChildren();this._profileViewStatusBarItemsContainer.removeChildren();this.removeAllListeners();this.recordButton.visible=true;this._profileViewStatusBarItemsContainer.classList.remove("hidden");this.clearResultsButton.element.classList.remove("hidden");this.profilesItemTreeElement.select();this._showLauncherView();},_showLauncherView:function()
89 {this.closeVisibleView();this._profileViewStatusBarItemsContainer.removeChildren();this._launcherView.show(this.profileViews);this.visibleView=this._launcherView;},_garbageCollectButtonClicked:function()
90 {HeapProfilerAgent.collectGarbage();},_registerProfileType:function(profileType)
91 {this._launcherView.addProfileType(profileType);var profileTypeSection=new WebInspector.ProfileTypeSidebarSection(profileType);this._typeIdToSidebarSection[profileType.id]=profileTypeSection
92 this.sidebarTree.appendChild(profileTypeSection);profileTypeSection.childrenListElement.addEventListener("contextmenu",this._handleContextMenuEvent.bind(this),true);function onAddProfileHeader(event)
93 {this._addProfileHeader(event.data);}
94 function onRemoveProfileHeader(event)
95 {this._removeProfileHeader(event.data);}
96 profileType.addEventListener(WebInspector.ProfileType.Events.ViewUpdated,this._updateProfileTypeSpecificUI,this);profileType.addEventListener(WebInspector.ProfileType.Events.AddProfileHeader,onAddProfileHeader,this);profileType.addEventListener(WebInspector.ProfileType.Events.RemoveProfileHeader,onRemoveProfileHeader,this);var profiles=profileType.getProfiles();for(var i=0;i<profiles.length;i++)
97 this._addProfileHeader(profiles[i]);},_handleContextMenuEvent:function(event)
98 {var element=event.srcElement;while(element&&!element.treeElement&&element!==this.element)
99 element=element.parentElement;if(!element)
100 return;if(element.treeElement&&element.treeElement.handleContextMenuEvent){element.treeElement.handleContextMenuEvent(event,this);return;}
101 var contextMenu=new WebInspector.ContextMenu(event);if(this.visibleView instanceof WebInspector.HeapSnapshotView){this.visibleView.populateContextMenu(contextMenu,event);}
102 if(element!==this.element||event.srcElement===this.sidebarElement()){contextMenu.appendItem(WebInspector.UIString("Load\u2026"),this._fileSelectorElement.click.bind(this._fileSelectorElement));}
103 contextMenu.show();},showLoadFromFileDialog:function()
104 {this._fileSelectorElement.click();},_addProfileHeader:function(profile)
105 {var profileType=profile.profileType();var typeId=profileType.id;this._typeIdToSidebarSection[typeId].addProfileHeader(profile);;if(!this.visibleView||this.visibleView===this._launcherView)
106 this.showProfile(profile);},_removeProfileHeader:function(profile)
107 {if(profile.profileType()._profileBeingRecorded===profile)
108 this._profileBeingRecordedRemoved();var i=this._indexOfViewForProfile(profile);if(i!==-1)
109 this._profileToView.splice(i,1);var profileType=profile.profileType();var typeId=profileType.id;var sectionIsEmpty=this._typeIdToSidebarSection[typeId].removeProfileHeader(profile);if(sectionIsEmpty){this.profilesItemTreeElement.select();this._showLauncherView();}},showProfile:function(profile)
110 {if(!profile||(profile.profileType().profileBeingRecorded()===profile)&&!profile.profileType().hasTemporaryView())
111 return null;var view=this._viewForProfile(profile);if(view===this.visibleView)
112 return view;this.closeVisibleView();view.show(this.profileViews);this.visibleView=view;var profileTypeSection=this._typeIdToSidebarSection[profile.profileType().id];var sidebarElement=profileTypeSection.sidebarElementForProfile(profile);sidebarElement.revealAndSelect();this._profileViewStatusBarItemsContainer.removeChildren();var statusBarItems=view.statusBarItems;if(statusBarItems)
113 for(var i=0;i<statusBarItems.length;++i)
114 this._profileViewStatusBarItemsContainer.appendChild(statusBarItems[i]);return view;},showObject:function(snapshotObjectId,perspectiveName)
115 {var heapProfiles=WebInspector.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles();for(var i=0;i<heapProfiles.length;i++){var profile=heapProfiles[i];if(profile.maxJSObjectId>=snapshotObjectId){this.showProfile(profile);var view=this._viewForProfile(profile);view.highlightLiveObject(perspectiveName,snapshotObjectId);break;}}},_viewForProfile:function(profile)
116 {var index=this._indexOfViewForProfile(profile);if(index!==-1)
117 return this._profileToView[index].view;var view=profile.createView();view.element.classList.add("profile-view");this._profileToView.push({profile:profile,view:view});return view;},_indexOfViewForProfile:function(profile)
118 {for(var i=0;i<this._profileToView.length;i++){if(this._profileToView[i].profile===profile)
119 return i;}
120 return-1;},closeVisibleView:function()
121 {if(this.visibleView)
122 this.visibleView.detach();delete this.visibleView;},performSearch:function(query,shouldJump)
123 {this.searchCanceled();var visibleView=this.visibleView;if(!visibleView)
124 return;function finishedCallback(view,searchMatches)
125 {if(!searchMatches)
126 return;this._searchableView.updateSearchMatchesCount(searchMatches);this._searchResultsView=view;if(shouldJump){view.jumpToFirstSearchResult();this._searchableView.updateCurrentMatchIndex(view.currentSearchResultIndex());}}
127 visibleView.currentQuery=query;visibleView.performSearch(query,finishedCallback.bind(this));},jumpToNextSearchResult:function()
128 {if(!this._searchResultsView)
129 return;if(this._searchResultsView!==this.visibleView)
130 return;this._searchResultsView.jumpToNextSearchResult();this._searchableView.updateCurrentMatchIndex(this._searchResultsView.currentSearchResultIndex());},jumpToPreviousSearchResult:function()
131 {if(!this._searchResultsView)
132 return;if(this._searchResultsView!==this.visibleView)
133 return;this._searchResultsView.jumpToPreviousSearchResult();this._searchableView.updateCurrentMatchIndex(this._searchResultsView.currentSearchResultIndex());},searchCanceled:function()
134 {if(this._searchResultsView){if(this._searchResultsView.searchCanceled)
135 this._searchResultsView.searchCanceled();this._searchResultsView.currentQuery=null;this._searchResultsView=null;}
136 this._searchableView.updateSearchMatchesCount(0);},appendApplicableItems:function(event,contextMenu,target)
137 {if(!(target instanceof WebInspector.RemoteObject))
138 return;if(WebInspector.inspectorView.currentPanel()!==this)
139 return;var object=(target);var objectId=object.objectId;if(!objectId)
140 return;var heapProfiles=WebInspector.ProfileTypeRegistry.instance.heapSnapshotProfileType.getProfiles();if(!heapProfiles.length)
141 return;function revealInView(viewName)
142 {HeapProfilerAgent.getHeapObjectId(objectId,didReceiveHeapObjectId.bind(this,viewName));}
143 function didReceiveHeapObjectId(viewName,error,result)
144 {if(WebInspector.inspectorView.currentPanel()!==this)
145 return;if(!error)
146 this.showObject(result,viewName);}
147 if(WebInspector.settings.showAdvancedHeapSnapshotProperties.get())
148 contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles()?"Reveal in Dominators view":"Reveal in Dominators View"),revealInView.bind(this,"Dominators"));contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles()?"Reveal in Summary view":"Reveal in Summary View"),revealInView.bind(this,"Summary"));},__proto__:WebInspector.PanelWithSidebarTree.prototype}
149 WebInspector.ProfileTypeSidebarSection=function(profileType)
150 {WebInspector.SidebarSectionTreeElement.call(this,profileType.treeItemTitle,null,true);this._profileTreeElements=[];this._profileGroups={};this.hidden=true;}
151 WebInspector.ProfileTypeSidebarSection.ProfileGroup=function()
152 {this.profileSidebarTreeElements=[];this.sidebarTreeElement=null;}
153 WebInspector.ProfileTypeSidebarSection.prototype={addProfileHeader:function(profile)
154 {this.hidden=false;var profileType=profile.profileType();var sidebarParent=this;var profileTreeElement=profile.createSidebarTreeElement();this._profileTreeElements.push(profileTreeElement);if(!profile.fromFile()&&profileType.profileBeingRecorded()!==profile){var profileTitle=profile.title;var group=this._profileGroups[profileTitle];if(!group){group=new WebInspector.ProfileTypeSidebarSection.ProfileGroup();this._profileGroups[profileTitle]=group;}
155 group.profileSidebarTreeElements.push(profileTreeElement);var groupSize=group.profileSidebarTreeElements.length;if(groupSize===2){group.sidebarTreeElement=new WebInspector.ProfileGroupSidebarTreeElement(profile.title);var firstProfileTreeElement=group.profileSidebarTreeElements[0];var index=this.children.indexOf(firstProfileTreeElement);this.insertChild(group.sidebarTreeElement,index);var selected=firstProfileTreeElement.selected;this.removeChild(firstProfileTreeElement);group.sidebarTreeElement.appendChild(firstProfileTreeElement);if(selected)
156 firstProfileTreeElement.revealAndSelect();firstProfileTreeElement.small=true;firstProfileTreeElement.mainTitle=WebInspector.UIString("Run %d",1);this.treeOutline.element.classList.add("some-expandable");}
157 if(groupSize>=2){sidebarParent=group.sidebarTreeElement;profileTreeElement.small=true;profileTreeElement.mainTitle=WebInspector.UIString("Run %d",groupSize);}}
158 sidebarParent.appendChild(profileTreeElement);},removeProfileHeader:function(profile)
159 {var index=this._sidebarElementIndex(profile);if(index===-1)
160 return false;var profileTreeElement=this._profileTreeElements[index];this._profileTreeElements.splice(index,1);var sidebarParent=this;var group=this._profileGroups[profile.title];if(group){var groupElements=group.profileSidebarTreeElements;groupElements.splice(groupElements.indexOf(profileTreeElement),1);if(groupElements.length===1){var pos=sidebarParent.children.indexOf(group.sidebarTreeElement);this.insertChild(groupElements[0],pos);groupElements[0].small=false;groupElements[0].mainTitle=group.sidebarTreeElement.title;this.removeChild(group.sidebarTreeElement);}
161 if(groupElements.length!==0)
162 sidebarParent=group.sidebarTreeElement;}
163 sidebarParent.removeChild(profileTreeElement);profileTreeElement.dispose();if(this.children.length)
164 return false;this.hidden=true;return true;},sidebarElementForProfile:function(profile)
165 {var index=this._sidebarElementIndex(profile);return index===-1?null:this._profileTreeElements[index];},_sidebarElementIndex:function(profile)
166 {var elements=this._profileTreeElements;for(var i=0;i<elements.length;i++){if(elements[i].profile===profile)
167 return i;}
168 return-1;},__proto__:WebInspector.SidebarSectionTreeElement.prototype}
169 WebInspector.ProfilesPanel.ContextMenuProvider=function()
170 {}
171 WebInspector.ProfilesPanel.ContextMenuProvider.prototype={appendApplicableItems:function(event,contextMenu,target)
172 {WebInspector.inspectorView.panel("profiles").appendApplicableItems(event,contextMenu,target);}}
173 WebInspector.ProfileSidebarTreeElement=function(profile,className)
174 {this.profile=profile;WebInspector.SidebarTreeElement.call(this,className,profile.title,"",profile,false);this.refreshTitles();profile.addEventListener(WebInspector.ProfileHeader.Events.UpdateStatus,this._updateStatus,this);if(profile.canSaveToFile())
175 this._createSaveLink();else
176 profile.addEventListener(WebInspector.ProfileHeader.Events.ProfileReceived,this._onProfileReceived,this);}
177 WebInspector.ProfileSidebarTreeElement.prototype={_createSaveLink:function()
178 {this._saveLinkElement=this.titleContainer.createChild("span","save-link");this._saveLinkElement.textContent=WebInspector.UIString("Save");this._saveLinkElement.addEventListener("click",this._saveProfile.bind(this),false);},_onProfileReceived:function(event)
179 {this._createSaveLink();},_updateStatus:function(event)
180 {var statusUpdate=event.data;if(statusUpdate.subtitle!==null)
181 this.subtitle=statusUpdate.subtitle;if(typeof statusUpdate.wait==="boolean")
182 this.wait=statusUpdate.wait;this.refreshTitles();},dispose:function()
183 {this.profile.removeEventListener(WebInspector.ProfileHeader.Events.UpdateStatus,this._updateStatus,this);this.profile.removeEventListener(WebInspector.ProfileHeader.Events.ProfileReceived,this._onProfileReceived,this);},onselect:function()
184 {WebInspector.panels.profiles.showProfile(this.profile);},ondelete:function()
185 {this.profile.profileType().removeProfile(this.profile);return true;},handleContextMenuEvent:function(event,panel)
186 {var profile=this.profile;var contextMenu=new WebInspector.ContextMenu(event);contextMenu.appendItem(WebInspector.UIString("Load\u2026"),panel._fileSelectorElement.click.bind(panel._fileSelectorElement));if(profile.canSaveToFile())
187 contextMenu.appendItem(WebInspector.UIString("Save\u2026"),profile.saveToFile.bind(profile));contextMenu.appendItem(WebInspector.UIString("Delete"),this.ondelete.bind(this));contextMenu.show();},_saveProfile:function(event)
188 {this.profile.saveToFile();},__proto__:WebInspector.SidebarTreeElement.prototype}
189 WebInspector.ProfileGroupSidebarTreeElement=function(title,subtitle)
190 {WebInspector.SidebarTreeElement.call(this,"profile-group-sidebar-tree-item",title,subtitle,null,true);}
191 WebInspector.ProfileGroupSidebarTreeElement.prototype={onselect:function()
192 {if(this.children.length>0)
193 WebInspector.panels.profiles.showProfile(this.children[this.children.length-1].profile);},__proto__:WebInspector.SidebarTreeElement.prototype}
194 WebInspector.ProfilesSidebarTreeElement=function(panel)
195 {this._panel=panel;this.small=false;WebInspector.SidebarTreeElement.call(this,"profile-launcher-view-tree-item",WebInspector.UIString("Profiles"),"",null,false);}
196 WebInspector.ProfilesSidebarTreeElement.prototype={onselect:function()
197 {this._panel._showLauncherView();},get selectable()
198 {return true;},__proto__:WebInspector.SidebarTreeElement.prototype}
199 WebInspector.ProfileDataGridNode=function(profileNode,owningTree,hasChildren)
200 {this.profileNode=profileNode;WebInspector.DataGridNode.call(this,null,hasChildren);this.tree=owningTree;this.childrenByCallUID={};this.lastComparator=null;this.callUID=profileNode.callUID;this.selfTime=profileNode.selfTime;this.totalTime=profileNode.totalTime;this.functionName=profileNode.functionName;this._deoptReason=(!profileNode.deoptReason||profileNode.deoptReason==="no reason")?"":profileNode.deoptReason;this.url=profileNode.url;}
201 WebInspector.ProfileDataGridNode.prototype={get data()
202 {function formatMilliseconds(time)
203 {return WebInspector.UIString("%.1f\u2009ms",time);}
204 var data={};if(this._deoptReason){var content=document.createDocumentFragment();var marker=content.createChild("span","profile-warn-marker");marker.title=WebInspector.UIString("Not optimized: %s",this._deoptReason);content.createTextChild(this.functionName);data["function"]=content;}else
205 data["function"]=this.functionName;if(this.tree.profileView.showSelfTimeAsPercent.get())
206 data["self"]=WebInspector.UIString("%.2f%",this.selfPercent);else
207 data["self"]=formatMilliseconds(this.selfTime);if(this.tree.profileView.showTotalTimeAsPercent.get())
208 data["total"]=WebInspector.UIString("%.2f%",this.totalPercent);else
209 data["total"]=formatMilliseconds(this.totalTime);return data;},createCell:function(columnIdentifier)
210 {var cell=WebInspector.DataGridNode.prototype.createCell.call(this,columnIdentifier);if(columnIdentifier==="self"&&this._searchMatchedSelfColumn)
211 cell.classList.add("highlight");else if(columnIdentifier==="total"&&this._searchMatchedTotalColumn)
212 cell.classList.add("highlight");if(columnIdentifier!=="function")
213 return cell;if(this._deoptReason)
214 cell.classList.add("not-optimized");if(this.profileNode._searchMatchedFunctionColumn)
215 cell.classList.add("highlight");if(this.profileNode.scriptId!=="0"){var lineNumber=this.profileNode.lineNumber?this.profileNode.lineNumber-1:0;var columnNumber=this.profileNode.columnNumber?this.profileNode.columnNumber-1:0;var location=new WebInspector.DebuggerModel.Location(this.profileNode.scriptId,lineNumber,columnNumber);var urlElement=this.tree.profileView._linkifier.linkifyRawLocation(location,"profile-node-file");if(!urlElement)
216 urlElement=this.tree.profileView._linkifier.linkifyLocation(this.profileNode.url,lineNumber,columnNumber,"profile-node-file");urlElement.style.maxWidth="75%";cell.insertBefore(urlElement,cell.firstChild);}
217 return cell;},select:function(supressSelectedEvent)
218 {WebInspector.DataGridNode.prototype.select.call(this,supressSelectedEvent);this.tree.profileView._dataGridNodeSelected(this);},deselect:function(supressDeselectedEvent)
219 {WebInspector.DataGridNode.prototype.deselect.call(this,supressDeselectedEvent);this.tree.profileView._dataGridNodeDeselected(this);},sort:function(comparator,force)
220 {var gridNodeGroups=[[this]];for(var gridNodeGroupIndex=0;gridNodeGroupIndex<gridNodeGroups.length;++gridNodeGroupIndex){var gridNodes=gridNodeGroups[gridNodeGroupIndex];var count=gridNodes.length;for(var index=0;index<count;++index){var gridNode=gridNodes[index];if(!force&&(!gridNode.expanded||gridNode.lastComparator===comparator)){if(gridNode.children.length)
221 gridNode.shouldRefreshChildren=true;continue;}
222 gridNode.lastComparator=comparator;var children=gridNode.children;var childCount=children.length;if(childCount){children.sort(comparator);for(var childIndex=0;childIndex<childCount;++childIndex)
223 children[childIndex]._recalculateSiblings(childIndex);gridNodeGroups.push(children);}}}},insertChild:function(profileDataGridNode,index)
224 {WebInspector.DataGridNode.prototype.insertChild.call(this,profileDataGridNode,index);this.childrenByCallUID[profileDataGridNode.callUID]=profileDataGridNode;},removeChild:function(profileDataGridNode)
225 {WebInspector.DataGridNode.prototype.removeChild.call(this,profileDataGridNode);delete this.childrenByCallUID[profileDataGridNode.callUID];},removeChildren:function()
226 {WebInspector.DataGridNode.prototype.removeChildren.call(this);this.childrenByCallUID={};},findChild:function(node)
227 {if(!node)
228 return null;return this.childrenByCallUID[node.callUID];},get selfPercent()
229 {return this.selfTime/this.tree.totalTime*100.0;},get totalPercent()
230 {return this.totalTime/this.tree.totalTime*100.0;},get _parent()
231 {return this.parent!==this.dataGrid?this.parent:this.tree;},populate:function()
232 {if(this._populated)
233 return;this._populated=true;this._sharedPopulate();var currentComparator=this.tree.lastComparator;if(currentComparator)
234 this.sort(currentComparator,true);},_save:function()
235 {if(this._savedChildren)
236 return;this._savedSelfTime=this.selfTime;this._savedTotalTime=this.totalTime;this._savedChildren=this.children.slice();},_restore:function()
237 {if(!this._savedChildren)
238 return;this.selfTime=this._savedSelfTime;this.totalTime=this._savedTotalTime;this.removeChildren();var children=this._savedChildren;var count=children.length;for(var index=0;index<count;++index){children[index]._restore();this.appendChild(children[index]);}},_merge:function(child,shouldAbsorb)
239 {this.selfTime+=child.selfTime;if(!shouldAbsorb)
240 this.totalTime+=child.totalTime;var children=this.children.slice();this.removeChildren();var count=children.length;for(var index=0;index<count;++index){if(!shouldAbsorb||children[index]!==child)
241 this.appendChild(children[index]);}
242 children=child.children.slice();count=children.length;for(var index=0;index<count;++index){var orphanedChild=children[index],existingChild=this.childrenByCallUID[orphanedChild.callUID];if(existingChild)
243 existingChild._merge(orphanedChild,false);else
244 this.appendChild(orphanedChild);}},__proto__:WebInspector.DataGridNode.prototype}
245 WebInspector.ProfileDataGridTree=function(profileView,rootProfileNode)
246 {this.tree=this;this.children=[];this.profileView=profileView;this.totalTime=rootProfileNode.totalTime;this.lastComparator=null;this.childrenByCallUID={};}
247 WebInspector.ProfileDataGridTree.prototype={get expanded()
248 {return true;},appendChild:function(child)
249 {this.insertChild(child,this.children.length);},insertChild:function(child,index)
250 {this.children.splice(index,0,child);this.childrenByCallUID[child.callUID]=child;},removeChildren:function()
251 {this.children=[];this.childrenByCallUID={};},findChild:WebInspector.ProfileDataGridNode.prototype.findChild,sort:WebInspector.ProfileDataGridNode.prototype.sort,_save:function()
252 {if(this._savedChildren)
253 return;this._savedTotalTime=this.totalTime;this._savedChildren=this.children.slice();},restore:function()
254 {if(!this._savedChildren)
255 return;this.children=this._savedChildren;this.totalTime=this._savedTotalTime;var children=this.children;var count=children.length;for(var index=0;index<count;++index)
256 children[index]._restore();this._savedChildren=null;}}
257 WebInspector.ProfileDataGridTree.propertyComparators=[{},{}];WebInspector.ProfileDataGridTree.propertyComparator=function(property,isAscending)
258 {var comparator=WebInspector.ProfileDataGridTree.propertyComparators[(isAscending?1:0)][property];if(!comparator){if(isAscending){comparator=function(lhs,rhs)
259 {if(lhs[property]<rhs[property])
260 return-1;if(lhs[property]>rhs[property])
261 return 1;return 0;}}else{comparator=function(lhs,rhs)
262 {if(lhs[property]>rhs[property])
263 return-1;if(lhs[property]<rhs[property])
264 return 1;return 0;}}
265 WebInspector.ProfileDataGridTree.propertyComparators[(isAscending?1:0)][property]=comparator;}
266 return comparator;};WebInspector.BottomUpProfileDataGridNode=function(profileNode,owningTree)
267 {WebInspector.ProfileDataGridNode.call(this,profileNode,owningTree,this._willHaveChildren(profileNode));this._remainingNodeInfos=[];}
268 WebInspector.BottomUpProfileDataGridNode.prototype={_takePropertiesFromProfileDataGridNode:function(profileDataGridNode)
269 {this._save();this.selfTime=profileDataGridNode.selfTime;this.totalTime=profileDataGridNode.totalTime;},_keepOnlyChild:function(child)
270 {this._save();this.removeChildren();this.appendChild(child);},_exclude:function(aCallUID)
271 {if(this._remainingNodeInfos)
272 this.populate();this._save();var children=this.children;var index=this.children.length;while(index--)
273 children[index]._exclude(aCallUID);var child=this.childrenByCallUID[aCallUID];if(child)
274 this._merge(child,true);},_restore:function()
275 {WebInspector.ProfileDataGridNode.prototype._restore();if(!this.children.length)
276 this.hasChildren=this._willHaveChildren(this.profileNode);},_merge:function(child,shouldAbsorb)
277 {this.selfTime-=child.selfTime;WebInspector.ProfileDataGridNode.prototype._merge.call(this,child,shouldAbsorb);},_sharedPopulate:function()
278 {var remainingNodeInfos=this._remainingNodeInfos;var count=remainingNodeInfos.length;for(var index=0;index<count;++index){var nodeInfo=remainingNodeInfos[index];var ancestor=nodeInfo.ancestor;var focusNode=nodeInfo.focusNode;var child=this.findChild(ancestor);if(child){var totalTimeAccountedFor=nodeInfo.totalTimeAccountedFor;child.selfTime+=focusNode.selfTime;if(!totalTimeAccountedFor)
279 child.totalTime+=focusNode.totalTime;}else{child=new WebInspector.BottomUpProfileDataGridNode(ancestor,this.tree);if(ancestor!==focusNode){child.selfTime=focusNode.selfTime;child.totalTime=focusNode.totalTime;}
280 this.appendChild(child);}
281 var parent=ancestor.parent;if(parent&&parent.parent){nodeInfo.ancestor=parent;child._remainingNodeInfos.push(nodeInfo);}}
282 delete this._remainingNodeInfos;},_willHaveChildren:function(profileNode)
283 {return!!(profileNode.parent&&profileNode.parent.parent);},__proto__:WebInspector.ProfileDataGridNode.prototype}
284 WebInspector.BottomUpProfileDataGridTree=function(profileView,rootProfileNode)
285 {WebInspector.ProfileDataGridTree.call(this,profileView,rootProfileNode);var profileNodeUIDs=0;var profileNodeGroups=[[],[rootProfileNode]];var visitedProfileNodesForCallUID={};this._remainingNodeInfos=[];for(var profileNodeGroupIndex=0;profileNodeGroupIndex<profileNodeGroups.length;++profileNodeGroupIndex){var parentProfileNodes=profileNodeGroups[profileNodeGroupIndex];var profileNodes=profileNodeGroups[++profileNodeGroupIndex];var count=profileNodes.length;for(var index=0;index<count;++index){var profileNode=profileNodes[index];if(!profileNode.UID)
286 profileNode.UID=++profileNodeUIDs;if(profileNode.head&&profileNode!==profileNode.head){var visitedNodes=visitedProfileNodesForCallUID[profileNode.callUID];var totalTimeAccountedFor=false;if(!visitedNodes){visitedNodes={}
287 visitedProfileNodesForCallUID[profileNode.callUID]=visitedNodes;}else{var parentCount=parentProfileNodes.length;for(var parentIndex=0;parentIndex<parentCount;++parentIndex){if(visitedNodes[parentProfileNodes[parentIndex].UID]){totalTimeAccountedFor=true;break;}}}
288 visitedNodes[profileNode.UID]=true;this._remainingNodeInfos.push({ancestor:profileNode,focusNode:profileNode,totalTimeAccountedFor:totalTimeAccountedFor});}
289 var children=profileNode.children;if(children.length){profileNodeGroups.push(parentProfileNodes.concat([profileNode]))
290 profileNodeGroups.push(children);}}}
291 var any=(this);var node=(any);WebInspector.BottomUpProfileDataGridNode.prototype.populate.call(node);return this;}
292 WebInspector.BottomUpProfileDataGridTree.prototype={focus:function(profileDataGridNode)
293 {if(!profileDataGridNode)
294 return;this._save();var currentNode=profileDataGridNode;var focusNode=profileDataGridNode;while(currentNode.parent&&(currentNode instanceof WebInspector.ProfileDataGridNode)){currentNode._takePropertiesFromProfileDataGridNode(profileDataGridNode);focusNode=currentNode;currentNode=currentNode.parent;if(currentNode instanceof WebInspector.ProfileDataGridNode)
295 currentNode._keepOnlyChild(focusNode);}
296 this.children=[focusNode];this.totalTime=profileDataGridNode.totalTime;},exclude:function(profileDataGridNode)
297 {if(!profileDataGridNode)
298 return;this._save();var excludedCallUID=profileDataGridNode.callUID;var excludedTopLevelChild=this.childrenByCallUID[excludedCallUID];if(excludedTopLevelChild)
299 this.children.remove(excludedTopLevelChild);var children=this.children;var count=children.length;for(var index=0;index<count;++index)
300 children[index]._exclude(excludedCallUID);if(this.lastComparator)
301 this.sort(this.lastComparator,true);},_sharedPopulate:WebInspector.BottomUpProfileDataGridNode.prototype._sharedPopulate,__proto__:WebInspector.ProfileDataGridTree.prototype};WebInspector.CPUProfileFlameChart=function(dataProvider)
302 {WebInspector.VBox.call(this);this.registerRequiredCSS("flameChart.css");this.element.id="cpu-flame-chart";this._overviewPane=new WebInspector.CPUProfileFlameChart.OverviewPane(dataProvider);this._overviewPane.show(this.element);this._mainPane=new WebInspector.FlameChart(dataProvider,this._overviewPane,true,false);this._mainPane.show(this.element);this._mainPane.addEventListener(WebInspector.FlameChart.Events.EntrySelected,this._onEntrySelected,this);this._overviewPane._overviewGrid.addEventListener(WebInspector.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);}
303 WebInspector.CPUProfileFlameChart.prototype={_onWindowChanged:function(event)
304 {this._mainPane.changeWindow(this._overviewPane._overviewGrid.windowLeft(),this._overviewPane._overviewGrid.windowRight());},selectRange:function(timeLeft,timeRight)
305 {this._overviewPane._selectRange(timeLeft,timeRight);},_onEntrySelected:function(event)
306 {this.dispatchEventToListeners(WebInspector.FlameChart.Events.EntrySelected,event.data);},update:function()
307 {this._overviewPane.update();this._mainPane.update();},__proto__:WebInspector.VBox.prototype};WebInspector.CPUProfileFlameChart.OverviewCalculator=function()
308 {}
309 WebInspector.CPUProfileFlameChart.OverviewCalculator.prototype={paddingLeft:function()
310 {return 0;},_updateBoundaries:function(overviewPane)
311 {this._minimumBoundaries=0;var totalTime=overviewPane._dataProvider.totalTime();this._maximumBoundaries=totalTime;this._xScaleFactor=overviewPane._overviewCanvas.width/totalTime;},computePosition:function(time)
312 {return(time-this._minimumBoundaries)*this._xScaleFactor;},formatTime:function(value,precision)
313 {return Number.secondsToString((value+this._minimumBoundaries)/1000);},maximumBoundary:function()
314 {return this._maximumBoundaries;},minimumBoundary:function()
315 {return this._minimumBoundaries;},zeroTime:function()
316 {return this._minimumBoundaries;},boundarySpan:function()
317 {return this._maximumBoundaries-this._minimumBoundaries;}}
318 WebInspector.CPUProfileFlameChart.ColorGenerator=function()
319 {this._colors={};this._currentColorIndex=0;}
320 WebInspector.CPUProfileFlameChart.ColorGenerator.prototype={setColorForID:function(id,color)
321 {this._colors[id]=color;},colorForID:function(id,sat)
322 {if(typeof sat!=="number")
323 sat=100;var color=this._colors[id];if(!color){color=this._createColor(this._currentColorIndex++,sat);this._colors[id]=color;}
324 return color;},_createColor:function(index,sat)
325 {var hue=(index*7+12*(index%2))%360;return"hsla("+hue+", "+sat+"%, 66%, 0.7)";}}
326 WebInspector.CPUProfileFlameChart.OverviewPane=function(dataProvider)
327 {WebInspector.VBox.call(this);this.element.classList.add("flame-chart-overview-pane");this._overviewContainer=this.element.createChild("div","overview-container");this._overviewGrid=new WebInspector.OverviewGrid("flame-chart");this._overviewGrid.element.classList.add("fill");this._overviewCanvas=this._overviewContainer.createChild("canvas","flame-chart-overview-canvas");this._overviewContainer.appendChild(this._overviewGrid.element);this._overviewCalculator=new WebInspector.CPUProfileFlameChart.OverviewCalculator();this._dataProvider=dataProvider;}
328 WebInspector.CPUProfileFlameChart.OverviewPane.prototype={requestWindowTimes:function(windowStartTime,windowEndTime)
329 {this._overviewGrid.setWindow(windowStartTime/this._dataProvider.totalTime(),windowEndTime/this._dataProvider.totalTime());},_selectRange:function(timeLeft,timeRight)
330 {this._overviewGrid.setWindow(timeLeft/this._dataProvider.totalTime(),timeRight/this._dataProvider.totalTime());},_timelineData:function()
331 {return this._dataProvider.timelineData();},onResize:function()
332 {this._scheduleUpdate();},_scheduleUpdate:function()
333 {if(this._updateTimerId)
334 return;this._updateTimerId=requestAnimationFrame(this.update.bind(this));},update:function()
335 {this._updateTimerId=0;var timelineData=this._timelineData();if(!timelineData)
336 return;this._resetCanvas(this._overviewContainer.clientWidth,this._overviewContainer.clientHeight-WebInspector.FlameChart.DividersBarHeight);this._overviewCalculator._updateBoundaries(this);this._overviewGrid.updateDividers(this._overviewCalculator);WebInspector.CPUProfileFlameChart.OverviewPane.drawOverviewCanvas(this._dataProvider,timelineData,this._overviewCanvas.getContext("2d"),this._overviewContainer.clientWidth,this._overviewContainer.clientHeight-WebInspector.FlameChart.DividersBarHeight);},_resetCanvas:function(width,height)
337 {var ratio=window.devicePixelRatio;this._overviewCanvas.width=width*ratio;this._overviewCanvas.height=height*ratio;},__proto__:WebInspector.VBox.prototype}
338 WebInspector.CPUProfileFlameChart.OverviewPane.calculateDrawData=function(dataProvider,timelineData,width)
339 {var entryOffsets=timelineData.entryOffsets;var entryTotalTimes=timelineData.entryTotalTimes;var entryLevels=timelineData.entryLevels;var length=entryOffsets.length;var drawData=new Uint8Array(width);var scaleFactor=width/dataProvider.totalTime();for(var entryIndex=0;entryIndex<length;++entryIndex){var start=Math.floor(entryOffsets[entryIndex]*scaleFactor);var finish=Math.floor((entryOffsets[entryIndex]+entryTotalTimes[entryIndex])*scaleFactor);for(var x=start;x<=finish;++x)
340 drawData[x]=Math.max(drawData[x],entryLevels[entryIndex]+1);}
341 return drawData;}
342 WebInspector.CPUProfileFlameChart.OverviewPane.drawOverviewCanvas=function(dataProvider,timelineData,context,width,height)
343 {var ratio=window.devicePixelRatio;var canvasWidth=width*ratio;var canvasHeight=height*ratio;var drawData=WebInspector.CPUProfileFlameChart.OverviewPane.calculateDrawData(dataProvider,timelineData,canvasWidth);if(!drawData)
344 return;var yScaleFactor=canvasHeight/(dataProvider.maxStackDepth()*1.1);context.lineWidth=1;context.translate(0.5,0.5);context.strokeStyle="rgba(20,0,0,0.4)";context.fillStyle="rgba(214,225,254,0.8)";context.moveTo(-1,canvasHeight-1);context.lineTo(-1,Math.round(canvasHeight-drawData[0]*yScaleFactor-1));var value;for(var x=0;x<canvasWidth;++x){value=Math.round(canvasHeight-drawData[x]*yScaleFactor-1);context.lineTo(x,value);}
345 context.lineTo(canvasWidth+1,value);context.lineTo(canvasWidth+1,canvasHeight-1);context.fill();context.stroke();context.closePath();};WebInspector.CPUProfileView=function(profileHeader)
346 {WebInspector.VBox.call(this);this.element.classList.add("cpu-profile-view");this.showSelfTimeAsPercent=WebInspector.settings.createSetting("cpuProfilerShowSelfTimeAsPercent",true);this.showTotalTimeAsPercent=WebInspector.settings.createSetting("cpuProfilerShowTotalTimeAsPercent",true);this.showAverageTimeAsPercent=WebInspector.settings.createSetting("cpuProfilerShowAverageTimeAsPercent",true);this._viewType=WebInspector.settings.createSetting("cpuProfilerView",WebInspector.CPUProfileView._TypeHeavy);var columns=[];columns.push({id:"self",title:WebInspector.UIString("Self"),width:"72px",sort:WebInspector.DataGrid.Order.Descending,sortable:true});columns.push({id:"total",title:WebInspector.UIString("Total"),width:"72px",sortable:true});columns.push({id:"function",title:WebInspector.UIString("Function"),disclosure:true,sortable:true});this.dataGrid=new WebInspector.DataGrid(columns);this.dataGrid.addEventListener(WebInspector.DataGrid.Events.SortingChanged,this._sortProfile,this);this.dataGrid.element.addEventListener("mousedown",this._mouseDownInDataGrid.bind(this),true);this.dataGrid.show(this.element);this.viewSelectComboBox=new WebInspector.StatusBarComboBox(this._changeView.bind(this));var options={};options[WebInspector.CPUProfileView._TypeFlame]=this.viewSelectComboBox.createOption(WebInspector.UIString("Chart"),"",WebInspector.CPUProfileView._TypeFlame);options[WebInspector.CPUProfileView._TypeHeavy]=this.viewSelectComboBox.createOption(WebInspector.UIString("Heavy (Bottom Up)"),"",WebInspector.CPUProfileView._TypeHeavy);options[WebInspector.CPUProfileView._TypeTree]=this.viewSelectComboBox.createOption(WebInspector.UIString("Tree (Top Down)"),"",WebInspector.CPUProfileView._TypeTree);var optionName=this._viewType.get()||WebInspector.CPUProfileView._TypeFlame;var option=options[optionName]||options[WebInspector.CPUProfileView._TypeFlame];this.viewSelectComboBox.select(option);this._statusBarButtonsElement=document.createElement("span");this.percentButton=new WebInspector.StatusBarButton("","percent-time-status-bar-item");this.percentButton.addEventListener("click",this._percentClicked,this);this._statusBarButtonsElement.appendChild(this.percentButton.element);this.focusButton=new WebInspector.StatusBarButton(WebInspector.UIString("Focus selected function."),"focus-profile-node-status-bar-item");this.focusButton.setEnabled(false);this.focusButton.addEventListener("click",this._focusClicked,this);this._statusBarButtonsElement.appendChild(this.focusButton.element);this.excludeButton=new WebInspector.StatusBarButton(WebInspector.UIString("Exclude selected function."),"exclude-profile-node-status-bar-item");this.excludeButton.setEnabled(false);this.excludeButton.addEventListener("click",this._excludeClicked,this);this._statusBarButtonsElement.appendChild(this.excludeButton.element);this.resetButton=new WebInspector.StatusBarButton(WebInspector.UIString("Restore all functions."),"reset-profile-status-bar-item");this.resetButton.visible=false;this.resetButton.addEventListener("click",this._resetClicked,this);this._statusBarButtonsElement.appendChild(this.resetButton.element);this.profileHead=(null);this.profile=profileHeader;this._linkifier=new WebInspector.Linkifier(new WebInspector.Linkifier.DefaultFormatter(30));if(this.profile._profile)
347 this._processProfileData(this.profile._profile);else
348 this._processProfileData(this.profile.protocolProfile());}
349 WebInspector.CPUProfileView._TypeFlame="Flame";WebInspector.CPUProfileView._TypeTree="Tree";WebInspector.CPUProfileView._TypeHeavy="Heavy";WebInspector.CPUProfileView.prototype={selectRange:function(timeLeft,timeRight)
350 {if(!this._flameChart)
351 return;this._flameChart.selectRange(timeLeft,timeRight);},_processProfileData:function(profile)
352 {this.profileHead=profile.head;this.samples=profile.samples;this._calculateTimes(profile);this._assignParentsInProfile();if(this.samples)
353 this._buildIdToNodeMap();this._changeView();this._updatePercentButton();if(this._flameChart)
354 this._flameChart.update();},get statusBarItems()
355 {return[this.viewSelectComboBox.element,this._statusBarButtonsElement];},_getBottomUpProfileDataGridTree:function()
356 {if(!this._bottomUpProfileDataGridTree)
357 this._bottomUpProfileDataGridTree=new WebInspector.BottomUpProfileDataGridTree(this,(this.profileHead));return this._bottomUpProfileDataGridTree;},_getTopDownProfileDataGridTree:function()
358 {if(!this._topDownProfileDataGridTree)
359 this._topDownProfileDataGridTree=new WebInspector.TopDownProfileDataGridTree(this,(this.profileHead));return this._topDownProfileDataGridTree;},willHide:function()
360 {this._currentSearchResultIndex=-1;},refresh:function()
361 {var selectedProfileNode=this.dataGrid.selectedNode?this.dataGrid.selectedNode.profileNode:null;this.dataGrid.rootNode().removeChildren();var children=this.profileDataGridTree.children;var count=children.length;for(var index=0;index<count;++index)
362 this.dataGrid.rootNode().appendChild(children[index]);if(selectedProfileNode)
363 selectedProfileNode.selected=true;},refreshVisibleData:function()
364 {var child=this.dataGrid.rootNode().children[0];while(child){child.refresh();child=child.traverseNextNode(false,null,true);}},refreshShowAsPercents:function()
365 {this._updatePercentButton();this.refreshVisibleData();},searchCanceled:function()
366 {if(this._searchResults){for(var i=0;i<this._searchResults.length;++i){var profileNode=this._searchResults[i].profileNode;delete profileNode._searchMatchedSelfColumn;delete profileNode._searchMatchedTotalColumn;delete profileNode._searchMatchedFunctionColumn;profileNode.refresh();}}
367 delete this._searchFinishedCallback;this._currentSearchResultIndex=-1;this._searchResults=[];},performSearch:function(query,finishedCallback)
368 {this.searchCanceled();query=query.trim();if(!query.length)
369 return;this._searchFinishedCallback=finishedCallback;var greaterThan=(query.startsWith(">"));var lessThan=(query.startsWith("<"));var equalTo=(query.startsWith("=")||((greaterThan||lessThan)&&query.indexOf("=")===1));var percentUnits=(query.lastIndexOf("%")===(query.length-1));var millisecondsUnits=(query.length>2&&query.lastIndexOf("ms")===(query.length-2));var secondsUnits=(!millisecondsUnits&&query.lastIndexOf("s")===(query.length-1));var queryNumber=parseFloat(query);if(greaterThan||lessThan||equalTo){if(equalTo&&(greaterThan||lessThan))
370 queryNumber=parseFloat(query.substring(2));else
371 queryNumber=parseFloat(query.substring(1));}
372 var queryNumberMilliseconds=(secondsUnits?(queryNumber*1000):queryNumber);if(!isNaN(queryNumber)&&!(greaterThan||lessThan))
373 equalTo=true;var matcher=createPlainTextSearchRegex(query,"i");function matchesQuery(profileDataGridNode)
374 {delete profileDataGridNode._searchMatchedSelfColumn;delete profileDataGridNode._searchMatchedTotalColumn;delete profileDataGridNode._searchMatchedFunctionColumn;if(percentUnits){if(lessThan){if(profileDataGridNode.selfPercent<queryNumber)
375 profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent<queryNumber)
376 profileDataGridNode._searchMatchedTotalColumn=true;}else if(greaterThan){if(profileDataGridNode.selfPercent>queryNumber)
377 profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent>queryNumber)
378 profileDataGridNode._searchMatchedTotalColumn=true;}
379 if(equalTo){if(profileDataGridNode.selfPercent==queryNumber)
380 profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalPercent==queryNumber)
381 profileDataGridNode._searchMatchedTotalColumn=true;}}else if(millisecondsUnits||secondsUnits){if(lessThan){if(profileDataGridNode.selfTime<queryNumberMilliseconds)
382 profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalTime<queryNumberMilliseconds)
383 profileDataGridNode._searchMatchedTotalColumn=true;}else if(greaterThan){if(profileDataGridNode.selfTime>queryNumberMilliseconds)
384 profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalTime>queryNumberMilliseconds)
385 profileDataGridNode._searchMatchedTotalColumn=true;}
386 if(equalTo){if(profileDataGridNode.selfTime==queryNumberMilliseconds)
387 profileDataGridNode._searchMatchedSelfColumn=true;if(profileDataGridNode.totalTime==queryNumberMilliseconds)
388 profileDataGridNode._searchMatchedTotalColumn=true;}}
389 if(profileDataGridNode.functionName.match(matcher)||(profileDataGridNode.url&&profileDataGridNode.url.match(matcher)))
390 profileDataGridNode._searchMatchedFunctionColumn=true;if(profileDataGridNode._searchMatchedSelfColumn||profileDataGridNode._searchMatchedTotalColumn||profileDataGridNode._searchMatchedFunctionColumn)
391 {profileDataGridNode.refresh();return true;}
392 return false;}
393 var current=this.profileDataGridTree.children[0];while(current){if(matchesQuery(current)){this._searchResults.push({profileNode:current});}
394 current=current.traverseNextNode(false,null,false);}
395 finishedCallback(this,this._searchResults.length);},jumpToFirstSearchResult:function()
396 {if(!this._searchResults||!this._searchResults.length)
397 return;this._currentSearchResultIndex=0;this._jumpToSearchResult(this._currentSearchResultIndex);},jumpToLastSearchResult:function()
398 {if(!this._searchResults||!this._searchResults.length)
399 return;this._currentSearchResultIndex=(this._searchResults.length-1);this._jumpToSearchResult(this._currentSearchResultIndex);},jumpToNextSearchResult:function()
400 {if(!this._searchResults||!this._searchResults.length)
401 return;if(++this._currentSearchResultIndex>=this._searchResults.length)
402 this._currentSearchResultIndex=0;this._jumpToSearchResult(this._currentSearchResultIndex);},jumpToPreviousSearchResult:function()
403 {if(!this._searchResults||!this._searchResults.length)
404 return;if(--this._currentSearchResultIndex<0)
405 this._currentSearchResultIndex=(this._searchResults.length-1);this._jumpToSearchResult(this._currentSearchResultIndex);},showingFirstSearchResult:function()
406 {return(this._currentSearchResultIndex===0);},showingLastSearchResult:function()
407 {return(this._searchResults&&this._currentSearchResultIndex===(this._searchResults.length-1));},currentSearchResultIndex:function(){return this._currentSearchResultIndex;},_jumpToSearchResult:function(index)
408 {var searchResult=this._searchResults[index];if(!searchResult)
409 return;var profileNode=searchResult.profileNode;profileNode.revealAndSelect();},_ensureFlameChartCreated:function()
410 {if(this._flameChart)
411 return;this._dataProvider=new WebInspector.CPUFlameChartDataProvider(this);this._flameChart=new WebInspector.CPUProfileFlameChart(this._dataProvider);this._flameChart.addEventListener(WebInspector.FlameChart.Events.EntrySelected,this._onEntrySelected.bind(this));},_onEntrySelected:function(event)
412 {var entryIndex=event.data;var node=this._dataProvider._entryNodes[entryIndex];if(!node||!node.scriptId)
413 return;var script=WebInspector.debuggerModel.scriptForId(node.scriptId)
414 if(!script)
415 return;WebInspector.Revealer.reveal(script.rawLocationToUILocation(node.lineNumber));},_changeView:function()
416 {if(!this.profile)
417 return;switch(this.viewSelectComboBox.selectedOption().value){case WebInspector.CPUProfileView._TypeFlame:this._ensureFlameChartCreated();this.dataGrid.detach();this._flameChart.show(this.element);this._viewType.set(WebInspector.CPUProfileView._TypeFlame);this._statusBarButtonsElement.classList.toggle("hidden",true);return;case WebInspector.CPUProfileView._TypeTree:this.profileDataGridTree=this._getTopDownProfileDataGridTree();this._sortProfile();this._viewType.set(WebInspector.CPUProfileView._TypeTree);break;case WebInspector.CPUProfileView._TypeHeavy:this.profileDataGridTree=this._getBottomUpProfileDataGridTree();this._sortProfile();this._viewType.set(WebInspector.CPUProfileView._TypeHeavy);break;}
418 this._statusBarButtonsElement.classList.toggle("hidden",false);if(this._flameChart)
419 this._flameChart.detach();this.dataGrid.show(this.element);if(!this.currentQuery||!this._searchFinishedCallback||!this._searchResults)
420 return;this._searchFinishedCallback(this,-this._searchResults.length);this.performSearch(this.currentQuery,this._searchFinishedCallback);},_percentClicked:function(event)
421 {var currentState=this.showSelfTimeAsPercent.get()&&this.showTotalTimeAsPercent.get()&&this.showAverageTimeAsPercent.get();this.showSelfTimeAsPercent.set(!currentState);this.showTotalTimeAsPercent.set(!currentState);this.showAverageTimeAsPercent.set(!currentState);this.refreshShowAsPercents();},_updatePercentButton:function()
422 {if(this.showSelfTimeAsPercent.get()&&this.showTotalTimeAsPercent.get()&&this.showAverageTimeAsPercent.get()){this.percentButton.title=WebInspector.UIString("Show absolute total and self times.");this.percentButton.toggled=true;}else{this.percentButton.title=WebInspector.UIString("Show total and self times as percentages.");this.percentButton.toggled=false;}},_focusClicked:function(event)
423 {if(!this.dataGrid.selectedNode)
424 return;this.resetButton.visible=true;this.profileDataGridTree.focus(this.dataGrid.selectedNode);this.refresh();this.refreshVisibleData();},_excludeClicked:function(event)
425 {var selectedNode=this.dataGrid.selectedNode
426 if(!selectedNode)
427 return;selectedNode.deselect();this.resetButton.visible=true;this.profileDataGridTree.exclude(selectedNode);this.refresh();this.refreshVisibleData();},_resetClicked:function(event)
428 {this.resetButton.visible=false;this.profileDataGridTree.restore();this._linkifier.reset();this.refresh();this.refreshVisibleData();},_dataGridNodeSelected:function(node)
429 {this.focusButton.setEnabled(true);this.excludeButton.setEnabled(true);},_dataGridNodeDeselected:function(node)
430 {this.focusButton.setEnabled(false);this.excludeButton.setEnabled(false);},_sortProfile:function()
431 {var sortAscending=this.dataGrid.isSortOrderAscending();var sortColumnIdentifier=this.dataGrid.sortColumnIdentifier();var sortProperty={"self":"selfTime","total":"totalTime","function":"functionName"}[sortColumnIdentifier];this.profileDataGridTree.sort(WebInspector.ProfileDataGridTree.propertyComparator(sortProperty,sortAscending));this.refresh();},_mouseDownInDataGrid:function(event)
432 {if(event.detail<2)
433 return;var cell=event.target.enclosingNodeOrSelfWithNodeName("td");if(!cell||(!cell.classList.contains("total-column")&&!cell.classList.contains("self-column")&&!cell.classList.contains("average-column")))
434 return;if(cell.classList.contains("total-column"))
435 this.showTotalTimeAsPercent.set(!this.showTotalTimeAsPercent.get());else if(cell.classList.contains("self-column"))
436 this.showSelfTimeAsPercent.set(!this.showSelfTimeAsPercent.get());else if(cell.classList.contains("average-column"))
437 this.showAverageTimeAsPercent.set(!this.showAverageTimeAsPercent.get());this.refreshShowAsPercents();event.consume(true);},_calculateTimes:function(profile)
438 {function totalHitCount(node){var result=node.hitCount;for(var i=0;i<node.children.length;i++)
439 result+=totalHitCount(node.children[i]);return result;}
440 profile.totalHitCount=totalHitCount(profile.head);var durationMs=1000*(profile.endTime-profile.startTime);var samplingInterval=durationMs/profile.totalHitCount;this.samplingIntervalMs=samplingInterval;function calculateTimesForNode(node){node.selfTime=node.hitCount*samplingInterval;var totalHitCount=node.hitCount;for(var i=0;i<node.children.length;i++)
441 totalHitCount+=calculateTimesForNode(node.children[i]);node.totalTime=totalHitCount*samplingInterval;return totalHitCount;}
442 calculateTimesForNode(profile.head);},_assignParentsInProfile:function()
443 {var head=this.profileHead;head.parent=null;head.head=null;var nodesToTraverse=[head];while(nodesToTraverse.length){var parent=nodesToTraverse.pop();var children=parent.children;var length=children.length;for(var i=0;i<length;++i){var child=children[i];child.head=head;child.parent=parent;if(child.children.length)
444 nodesToTraverse.push(child);}}},_buildIdToNodeMap:function()
445 {var idToNode=this._idToNode={};var stack=[this.profileHead];while(stack.length){var node=stack.pop();idToNode[node.id]=node;for(var i=0;i<node.children.length;i++)
446 stack.push(node.children[i]);}
447 var topLevelNodes=this.profileHead.children;for(var i=0;i<topLevelNodes.length;i++){var node=topLevelNodes[i];if(node.functionName==="(garbage collector)"){this._gcNode=node;break;}}},__proto__:WebInspector.VBox.prototype}
448 WebInspector.CPUProfileType=function()
449 {WebInspector.ProfileType.call(this,WebInspector.CPUProfileType.TypeId,WebInspector.UIString("Collect JavaScript CPU Profile"));this._recording=false;this._nextAnonymousConsoleProfileNumber=1;this._anonymousConsoleProfileIdToTitle={};WebInspector.CPUProfileType.instance=this;WebInspector.cpuProfilerModel.setDelegate(this);}
450 WebInspector.CPUProfileType.TypeId="CPU";WebInspector.CPUProfileType.prototype={fileExtension:function()
451 {return".cpuprofile";},get buttonTooltip()
452 {return this._recording?WebInspector.UIString("Stop CPU profiling."):WebInspector.UIString("Start CPU profiling.");},buttonClicked:function()
453 {if(this._recording){this.stopRecordingProfile();return false;}else{this.startRecordingProfile();return true;}},get treeItemTitle()
454 {return WebInspector.UIString("CPU PROFILES");},get description()
455 {return WebInspector.UIString("CPU profiles show where the execution time is spent in your page's JavaScript functions.");},consoleProfileStarted:function(id,scriptLocation,title)
456 {var resolvedTitle=title;if(!resolvedTitle){resolvedTitle=WebInspector.UIString("Profile %s",this._nextAnonymousConsoleProfileNumber++);this._anonymousConsoleProfileIdToTitle[id]=resolvedTitle;}
457 this._addMessageToConsole(WebInspector.ConsoleMessage.MessageType.Profile,scriptLocation,WebInspector.UIString("Profile '%s' started.",resolvedTitle));},consoleProfileFinished:function(protocolId,scriptLocation,cpuProfile,title)
458 {var resolvedTitle=title;if(typeof title==="undefined"){resolvedTitle=this._anonymousConsoleProfileIdToTitle[protocolId];delete this._anonymousConsoleProfileIdToTitle[protocolId];}
459 var profile=new WebInspector.CPUProfileHeader(this,resolvedTitle);profile.setProtocolProfile(cpuProfile);this.addProfile(profile);this._addMessageToConsole(WebInspector.ConsoleMessage.MessageType.ProfileEnd,scriptLocation,WebInspector.UIString("Profile '%s' finished.",resolvedTitle));},_addMessageToConsole:function(type,scriptLocation,messageText)
460 {var script=WebInspector.debuggerModel.scriptForId(scriptLocation.scriptId);var message=new WebInspector.ConsoleMessage(WebInspector.ConsoleMessage.MessageSource.ConsoleAPI,WebInspector.ConsoleMessage.MessageLevel.Debug,messageText,type,undefined,undefined,undefined,undefined,undefined,[{functionName:"",scriptId:scriptLocation.scriptId,url:script?script.contentURL():"",lineNumber:scriptLocation.lineNumber,columnNumber:scriptLocation.columnNumber||0}]);WebInspector.console.addMessage(message);},isRecordingProfile:function()
461 {return this._recording;},startRecordingProfile:function()
462 {if(this._profileBeingRecorded)
463 return;this._profileBeingRecorded=new WebInspector.CPUProfileHeader(this);this.addProfile(this._profileBeingRecorded);this._profileBeingRecorded.updateStatus(WebInspector.UIString("Recording\u2026"));this._recording=true;WebInspector.cpuProfilerModel.setRecording(true);WebInspector.userMetrics.ProfilesCPUProfileTaken.record();ProfilerAgent.start();},stopRecordingProfile:function()
464 {this._recording=false;WebInspector.cpuProfilerModel.setRecording(false);function didStopProfiling(error,profile)
465 {if(!this._profileBeingRecorded)
466 return;this._profileBeingRecorded.setProtocolProfile(profile);this._profileBeingRecorded.updateStatus("");var recordedProfile=this._profileBeingRecorded;this._profileBeingRecorded=null;WebInspector.panels.profiles.showProfile(recordedProfile);}
467 ProfilerAgent.stop(didStopProfiling.bind(this));},createProfileLoadedFromFile:function(title)
468 {return new WebInspector.CPUProfileHeader(this,title);},profileBeingRecordedRemoved:function()
469 {this.stopRecordingProfile();},__proto__:WebInspector.ProfileType.prototype}
470 WebInspector.CPUProfileHeader=function(type,title)
471 {WebInspector.ProfileHeader.call(this,type,title||WebInspector.UIString("Profile %d",type._nextProfileUid));this._tempFile=null;}
472 WebInspector.CPUProfileHeader.prototype={onTransferStarted:function()
473 {this._jsonifiedProfile="";this.updateStatus(WebInspector.UIString("Loading\u2026 %s",Number.bytesToString(this._jsonifiedProfile.length)),true);},onChunkTransferred:function(reader)
474 {this.updateStatus(WebInspector.UIString("Loading\u2026 %d\%",Number.bytesToString(this._jsonifiedProfile.length)));},onTransferFinished:function()
475 {this.updateStatus(WebInspector.UIString("Parsing\u2026"),true);this._profile=JSON.parse(this._jsonifiedProfile);this._jsonifiedProfile=null;this.updateStatus(WebInspector.UIString("Loaded"),false);if(this._profileType._profileBeingRecorded===this)
476 this._profileType._profileBeingRecorded=null;},onError:function(reader,e)
477 {var subtitle;switch(e.target.error.code){case e.target.error.NOT_FOUND_ERR:subtitle=WebInspector.UIString("'%s' not found.",reader.fileName());break;case e.target.error.NOT_READABLE_ERR:subtitle=WebInspector.UIString("'%s' is not readable",reader.fileName());break;case e.target.error.ABORT_ERR:return;default:subtitle=WebInspector.UIString("'%s' error %d",reader.fileName(),e.target.error.code);}
478 this.updateStatus(subtitle);},write:function(text)
479 {this._jsonifiedProfile+=text;},close:function(){},dispose:function()
480 {this.removeTempFile();},createSidebarTreeElement:function()
481 {return new WebInspector.ProfileSidebarTreeElement(this,"profile-sidebar-tree-item");},createView:function()
482 {return new WebInspector.CPUProfileView(this);},canSaveToFile:function()
483 {return!this.fromFile()&&this._protocolProfile;},saveToFile:function()
484 {var fileOutputStream=new WebInspector.FileOutputStream();function onOpenForSave(accepted)
485 {if(!accepted)
486 return;function didRead(data)
487 {if(data)
488 fileOutputStream.write(data,fileOutputStream.close.bind(fileOutputStream));else
489 fileOutputStream.close();}
490 if(this._failedToCreateTempFile){WebInspector.console.log("Failed to open temp file with heap snapshot",WebInspector.ConsoleMessage.MessageLevel.Error);fileOutputStream.close();}else if(this._tempFile){this._tempFile.read(didRead);}else{this._onTempFileReady=onOpenForSave.bind(this,accepted);}}
491 this._fileName=this._fileName||"CPU-"+new Date().toISO8601Compact()+this._profileType.fileExtension();fileOutputStream.open(this._fileName,onOpenForSave.bind(this));},loadFromFile:function(file)
492 {this.updateStatus(WebInspector.UIString("Loading\u2026"),true);var fileReader=new WebInspector.ChunkedFileReader(file,10000000,this);fileReader.start(this);},protocolProfile:function()
493 {return this._protocolProfile;},setProtocolProfile:function(cpuProfile)
494 {this._protocolProfile=cpuProfile;this._saveProfileDataToTempFile(cpuProfile);if(this.canSaveToFile())
495 this.dispatchEventToListeners(WebInspector.ProfileHeader.Events.ProfileReceived);},_saveProfileDataToTempFile:function(data)
496 {var serializedData=JSON.stringify(data);function didCreateTempFile(tempFile)
497 {this._writeToTempFile(tempFile,serializedData);}
498 new WebInspector.TempFile("cpu-profiler",this.uid,didCreateTempFile.bind(this));},_writeToTempFile:function(tempFile,serializedData)
499 {this._tempFile=tempFile;if(!tempFile){this._failedToCreateTempFile=true;this._notifyTempFileReady();return;}
500 function didWriteToTempFile(success)
501 {if(!success)
502 this._failedToCreateTempFile=true;tempFile.finishWriting();this._notifyTempFileReady();}
503 tempFile.write(serializedData,didWriteToTempFile.bind(this));},_notifyTempFileReady:function()
504 {if(this._onTempFileReady){this._onTempFileReady();this._onTempFileReady=null;}},__proto__:WebInspector.ProfileHeader.prototype}
505 WebInspector.CPUProfileView.colorGenerator=function()
506 {if(!WebInspector.CPUProfileView._colorGenerator){var colorGenerator=new WebInspector.CPUProfileFlameChart.ColorGenerator();colorGenerator.colorForID("(idle)::0",50);colorGenerator.colorForID("(program)::0",50);colorGenerator.colorForID("(garbage collector)::0",50);WebInspector.CPUProfileView._colorGenerator=colorGenerator;}
507 return WebInspector.CPUProfileView._colorGenerator;}
508 WebInspector.CPUFlameChartDataProvider=function(cpuProfileView)
509 {WebInspector.FlameChartDataProvider.call(this);this._cpuProfileView=cpuProfileView;this._colorGenerator=WebInspector.CPUProfileView.colorGenerator();}
510 WebInspector.CPUFlameChartDataProvider.prototype={barHeight:function()
511 {return 15;},textBaseline:function()
512 {return 4;},textPadding:function()
513 {return 2;},dividerOffsets:function(startTime,endTime)
514 {return null;},zeroTime:function()
515 {return 0;},totalTime:function()
516 {return this._cpuProfileView.profileHead.totalTime;},maxStackDepth:function()
517 {return this._maxStackDepth;},timelineData:function()
518 {return this._timelineData||this._calculateTimelineData();},_calculateTimelineData:function()
519 {if(!this._cpuProfileView.profileHead)
520 return null;var samples=this._cpuProfileView.samples;var idToNode=this._cpuProfileView._idToNode;var gcNode=this._cpuProfileView._gcNode;var samplesCount=samples.length;var samplingInterval=this._cpuProfileView.samplingIntervalMs;var index=0;var openIntervals=[];var stackTrace=[];var maxDepth=5;var depth=0;function ChartEntry(depth,duration,startTime,node)
521 {this.depth=depth;this.duration=duration;this.startTime=startTime;this.node=node;this.selfTime=0;}
522 var entries=([]);for(var sampleIndex=0;sampleIndex<samplesCount;sampleIndex++){var node=idToNode[samples[sampleIndex]];stackTrace.length=0;while(node){stackTrace.push(node);node=node.parent;}
523 stackTrace.pop();maxDepth=Math.max(maxDepth,depth);depth=0;node=stackTrace.pop();var intervalIndex;if(node===gcNode){while(depth<openIntervals.length){intervalIndex=openIntervals[depth].index;entries[intervalIndex].duration+=samplingInterval;++depth;}
524 if(openIntervals.length>0&&openIntervals.peekLast().node===node){entries[intervalIndex].selfTime+=samplingInterval;continue;}}
525 while(node&&depth<openIntervals.length&&node===openIntervals[depth].node){intervalIndex=openIntervals[depth].index;entries[intervalIndex].duration+=samplingInterval;node=stackTrace.pop();++depth;}
526 if(depth<openIntervals.length)
527 openIntervals.length=depth;if(!node){entries[intervalIndex].selfTime+=samplingInterval;continue;}
528 var colorGenerator=this._colorGenerator;var color="";while(node){entries.push(new ChartEntry(depth,samplingInterval,sampleIndex*samplingInterval,node));openIntervals.push({node:node,index:index});++index;node=stackTrace.pop();++depth;}
529 entries[entries.length-1].selfTime+=samplingInterval;}
530 var entryNodes=new Array(entries.length);var entryLevels=new Uint8Array(entries.length);var entryTotalTimes=new Float32Array(entries.length);var entrySelfTimes=new Float32Array(entries.length);var entryOffsets=new Float32Array(entries.length);for(var i=0;i<entries.length;++i){var entry=entries[i];entryNodes[i]=entry.node;entryLevels[i]=entry.depth;entryTotalTimes[i]=entry.duration;entryOffsets[i]=entry.startTime;entrySelfTimes[i]=entry.selfTime;}
531 this._maxStackDepth=Math.max(maxDepth,depth);this._timelineData={entryLevels:entryLevels,entryTotalTimes:entryTotalTimes,entryOffsets:entryOffsets,};this._entryNodes=entryNodes;this._entrySelfTimes=entrySelfTimes;return(this._timelineData);},_millisecondsToString:function(ms)
532 {if(ms===0)
533 return"0";if(ms<1000)
534 return WebInspector.UIString("%.1f\u2009ms",ms);return Number.secondsToString(ms/1000,true);},prepareHighlightedEntryInfo:function(entryIndex)
535 {var timelineData=this._timelineData;var node=this._entryNodes[entryIndex];if(!node)
536 return null;var entryInfo=[];function pushEntryInfoRow(title,text)
537 {var row={};row.title=title;row.text=text;entryInfo.push(row);}
538 pushEntryInfoRow(WebInspector.UIString("Name"),node.functionName);var selfTime=this._millisecondsToString(this._entrySelfTimes[entryIndex]);var totalTime=this._millisecondsToString(timelineData.entryTotalTimes[entryIndex]);pushEntryInfoRow(WebInspector.UIString("Self time"),selfTime);pushEntryInfoRow(WebInspector.UIString("Total time"),totalTime);var text=WebInspector.Linkifier.liveLocationText(node.scriptId,node.lineNumber,node.columnNumber);pushEntryInfoRow(WebInspector.UIString("URL"),text);pushEntryInfoRow(WebInspector.UIString("Aggregated self time"),Number.secondsToString(node.selfTime/1000,true));pushEntryInfoRow(WebInspector.UIString("Aggregated total time"),Number.secondsToString(node.totalTime/1000,true));if(node.deoptReason&&node.deoptReason!=="no reason")
539 pushEntryInfoRow(WebInspector.UIString("Not optimized"),node.deoptReason);return entryInfo;},canJumpToEntry:function(entryIndex)
540 {return this._entryNodes[entryIndex].scriptId!=="0";},entryTitle:function(entryIndex)
541 {var node=this._entryNodes[entryIndex];return node.functionName;},entryFont:function(entryIndex)
542 {if(!this._font){this._font=(this.barHeight()-4)+"px "+WebInspector.fontFamily();this._boldFont="bold "+this._font;}
543 var node=this._entryNodes[entryIndex];var reason=node.deoptReason;return(reason&&reason!=="no reason")?this._boldFont:this._font;},entryColor:function(entryIndex)
544 {var node=this._entryNodes[entryIndex];return this._colorGenerator.colorForID(node.functionName+":"+node.url+":"+node.lineNumber);},decorateEntry:function(entryIndex,context,text,barX,barY,barWidth,barHeight,offsetToPosition)
545 {return false;},forceDecoration:function(entryIndex)
546 {return false;},highlightTimeRange:function(entryIndex)
547 {var startTimeOffset=this._timelineData.entryOffsets[entryIndex];return{startTimeOffset:startTimeOffset,endTimeOffset:startTimeOffset+this._timelineData.entryTotalTimes[entryIndex]};},paddingLeft:function()
548 {return 15;},textColor:function(entryIndex)
549 {return"#333";}};WebInspector.HeapSnapshotProgressEvent={Update:"ProgressUpdate"};WebInspector.HeapSnapshotCommon={}
550 WebInspector.HeapSnapshotCommon.AllocationNodeCallers=function(nodesWithSingleCaller,branchingCallers)
551 {this.nodesWithSingleCaller=nodesWithSingleCaller;this.branchingCallers=branchingCallers;}
552 WebInspector.HeapSnapshotCommon.SerializedAllocationNode=function(nodeId,functionName,scriptName,line,column,count,size,liveCount,liveSize,hasChildren)
553 {this.id=nodeId;this.name=functionName;this.scriptName=scriptName;this.line=line;this.column=column;this.count=count;this.size=size;this.liveCount=liveCount;this.liveSize=liveSize;this.hasChildren=hasChildren;}
554 WebInspector.HeapSnapshotCommon.Aggregate=function()
555 {this.count;this.distance;this.self;this.maxRet;this.type;this.name;this.idxs;}
556 WebInspector.HeapSnapshotCommon.AggregateForDiff=function(){this.indexes=[];this.ids=[];this.selfSizes=[];}
557 WebInspector.HeapSnapshotCommon.Diff=function()
558 {this.addedCount=0;this.removedCount=0;this.addedSize=0;this.removedSize=0;this.deletedIndexes=[];this.addedIndexes=[];}
559 WebInspector.HeapSnapshotCommon.DiffForClass=function()
560 {this.addedCount;this.removedCount;this.addedSize;this.removedSize;this.deletedIndexes;this.addedIndexes;this.countDelta;this.sizeDelta;}
561 WebInspector.HeapSnapshotCommon.ComparatorConfig=function()
562 {this.fieldName1;this.ascending1;this.fieldName2;this.ascending2;}
563 WebInspector.HeapSnapshotCommon.WorkerCommand=function()
564 {this.callId;this.disposition;this.objectId;this.newObjectId;this.methodName;this.methodArguments;this.source;}
565 WebInspector.HeapSnapshotCommon.ItemsRange=function(startPosition,endPosition,totalLength,items)
566 {this.startPosition=startPosition;this.endPosition=endPosition;this.totalLength=totalLength;this.items=items;}
567 WebInspector.HeapSnapshotCommon.StaticData=function(nodeCount,rootNodeIndex,totalSize,maxJSObjectId)
568 {this.nodeCount=nodeCount;this.rootNodeIndex=rootNodeIndex;this.totalSize=totalSize;this.maxJSObjectId=maxJSObjectId;}
569 WebInspector.HeapSnapshotCommon.Statistics=function()
570 {this.total;this.v8heap;this.native;this.code;this.jsArrays;this.strings;}
571 WebInspector.HeapSnapshotCommon.NodeFilter=function(minNodeId,maxNodeId)
572 {this.minNodeId=minNodeId;this.maxNodeId=maxNodeId;this.allocationNodeId;}
573 WebInspector.HeapSnapshotCommon.NodeFilter.prototype={equals:function(o)
574 {return this.minNodeId===o.minNodeId&&this.maxNodeId===o.maxNodeId&&this.allocationNodeId===o.allocationNodeId;}};WebInspector.HeapSnapshotWorkerProxy=function(eventHandler)
575 {this._eventHandler=eventHandler;this._nextObjectId=1;this._nextCallId=1;this._callbacks=[];this._previousCallbacks=[];this._worker=new Worker("HeapSnapshotWorker.js");this._worker.onmessage=this._messageReceived.bind(this);}
576 WebInspector.HeapSnapshotWorkerProxy.prototype={createLoader:function(profileUid,snapshotReceivedCallback)
577 {var objectId=this._nextObjectId++;var proxy=new WebInspector.HeapSnapshotLoaderProxy(this,objectId,profileUid,snapshotReceivedCallback);this._postMessage({callId:this._nextCallId++,disposition:"create",objectId:objectId,methodName:"WebInspector.HeapSnapshotLoader"});return proxy;},dispose:function()
578 {this._worker.terminate();if(this._interval)
579 clearInterval(this._interval);},disposeObject:function(objectId)
580 {this._postMessage({callId:this._nextCallId++,disposition:"dispose",objectId:objectId});},evaluateForTest:function(script,callback)
581 {var callId=this._nextCallId++;this._callbacks[callId]=callback;this._postMessage({callId:callId,disposition:"evaluateForTest",source:script});},callFactoryMethod:function(callback,objectId,methodName,proxyConstructor)
582 {var callId=this._nextCallId++;var methodArguments=Array.prototype.slice.call(arguments,4);var newObjectId=this._nextObjectId++;function wrapCallback(remoteResult)
583 {callback(remoteResult?new proxyConstructor(this,newObjectId):null);}
584 if(callback){this._callbacks[callId]=wrapCallback.bind(this);this._postMessage({callId:callId,disposition:"factory",objectId:objectId,methodName:methodName,methodArguments:methodArguments,newObjectId:newObjectId});return null;}else{this._postMessage({callId:callId,disposition:"factory",objectId:objectId,methodName:methodName,methodArguments:methodArguments,newObjectId:newObjectId});return new proxyConstructor(this,newObjectId);}},callMethod:function(callback,objectId,methodName)
585 {var callId=this._nextCallId++;var methodArguments=Array.prototype.slice.call(arguments,3);if(callback)
586 this._callbacks[callId]=callback;this._postMessage({callId:callId,disposition:"method",objectId:objectId,methodName:methodName,methodArguments:methodArguments});},startCheckingForLongRunningCalls:function()
587 {if(this._interval)
588 return;this._checkLongRunningCalls();this._interval=setInterval(this._checkLongRunningCalls.bind(this),300);},_checkLongRunningCalls:function()
589 {for(var callId in this._previousCallbacks)
590 if(!(callId in this._callbacks))
591 delete this._previousCallbacks[callId];var hasLongRunningCalls=false;for(callId in this._previousCallbacks){hasLongRunningCalls=true;break;}
592 this.dispatchEventToListeners("wait",hasLongRunningCalls);for(callId in this._callbacks)
593 this._previousCallbacks[callId]=true;},_messageReceived:function(event)
594 {var data=event.data;if(data.eventName){if(this._eventHandler)
595 this._eventHandler(data.eventName,data.data);return;}
596 if(data.error){if(data.errorMethodName)
597 WebInspector.console.log(WebInspector.UIString("An error happened when a call for method '%s' was requested",data.errorMethodName));WebInspector.console.log(data["errorCallStack"]);delete this._callbacks[data.callId];return;}
598 if(!this._callbacks[data.callId])
599 return;var callback=this._callbacks[data.callId];delete this._callbacks[data.callId];callback(data.result);},_postMessage:function(message)
600 {this._worker.postMessage(message);},__proto__:WebInspector.Object.prototype}
601 WebInspector.HeapSnapshotProxyObject=function(worker,objectId)
602 {this._worker=worker;this._objectId=objectId;}
603 WebInspector.HeapSnapshotProxyObject.prototype={_callWorker:function(workerMethodName,args)
604 {args.splice(1,0,this._objectId);return this._worker[workerMethodName].apply(this._worker,args);},dispose:function()
605 {this._worker.disposeObject(this._objectId);},disposeWorker:function()
606 {this._worker.dispose();},callFactoryMethod:function(callback,methodName,proxyConstructor,var_args)
607 {return this._callWorker("callFactoryMethod",Array.prototype.slice.call(arguments,0));},callMethod:function(callback,methodName,var_args)
608 {return this._callWorker("callMethod",Array.prototype.slice.call(arguments,0));}};WebInspector.HeapSnapshotLoaderProxy=function(worker,objectId,profileUid,snapshotReceivedCallback)
609 {WebInspector.HeapSnapshotProxyObject.call(this,worker,objectId);this._profileUid=profileUid;this._snapshotReceivedCallback=snapshotReceivedCallback;}
610 WebInspector.HeapSnapshotLoaderProxy.prototype={write:function(chunk,callback)
611 {this.callMethod(callback,"write",chunk);},close:function(callback)
612 {function buildSnapshot()
613 {if(callback)
614 callback();var showHiddenData=WebInspector.settings.showAdvancedHeapSnapshotProperties.get();this.callFactoryMethod(updateStaticData.bind(this),"buildSnapshot",WebInspector.HeapSnapshotProxy,showHiddenData);}
615 function updateStaticData(snapshotProxy)
616 {this.dispose();snapshotProxy.setProfileUid(this._profileUid);snapshotProxy.updateStaticData(this._snapshotReceivedCallback.bind(this));}
617 this.callMethod(buildSnapshot.bind(this),"close");},__proto__:WebInspector.HeapSnapshotProxyObject.prototype}
618 WebInspector.HeapSnapshotProxy=function(worker,objectId)
619 {WebInspector.HeapSnapshotProxyObject.call(this,worker,objectId);this._staticData=null;}
620 WebInspector.HeapSnapshotProxy.prototype={aggregatesWithFilter:function(filter,callback)
621 {this.callMethod(callback,"aggregatesWithFilter",filter);},aggregatesForDiff:function(callback)
622 {this.callMethod(callback,"aggregatesForDiff");},calculateSnapshotDiff:function(baseSnapshotId,baseSnapshotAggregates,callback)
623 {this.callMethod(callback,"calculateSnapshotDiff",baseSnapshotId,baseSnapshotAggregates);},nodeClassName:function(snapshotObjectId,callback)
624 {this.callMethod(callback,"nodeClassName",snapshotObjectId);},dominatorIdsForNode:function(nodeIndex,callback)
625 {this.callMethod(callback,"dominatorIdsForNode",nodeIndex);},createEdgesProvider:function(nodeIndex)
626 {return this.callFactoryMethod(null,"createEdgesProvider",WebInspector.HeapSnapshotProviderProxy,nodeIndex);},createRetainingEdgesProvider:function(nodeIndex)
627 {return this.callFactoryMethod(null,"createRetainingEdgesProvider",WebInspector.HeapSnapshotProviderProxy,nodeIndex);},createAddedNodesProvider:function(baseSnapshotId,className)
628 {return this.callFactoryMethod(null,"createAddedNodesProvider",WebInspector.HeapSnapshotProviderProxy,baseSnapshotId,className);},createDeletedNodesProvider:function(nodeIndexes)
629 {return this.callFactoryMethod(null,"createDeletedNodesProvider",WebInspector.HeapSnapshotProviderProxy,nodeIndexes);},createNodesProvider:function(filter)
630 {return this.callFactoryMethod(null,"createNodesProvider",WebInspector.HeapSnapshotProviderProxy,filter);},createNodesProviderForClass:function(className,nodeFilter)
631 {return this.callFactoryMethod(null,"createNodesProviderForClass",WebInspector.HeapSnapshotProviderProxy,className,nodeFilter);},createNodesProviderForDominator:function(nodeIndex)
632 {return this.callFactoryMethod(null,"createNodesProviderForDominator",WebInspector.HeapSnapshotProviderProxy,nodeIndex);},allocationTracesTops:function(callback)
633 {this.callMethod(callback,"allocationTracesTops");},allocationNodeCallers:function(nodeId,callback)
634 {this.callMethod(callback,"allocationNodeCallers",nodeId);},dispose:function()
635 {throw new Error("Should never be called");},get nodeCount()
636 {return this._staticData.nodeCount;},get rootNodeIndex()
637 {return this._staticData.rootNodeIndex;},updateStaticData:function(callback)
638 {function dataReceived(staticData)
639 {this._staticData=staticData;callback(this);}
640 this.callMethod(dataReceived.bind(this),"updateStaticData");},getStatistics:function(callback)
641 {this.callMethod(callback,"getStatistics");},get totalSize()
642 {return this._staticData.totalSize;},get uid()
643 {return this._profileUid;},setProfileUid:function(profileUid)
644 {this._profileUid=profileUid;},maxJSObjectId:function()
645 {return this._staticData.maxJSObjectId;},__proto__:WebInspector.HeapSnapshotProxyObject.prototype}
646 WebInspector.HeapSnapshotProviderProxy=function(worker,objectId)
647 {WebInspector.HeapSnapshotProxyObject.call(this,worker,objectId);}
648 WebInspector.HeapSnapshotProviderProxy.prototype={nodePosition:function(snapshotObjectId,callback)
649 {this.callMethod(callback,"nodePosition",snapshotObjectId);},isEmpty:function(callback)
650 {this.callMethod(callback,"isEmpty");},serializeItemsRange:function(startPosition,endPosition,callback)
651 {this.callMethod(callback,"serializeItemsRange",startPosition,endPosition);},sortAndRewind:function(comparator,callback)
652 {this.callMethod(callback,"sortAndRewind",comparator);},__proto__:WebInspector.HeapSnapshotProxyObject.prototype};WebInspector.HeapSnapshotSortableDataGrid=function(columns)
653 {WebInspector.DataGrid.call(this,columns);this._recursiveSortingDepth=0;this._highlightedNode=null;this._populatedAndSorted=false;this._nameFilter="";this.addEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.SortingComplete,this._sortingComplete,this);this.addEventListener(WebInspector.DataGrid.Events.SortingChanged,this.sortingChanged,this);}
654 WebInspector.HeapSnapshotSortableDataGrid.Events={ContentShown:"ContentShown",ResetFilter:"ResetFilter",SortingComplete:"SortingComplete"}
655 WebInspector.HeapSnapshotSortableDataGrid.prototype={defaultPopulateCount:function()
656 {return 100;},_disposeAllNodes:function()
657 {var children=this.topLevelNodes();for(var i=0,l=children.length;i<l;++i)
658 children[i].dispose();},wasShown:function()
659 {if(this._populatedAndSorted)
660 this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown,this);},_sortingComplete:function()
661 {this.removeEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.SortingComplete,this._sortingComplete,this);this._populatedAndSorted=true;this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown,this);},willHide:function()
662 {this._clearCurrentHighlight();},populateContextMenu:function(contextMenu,event)
663 {var td=event.target.enclosingNodeOrSelfWithNodeName("td");if(!td)
664 return;var node=td.heapSnapshotNode;function revealInDominatorsView()
665 {WebInspector.panels.profiles.showObject(node.snapshotNodeId,"Dominators");}
666 function revealInSummaryView()
667 {WebInspector.panels.profiles.showObject(node.snapshotNodeId,"Summary");}
668 if(node&&node.showRetainingEdges){contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles()?"Reveal in Summary view":"Reveal in Summary View"),revealInSummaryView);contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles()?"Reveal in Dominators view":"Reveal in Dominators View"),revealInDominatorsView);}
669 else if(node instanceof WebInspector.HeapSnapshotInstanceNode||node instanceof WebInspector.HeapSnapshotObjectNode){contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles()?"Reveal in Dominators view":"Reveal in Dominators View"),revealInDominatorsView);}else if(node instanceof WebInspector.HeapSnapshotDominatorObjectNode){contextMenu.appendItem(WebInspector.UIString(WebInspector.useLowerCaseMenuTitles()?"Reveal in Summary view":"Reveal in Summary View"),revealInSummaryView);}},resetSortingCache:function()
670 {delete this._lastSortColumnIdentifier;delete this._lastSortAscending;},topLevelNodes:function()
671 {return this.rootNode().children;},highlightObjectByHeapSnapshotId:function(heapSnapshotObjectId,callback)
672 {},highlightNode:function(node)
673 {var prevNode=this._highlightedNode;this._clearCurrentHighlight();this._highlightedNode=node;WebInspector.runCSSAnimationOnce(this._highlightedNode.element,"highlighted-row");},nodeWasDetached:function(node)
674 {if(this._highlightedNode===node)
675 this._clearCurrentHighlight();},_clearCurrentHighlight:function()
676 {if(!this._highlightedNode)
677 return
678 this._highlightedNode.element.classList.remove("highlighted-row");this._highlightedNode=null;},resetNameFilter:function(callback)
679 {this._callbackAfterFilterChange=callback;this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.ResetFilter);},changeNameFilter:function(filter)
680 {this._nameFilter=filter.toLowerCase();this.updateVisibleNodes(true);if(this._callbackAfterFilterChange){this._callbackAfterFilterChange();this._callbackAfterFilterChange=null;}},sortingChanged:function()
681 {var sortAscending=this.isSortOrderAscending();var sortColumnIdentifier=this.sortColumnIdentifier();if(this._lastSortColumnIdentifier===sortColumnIdentifier&&this._lastSortAscending===sortAscending)
682 return;this._lastSortColumnIdentifier=sortColumnIdentifier;this._lastSortAscending=sortAscending;var sortFields=this._sortFields(sortColumnIdentifier,sortAscending);function SortByTwoFields(nodeA,nodeB)
683 {var field1=nodeA[sortFields[0]];var field2=nodeB[sortFields[0]];var result=field1<field2?-1:(field1>field2?1:0);if(!sortFields[1])
684 result=-result;if(result!==0)
685 return result;field1=nodeA[sortFields[2]];field2=nodeB[sortFields[2]];result=field1<field2?-1:(field1>field2?1:0);if(!sortFields[3])
686 result=-result;return result;}
687 this._performSorting(SortByTwoFields);},_performSorting:function(sortFunction)
688 {this.recursiveSortingEnter();var children=this.allChildren(this.rootNode());this.rootNode().removeChildren();children.sort(sortFunction);for(var i=0,l=children.length;i<l;++i){var child=children[i];this.appendChildAfterSorting(child);if(child.expanded)
689 child.sort();}
690 this.recursiveSortingLeave();},appendChildAfterSorting:function(child)
691 {var revealed=child.revealed;this.rootNode().appendChild(child);child.revealed=revealed;},recursiveSortingEnter:function()
692 {++this._recursiveSortingDepth;},recursiveSortingLeave:function()
693 {if(!this._recursiveSortingDepth)
694 return;if(--this._recursiveSortingDepth)
695 return;this.updateVisibleNodes(true);this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.SortingComplete);},updateVisibleNodes:function(force)
696 {},allChildren:function(parent)
697 {return parent.children;},insertChild:function(parent,node,index)
698 {parent.insertChild(node,index);},removeChildByIndex:function(parent,index)
699 {parent.removeChild(parent.children[index]);},removeAllChildren:function(parent)
700 {parent.removeChildren();},__proto__:WebInspector.DataGrid.prototype}
701 WebInspector.HeapSnapshotViewportDataGrid=function(columns)
702 {WebInspector.HeapSnapshotSortableDataGrid.call(this,columns);this.scrollContainer.addEventListener("scroll",this._onScroll.bind(this),true);this._nodeToHighlightAfterScroll=null;this._topPadding=new WebInspector.HeapSnapshotPaddingNode();this._topPaddingHeight=0;this.dataTableBody.insertBefore(this._topPadding.element,this.dataTableBody.firstChild);this._bottomPadding=new WebInspector.HeapSnapshotPaddingNode();this._bottomPaddingHeight=0;this.dataTableBody.insertBefore(this._bottomPadding.element,this.dataTableBody.lastChild);}
703 WebInspector.HeapSnapshotViewportDataGrid.prototype={topLevelNodes:function()
704 {return this.allChildren(this.rootNode());},appendChildAfterSorting:function(child)
705 {},updateVisibleNodes:function(force,pathToReveal)
706 {var guardZoneHeight=40;var scrollHeight=this.scrollContainer.scrollHeight;var scrollTop=this.scrollContainer.scrollTop;var scrollBottom=scrollHeight-scrollTop-this.scrollContainer.offsetHeight;scrollTop=Math.max(0,scrollTop-guardZoneHeight);scrollBottom=Math.max(0,scrollBottom-guardZoneHeight);var viewPortHeight=scrollHeight-scrollTop-scrollBottom;if(!pathToReveal){if(!force&&scrollTop>=this._topPaddingHeight&&scrollBottom>=this._bottomPaddingHeight)
707 return;var hysteresisHeight=500;scrollTop-=hysteresisHeight;viewPortHeight+=2*hysteresisHeight;}
708 var selectedNode=this.selectedNode;this.rootNode().removeChildren();this._topPaddingHeight=0;this._bottomPaddingHeight=0;this._addVisibleNodes(this.rootNode(),scrollTop,scrollTop+viewPortHeight,pathToReveal||null);this._topPadding.setHeight(this._topPaddingHeight);this._bottomPadding.setHeight(this._bottomPaddingHeight);if(selectedNode){if(selectedNode.parent)
709 selectedNode.select(true);else
710 this.selectedNode=selectedNode;}},_addVisibleNodes:function(parentNode,topBound,bottomBound,pathToReveal)
711 {if(!parentNode.expanded)
712 return 0;var nodeToReveal=pathToReveal?pathToReveal[0]:null;var restPathToReveal=pathToReveal&&pathToReveal.length>1?pathToReveal.slice(1):null;var children=this.allChildren(parentNode);var topPadding=0;for(var i=0;i<children.length;++i){var child=children[i];if(child.filteredOut&&child.filteredOut())
713 continue;var newTop=topPadding+this._nodeHeight(child);if(nodeToReveal===child||(!nodeToReveal&&newTop>topBound))
714 break;topPadding=newTop;}
715 var position=topPadding;for(;i<children.length&&(nodeToReveal||position<bottomBound);++i){var child=children[i];if(child.filteredOut&&child.filteredOut())
716 continue;var hasChildren=child.hasChildren;child.removeChildren();child.hasChildren=hasChildren;child.revealed=true;parentNode.appendChild(child);position+=child.nodeSelfHeight();position+=this._addVisibleNodes(child,topBound-position,bottomBound-position,restPathToReveal);if(nodeToReveal===child)
717 break;}
718 var bottomPadding=0;for(;i<children.length;++i){var child=children[i];if(child.filteredOut&&child.filteredOut())
719 continue;bottomPadding+=this._nodeHeight(child);}
720 this._topPaddingHeight+=topPadding;this._bottomPaddingHeight+=bottomPadding;return position+bottomPadding;},_nodeHeight:function(node)
721 {if(!node.revealed)
722 return 0;var result=node.nodeSelfHeight();if(!node.expanded)
723 return result;var children=this.allChildren(node);for(var i=0;i<children.length;i++)
724 result+=this._nodeHeight(children[i]);return result;},defaultAttachLocation:function()
725 {return this._bottomPadding.element;},revealTreeNode:function(pathToReveal)
726 {this.updateVisibleNodes(true,pathToReveal);},allChildren:function(parent)
727 {return parent._allChildren||(parent._allChildren=[]);},appendNode:function(parent,node)
728 {this.allChildren(parent).push(node);},insertChild:function(parent,node,index)
729 {this.allChildren(parent).splice(index,0,node);},removeChildByIndex:function(parent,index)
730 {this.allChildren(parent).splice(index,1);},removeAllChildren:function(parent)
731 {parent._allChildren=[];},removeTopLevelNodes:function()
732 {this._disposeAllNodes();this.rootNode().removeChildren();this.rootNode()._allChildren=[];},highlightNode:function(node)
733 {if(this._isScrolledIntoView(node.element)){this.updateVisibleNodes(true);WebInspector.HeapSnapshotSortableDataGrid.prototype.highlightNode.call(this,node);}else{node.element.scrollIntoViewIfNeeded(true);this._nodeToHighlightAfterScroll=node;}},_isScrolledIntoView:function(element)
734 {var viewportTop=this.scrollContainer.scrollTop;var viewportBottom=viewportTop+this.scrollContainer.clientHeight;var elemTop=element.offsetTop
735 var elemBottom=elemTop+element.offsetHeight;return elemBottom<=viewportBottom&&elemTop>=viewportTop;},onResize:function()
736 {WebInspector.HeapSnapshotSortableDataGrid.prototype.onResize.call(this);this.updateVisibleNodes(false);},_onScroll:function(event)
737 {this.updateVisibleNodes(false);if(this._nodeToHighlightAfterScroll){WebInspector.HeapSnapshotSortableDataGrid.prototype.highlightNode.call(this,this._nodeToHighlightAfterScroll);this._nodeToHighlightAfterScroll=null;}},__proto__:WebInspector.HeapSnapshotSortableDataGrid.prototype}
738 WebInspector.HeapSnapshotPaddingNode=function()
739 {this.element=document.createElement("tr");this.element.classList.add("revealed");}
740 WebInspector.HeapSnapshotPaddingNode.prototype={setHeight:function(height)
741 {this.element.style.height=height+"px";},removeFromTable:function()
742 {var parent=this.element.parentNode;if(parent)
743 parent.removeChild(this.element);}}
744 WebInspector.HeapSnapshotContainmentDataGrid=function(columns)
745 {columns=columns||[{id:"object",title:WebInspector.UIString("Object"),disclosure:true,sortable:true},{id:"distance",title:WebInspector.UIString("Distance"),width:"80px",sortable:true},{id:"shallowSize",title:WebInspector.UIString("Shallow Size"),width:"120px",sortable:true},{id:"retainedSize",title:WebInspector.UIString("Retained Size"),width:"120px",sortable:true,sort:WebInspector.DataGrid.Order.Descending}];WebInspector.HeapSnapshotSortableDataGrid.call(this,columns);}
746 WebInspector.HeapSnapshotContainmentDataGrid.prototype={setDataSource:function(snapshot,nodeIndex)
747 {this.snapshot=snapshot;var node={nodeIndex:nodeIndex||snapshot.rootNodeIndex};var fakeEdge={node:node};this.setRootNode(new WebInspector.HeapSnapshotObjectNode(this,snapshot,fakeEdge,null));this.rootNode().sort();},sortingChanged:function()
748 {var rootNode=this.rootNode();if(rootNode.hasChildren)
749 rootNode.sort();},__proto__:WebInspector.HeapSnapshotSortableDataGrid.prototype}
750 WebInspector.HeapSnapshotRetainmentDataGrid=function()
751 {this.showRetainingEdges=true;var columns=[{id:"object",title:WebInspector.UIString("Object"),disclosure:true,sortable:true},{id:"distance",title:WebInspector.UIString("Distance"),width:"80px",sortable:true,sort:WebInspector.DataGrid.Order.Ascending},{id:"shallowSize",title:WebInspector.UIString("Shallow Size"),width:"120px",sortable:true},{id:"retainedSize",title:WebInspector.UIString("Retained Size"),width:"120px",sortable:true}];WebInspector.HeapSnapshotContainmentDataGrid.call(this,columns);}
752 WebInspector.HeapSnapshotRetainmentDataGrid.Events={ExpandRetainersComplete:"ExpandRetainersComplete"}
753 WebInspector.HeapSnapshotRetainmentDataGrid.prototype={_sortFields:function(sortColumn,sortAscending)
754 {return{object:["_name",sortAscending,"_count",false],count:["_count",sortAscending,"_name",true],shallowSize:["_shallowSize",sortAscending,"_name",true],retainedSize:["_retainedSize",sortAscending,"_name",true],distance:["_distance",sortAscending,"_name",true]}[sortColumn];},reset:function()
755 {this.rootNode().removeChildren();this.resetSortingCache();},setDataSource:function(snapshot,nodeIndex)
756 {WebInspector.HeapSnapshotContainmentDataGrid.prototype.setDataSource.call(this,snapshot,nodeIndex);var dataGrid=this;var maxExpandLevels=20;function populateComplete()
757 {this.removeEventListener(WebInspector.HeapSnapshotGridNode.Events.PopulateComplete,populateComplete,this);this.expand();if(--maxExpandLevels>0&&this.children.length>0){var retainer=this.children[0];if(retainer._distance>1){retainer.addEventListener(WebInspector.HeapSnapshotGridNode.Events.PopulateComplete,populateComplete,retainer);retainer.populate();return;}}
758 dataGrid.dispatchEventToListeners(WebInspector.HeapSnapshotRetainmentDataGrid.Events.ExpandRetainersComplete);}
759 this.rootNode().addEventListener(WebInspector.HeapSnapshotGridNode.Events.PopulateComplete,populateComplete,this.rootNode());},__proto__:WebInspector.HeapSnapshotContainmentDataGrid.prototype}
760 WebInspector.HeapSnapshotConstructorsDataGrid=function()
761 {var columns=[{id:"object",title:WebInspector.UIString("Constructor"),disclosure:true,sortable:true},{id:"distance",title:WebInspector.UIString("Distance"),width:"90px",sortable:true},{id:"count",title:WebInspector.UIString("Objects Count"),width:"90px",sortable:true},{id:"shallowSize",title:WebInspector.UIString("Shallow Size"),width:"120px",sortable:true},{id:"retainedSize",title:WebInspector.UIString("Retained Size"),width:"120px",sort:WebInspector.DataGrid.Order.Descending,sortable:true}];WebInspector.HeapSnapshotViewportDataGrid.call(this,columns);this._profileIndex=-1;this._objectIdToSelect=null;}
762 WebInspector.HeapSnapshotConstructorsDataGrid.prototype={_sortFields:function(sortColumn,sortAscending)
763 {return{object:["_name",sortAscending,"_count",false],distance:["_distance",sortAscending,"_retainedSize",true],count:["_count",sortAscending,"_name",true],shallowSize:["_shallowSize",sortAscending,"_name",true],retainedSize:["_retainedSize",sortAscending,"_name",true]}[sortColumn];},highlightObjectByHeapSnapshotId:function(id,callback)
764 {if(!this.snapshot){this._objectIdToSelect=id;return;}
765 function didGetClassName(className)
766 {if(!className){callback(false);return;}
767 var constructorNodes=this.topLevelNodes();for(var i=0;i<constructorNodes.length;i++){var parent=constructorNodes[i];if(parent._name===className){parent.revealNodeBySnapshotObjectId(parseInt(id,10),callback);return;}}}
768 this.snapshot.nodeClassName(parseInt(id,10),didGetClassName.bind(this));},clear:function()
769 {this._nextRequestedFilter=null;this._lastFilter=null;this.removeTopLevelNodes();},setDataSource:function(snapshot)
770 {this.snapshot=snapshot;if(this._profileIndex===-1)
771 this._populateChildren();if(this._objectIdToSelect){this.highlightObjectByHeapSnapshotId(this._objectIdToSelect,function(found){});this._objectIdToSelect=null;}},setSelectionRange:function(minNodeId,maxNodeId)
772 {this._populateChildren(new WebInspector.HeapSnapshotCommon.NodeFilter(minNodeId,maxNodeId));},setAllocationNodeId:function(allocationNodeId)
773 {var filter=new WebInspector.HeapSnapshotCommon.NodeFilter();filter.allocationNodeId=allocationNodeId;this._populateChildren(filter);},_aggregatesReceived:function(nodeFilter,aggregates)
774 {this._filterInProgress=null;if(this._nextRequestedFilter){this.snapshot.aggregatesWithFilter(this._nextRequestedFilter,this._aggregatesReceived.bind(this,this._nextRequestedFilter));this._filterInProgress=this._nextRequestedFilter;this._nextRequestedFilter=null;}
775 this.removeTopLevelNodes();this.resetSortingCache();for(var constructor in aggregates)
776 this.appendNode(this.rootNode(),new WebInspector.HeapSnapshotConstructorNode(this,constructor,aggregates[constructor],nodeFilter));this.sortingChanged();this._lastFilter=nodeFilter;},_populateChildren:function(nodeFilter)
777 {nodeFilter=nodeFilter||new WebInspector.HeapSnapshotCommon.NodeFilter();if(this._filterInProgress){this._nextRequestedFilter=this._filterInProgress.equals(nodeFilter)?null:nodeFilter;return;}
778 if(this._lastFilter&&this._lastFilter.equals(nodeFilter))
779 return;this._filterInProgress=nodeFilter;this.snapshot.aggregatesWithFilter(nodeFilter,this._aggregatesReceived.bind(this,nodeFilter));},filterSelectIndexChanged:function(profiles,profileIndex)
780 {this._profileIndex=profileIndex;var nodeFilter;if(profileIndex!==-1){var minNodeId=profileIndex>0?profiles[profileIndex-1].maxJSObjectId:0;var maxNodeId=profiles[profileIndex].maxJSObjectId;nodeFilter=new WebInspector.HeapSnapshotCommon.NodeFilter(minNodeId,maxNodeId)}
781 this._populateChildren(nodeFilter);},__proto__:WebInspector.HeapSnapshotViewportDataGrid.prototype}
782 WebInspector.HeapSnapshotDiffDataGrid=function()
783 {var columns=[{id:"object",title:WebInspector.UIString("Constructor"),disclosure:true,sortable:true},{id:"addedCount",title:WebInspector.UIString("# New"),width:"72px",sortable:true},{id:"removedCount",title:WebInspector.UIString("# Deleted"),width:"72px",sortable:true},{id:"countDelta",title:WebInspector.UIString("# Delta"),width:"64px",sortable:true},{id:"addedSize",title:WebInspector.UIString("Alloc. Size"),width:"72px",sortable:true,sort:WebInspector.DataGrid.Order.Descending},{id:"removedSize",title:WebInspector.UIString("Freed Size"),width:"72px",sortable:true},{id:"sizeDelta",title:WebInspector.UIString("Size Delta"),width:"72px",sortable:true}];WebInspector.HeapSnapshotViewportDataGrid.call(this,columns);}
784 WebInspector.HeapSnapshotDiffDataGrid.prototype={defaultPopulateCount:function()
785 {return 50;},_sortFields:function(sortColumn,sortAscending)
786 {return{object:["_name",sortAscending,"_count",false],addedCount:["_addedCount",sortAscending,"_name",true],removedCount:["_removedCount",sortAscending,"_name",true],countDelta:["_countDelta",sortAscending,"_name",true],addedSize:["_addedSize",sortAscending,"_name",true],removedSize:["_removedSize",sortAscending,"_name",true],sizeDelta:["_sizeDelta",sortAscending,"_name",true]}[sortColumn];},setDataSource:function(snapshot)
787 {this.snapshot=snapshot;},setBaseDataSource:function(baseSnapshot)
788 {this.baseSnapshot=baseSnapshot;this.removeTopLevelNodes();this.resetSortingCache();if(this.baseSnapshot===this.snapshot){this.dispatchEventToListeners(WebInspector.HeapSnapshotSortableDataGrid.Events.SortingComplete);return;}
789 this._populateChildren();},_populateChildren:function()
790 {function aggregatesForDiffReceived(aggregatesForDiff)
791 {this.snapshot.calculateSnapshotDiff(this.baseSnapshot.uid,aggregatesForDiff,didCalculateSnapshotDiff.bind(this));function didCalculateSnapshotDiff(diffByClassName)
792 {for(var className in diffByClassName){var diff=diffByClassName[className];this.appendNode(this.rootNode(),new WebInspector.HeapSnapshotDiffNode(this,className,diff));}
793 this.sortingChanged();}}
794 this.baseSnapshot.aggregatesForDiff(aggregatesForDiffReceived.bind(this));},__proto__:WebInspector.HeapSnapshotViewportDataGrid.prototype}
795 WebInspector.HeapSnapshotDominatorsDataGrid=function()
796 {var columns=[{id:"object",title:WebInspector.UIString("Object"),disclosure:true,sortable:true},{id:"shallowSize",title:WebInspector.UIString("Shallow Size"),width:"120px",sortable:true},{id:"retainedSize",title:WebInspector.UIString("Retained Size"),width:"120px",sort:WebInspector.DataGrid.Order.Descending,sortable:true}];WebInspector.HeapSnapshotSortableDataGrid.call(this,columns);this._objectIdToSelect=null;}
797 WebInspector.HeapSnapshotDominatorsDataGrid.prototype={defaultPopulateCount:function()
798 {return 25;},setDataSource:function(snapshot)
799 {this.snapshot=snapshot;var fakeNode={nodeIndex:this.snapshot.rootNodeIndex};this.setRootNode(new WebInspector.HeapSnapshotDominatorObjectNode(this,fakeNode));this.rootNode().sort();if(this._objectIdToSelect){this.highlightObjectByHeapSnapshotId(this._objectIdToSelect,function(found){});this._objectIdToSelect=null;}},sortingChanged:function()
800 {this.rootNode().sort();},highlightObjectByHeapSnapshotId:function(id,callback)
801 {if(!this.snapshot){this._objectIdToSelect=id;callback(false);return;}
802 function didGetDominators(dominatorIds)
803 {if(!dominatorIds){WebInspector.console.log(WebInspector.UIString("Cannot find corresponding heap snapshot node"));callback(false);return;}
804 var dominatorNode=this.rootNode();expandNextDominator.call(this,dominatorIds,dominatorNode);}
805 function expandNextDominator(dominatorIds,dominatorNode)
806 {if(!dominatorNode){console.error("Cannot find dominator node");callback(false);return;}
807 if(!dominatorIds.length){this.highlightNode(dominatorNode);dominatorNode.element.scrollIntoViewIfNeeded(true);callback(true);return;}
808 var snapshotObjectId=dominatorIds.pop();dominatorNode.retrieveChildBySnapshotObjectId(snapshotObjectId,expandNextDominator.bind(this,dominatorIds));}
809 this.snapshot.dominatorIdsForNode(parseInt(id,10),didGetDominators.bind(this));},__proto__:WebInspector.HeapSnapshotSortableDataGrid.prototype}
810 WebInspector.AllocationDataGrid=function()
811 {var columns=[{id:"liveCount",title:WebInspector.UIString("Live Count"),width:"72px",sortable:true},{id:"count",title:WebInspector.UIString("Count"),width:"72px",sortable:true},{id:"liveSize",title:WebInspector.UIString("Live Size"),width:"72px",sortable:true},{id:"size",title:WebInspector.UIString("Size"),width:"72px",sortable:true,sort:WebInspector.DataGrid.Order.Descending},{id:"name",title:WebInspector.UIString("Function"),disclosure:true,sortable:true},];WebInspector.DataGrid.call(this,columns);this._linkifier=new WebInspector.Linkifier();this.addEventListener(WebInspector.DataGrid.Events.SortingChanged,this._sortingChanged,this);}
812 WebInspector.AllocationDataGrid.prototype={setDataSource:function(snapshot)
813 {this.snapshot=snapshot;this.snapshot.allocationTracesTops(didReceiveAllocationTracesTops.bind(this));function didReceiveAllocationTracesTops(tops)
814 {this._topNodes=tops;this._populateChildren();}},_populateChildren:function()
815 {var root=this.rootNode();var tops=this._topNodes;for(var i=0;i<tops.length;i++)
816 root.appendChild(new WebInspector.AllocationGridNode(this,tops[i]));},_sortingChanged:function()
817 {this._topNodes.sort(this._createComparator());this.rootNode().removeChildren();this._populateChildren();},_createComparator:function()
818 {var fieldName=this.sortColumnIdentifier();var compareResult=(this.sortOrder()===WebInspector.DataGrid.Order.Ascending)?+1:-1;function compare(a,b)
819 {if(a[fieldName]>b[fieldName])
820 return compareResult;if(a[fieldName]<b[fieldName])
821 return-compareResult;return 0;}
822 return compare;},__proto__:WebInspector.DataGrid.prototype};WebInspector.HeapSnapshotGridNode=function(tree,hasChildren)
823 {WebInspector.DataGridNode.call(this,null,hasChildren);this._dataGrid=tree;this._instanceCount=0;this._savedChildren=null;this._retrievedChildrenRanges=[];this._providerObject=null;}
824 WebInspector.HeapSnapshotGridNode.Events={PopulateComplete:"PopulateComplete"}
825 WebInspector.HeapSnapshotGridNode.createComparator=function(fieldNames)
826 {return({fieldName1:fieldNames[0],ascending1:fieldNames[1],fieldName2:fieldNames[2],ascending2:fieldNames[3]});}
827 WebInspector.HeapSnapshotGridNode.ChildrenProvider=function(){}
828 WebInspector.HeapSnapshotGridNode.ChildrenProvider.prototype={dispose:function(){},nodePosition:function(snapshotObjectId,callback){},isEmpty:function(callback){},serializeItemsRange:function(startPosition,endPosition,callback){},sortAndRewind:function(comparator,callback){}}
829 WebInspector.HeapSnapshotGridNode.prototype={createProvider:function()
830 {throw new Error("Not implemented.");},retainersDataSource:function()
831 {return null;},_provider:function()
832 {if(!this._providerObject)
833 this._providerObject=this.createProvider();return this._providerObject;},createCell:function(columnIdentifier)
834 {var cell=WebInspector.DataGridNode.prototype.createCell.call(this,columnIdentifier);if(this._searchMatched)
835 cell.classList.add("highlight");return cell;},collapse:function()
836 {WebInspector.DataGridNode.prototype.collapse.call(this);this._dataGrid.updateVisibleNodes(true);},expand:function()
837 {WebInspector.DataGridNode.prototype.expand.call(this);this._dataGrid.updateVisibleNodes(true);},dispose:function()
838 {if(this._providerObject)
839 this._providerObject.dispose();for(var node=this.children[0];node;node=node.traverseNextNode(true,this,true))
840 if(node.dispose)
841 node.dispose();},_reachableFromWindow:false,queryObjectContent:function(callback)
842 {},wasDetached:function()
843 {this._dataGrid.nodeWasDetached(this);},_toPercentString:function(num)
844 {return num.toFixed(0)+"\u2009%";},allChildren:function()
845 {return this._dataGrid.allChildren(this);},removeChildByIndex:function(index)
846 {this._dataGrid.removeChildByIndex(this,index);},childForPosition:function(nodePosition)
847 {var indexOfFirstChildInRange=0;for(var i=0;i<this._retrievedChildrenRanges.length;i++){var range=this._retrievedChildrenRanges[i];if(range.from<=nodePosition&&nodePosition<range.to){var childIndex=indexOfFirstChildInRange+nodePosition-range.from;return this.allChildren()[childIndex];}
848 indexOfFirstChildInRange+=range.to-range.from+1;}
849 return null;},_createValueCell:function(columnIdentifier)
850 {var cell=document.createElement("td");cell.className=columnIdentifier+"-column";if(this.dataGrid.snapshot.totalSize!==0){var div=document.createElement("div");var valueSpan=document.createElement("span");valueSpan.textContent=this.data[columnIdentifier];div.appendChild(valueSpan);var percentColumn=columnIdentifier+"-percent";if(percentColumn in this.data){var percentSpan=document.createElement("span");percentSpan.className="percent-column";percentSpan.textContent=this.data[percentColumn];div.appendChild(percentSpan);div.classList.add("heap-snapshot-multiple-values");}
851 cell.appendChild(div);}
852 return cell;},populate:function(event)
853 {if(this._populated)
854 return;this._populated=true;function sorted()
855 {this._populateChildren();}
856 this._provider().sortAndRewind(this.comparator(),sorted.bind(this));},expandWithoutPopulate:function(callback)
857 {this._populated=true;this.expand();this._provider().sortAndRewind(this.comparator(),callback);},_populateChildren:function(fromPosition,toPosition,afterPopulate)
858 {fromPosition=fromPosition||0;toPosition=toPosition||fromPosition+this._dataGrid.defaultPopulateCount();var firstNotSerializedPosition=fromPosition;function serializeNextChunk()
859 {if(firstNotSerializedPosition>=toPosition)
860 return;var end=Math.min(firstNotSerializedPosition+this._dataGrid.defaultPopulateCount(),toPosition);this._provider().serializeItemsRange(firstNotSerializedPosition,end,childrenRetrieved.bind(this));firstNotSerializedPosition=end;}
861 function insertRetrievedChild(item,insertionIndex)
862 {if(this._savedChildren){var hash=this._childHashForEntity(item);if(hash in this._savedChildren){this._dataGrid.insertChild(this,this._savedChildren[hash],insertionIndex);return;}}
863 this._dataGrid.insertChild(this,this._createChildNode(item),insertionIndex);}
864 function insertShowMoreButton(from,to,insertionIndex)
865 {var button=new WebInspector.ShowMoreDataGridNode(this._populateChildren.bind(this),from,to,this._dataGrid.defaultPopulateCount());this._dataGrid.insertChild(this,button,insertionIndex);}
866 function childrenRetrieved(itemsRange)
867 {var itemIndex=0;var itemPosition=itemsRange.startPosition;var items=itemsRange.items;var insertionIndex=0;if(!this._retrievedChildrenRanges.length){if(itemsRange.startPosition>0){this._retrievedChildrenRanges.push({from:0,to:0});insertShowMoreButton.call(this,0,itemsRange.startPosition,insertionIndex++);}
868 this._retrievedChildrenRanges.push({from:itemsRange.startPosition,to:itemsRange.endPosition});for(var i=0,l=items.length;i<l;++i)
869 insertRetrievedChild.call(this,items[i],insertionIndex++);if(itemsRange.endPosition<itemsRange.totalLength)
870 insertShowMoreButton.call(this,itemsRange.endPosition,itemsRange.totalLength,insertionIndex++);}else{var rangeIndex=0;var found=false;var range;while(rangeIndex<this._retrievedChildrenRanges.length){range=this._retrievedChildrenRanges[rangeIndex];if(range.to>=itemPosition){found=true;break;}
871 insertionIndex+=range.to-range.from;if(range.to<itemsRange.totalLength)
872 insertionIndex+=1;++rangeIndex;}
873 if(!found||itemsRange.startPosition<range.from){this.allChildren()[insertionIndex-1].setEndPosition(itemsRange.startPosition);insertShowMoreButton.call(this,itemsRange.startPosition,found?range.from:itemsRange.totalLength,insertionIndex);range={from:itemsRange.startPosition,to:itemsRange.startPosition};if(!found)
874 rangeIndex=this._retrievedChildrenRanges.length;this._retrievedChildrenRanges.splice(rangeIndex,0,range);}else{insertionIndex+=itemPosition-range.from;}
875 while(range.to<itemsRange.endPosition){var skipCount=range.to-itemPosition;insertionIndex+=skipCount;itemIndex+=skipCount;itemPosition=range.to;var nextRange=this._retrievedChildrenRanges[rangeIndex+1];var newEndOfRange=nextRange?nextRange.from:itemsRange.totalLength;if(newEndOfRange>itemsRange.endPosition)
876 newEndOfRange=itemsRange.endPosition;while(itemPosition<newEndOfRange){insertRetrievedChild.call(this,items[itemIndex++],insertionIndex++);++itemPosition;}
877 if(nextRange&&newEndOfRange===nextRange.from){range.to=nextRange.to;this.removeChildByIndex(insertionIndex);this._retrievedChildrenRanges.splice(rangeIndex+1,1);}else{range.to=newEndOfRange;if(newEndOfRange===itemsRange.totalLength)
878 this.removeChildByIndex(insertionIndex);else
879 this.allChildren()[insertionIndex].setStartPosition(itemsRange.endPosition);}}}
880 this._instanceCount+=items.length;if(firstNotSerializedPosition<toPosition){serializeNextChunk.call(this);return;}
881 if(this.expanded)
882 this._dataGrid.updateVisibleNodes(true);if(afterPopulate)
883 afterPopulate();this.dispatchEventToListeners(WebInspector.HeapSnapshotGridNode.Events.PopulateComplete);}
884 serializeNextChunk.call(this);},_saveChildren:function()
885 {this._savedChildren=null;var children=this.allChildren();for(var i=0,l=children.length;i<l;++i){var child=children[i];if(!child.expanded)
886 continue;if(!this._savedChildren)
887 this._savedChildren={};this._savedChildren[this._childHashForNode(child)]=child;}},sort:function()
888 {this._dataGrid.recursiveSortingEnter();function afterSort()
889 {this._saveChildren();this._dataGrid.removeAllChildren(this);this._retrievedChildrenRanges=[];function afterPopulate()
890 {var children=this.allChildren();for(var i=0,l=children.length;i<l;++i){var child=children[i];if(child.expanded)
891 child.sort();}
892 this._dataGrid.recursiveSortingLeave();}
893 var instanceCount=this._instanceCount;this._instanceCount=0;this._populateChildren(0,instanceCount,afterPopulate.bind(this));}
894 this._provider().sortAndRewind(this.comparator(),afterSort.bind(this));},__proto__:WebInspector.DataGridNode.prototype}
895 WebInspector.HeapSnapshotGenericObjectNode=function(dataGrid,node)
896 {WebInspector.HeapSnapshotGridNode.call(this,dataGrid,false);if(!node)
897 return;this._name=node.name;this._type=node.type;this._distance=node.distance;this._shallowSize=node.selfSize;this._retainedSize=node.retainedSize;this.snapshotNodeId=node.id;this.snapshotNodeIndex=node.nodeIndex;if(this._type==="string")
898 this._reachableFromWindow=true;else if(this._type==="object"&&this._name.startsWith("Window")){this._name=this.shortenWindowURL(this._name,false);this._reachableFromWindow=true;}else if(node.canBeQueried)
899 this._reachableFromWindow=true;if(node.detachedDOMTreeNode)
900 this.detachedDOMTreeNode=true;var snapshot=dataGrid.snapshot;var shallowSizePercent=this._shallowSize/snapshot.totalSize*100.0;var retainedSizePercent=this._retainedSize/snapshot.totalSize*100.0;this.data={"distance":this._distance,"shallowSize":Number.withThousandsSeparator(this._shallowSize),"retainedSize":Number.withThousandsSeparator(this._retainedSize),"shallowSize-percent":this._toPercentString(shallowSizePercent),"retainedSize-percent":this._toPercentString(retainedSizePercent)};};WebInspector.HeapSnapshotGenericObjectNode.prototype={retainersDataSource:function()
901 {return{snapshot:this._dataGrid.snapshot,snapshotNodeIndex:this.snapshotNodeIndex};},createCell:function(columnIdentifier)
902 {var cell=columnIdentifier!=="object"?this._createValueCell(columnIdentifier):this._createObjectCell();if(this._searchMatched)
903 cell.classList.add("highlight");return cell;},_createObjectCell:function()
904 {var value=this._name;var valueStyle="object";switch(this._type){case"concatenated string":case"string":value="\""+value+"\"";valueStyle="string";break;case"regexp":value="/"+value+"/";valueStyle="string";break;case"closure":value="function"+(value?" ":"")+value+"()";valueStyle="function";break;case"number":valueStyle="number";break;case"hidden":valueStyle="null";break;case"array":if(!value)
905 value="[]";else
906 value+="[]";break;};if(this._reachableFromWindow)
907 valueStyle+=" highlight";if(value==="Object")
908 value="";if(this.detachedDOMTreeNode)
909 valueStyle+=" detached-dom-tree-node";return this._createObjectCellWithValue(valueStyle,value);},_createObjectCellWithValue:function(valueStyle,value)
910 {var cell=document.createElement("td");cell.className="object-column";var div=document.createElement("div");div.className="source-code event-properties";div.style.overflow="visible";this._prefixObjectCell(div);var valueSpan=document.createElement("span");valueSpan.className="value console-formatted-"+valueStyle;valueSpan.textContent=value;div.appendChild(valueSpan);var idSpan=document.createElement("span");idSpan.className="console-formatted-id";idSpan.textContent=" @"+this.snapshotNodeId;div.appendChild(idSpan);cell.appendChild(div);cell.classList.add("disclosure");if(this.depth)
911 cell.style.setProperty("padding-left",(this.depth*this.dataGrid.indentWidth)+"px");cell.heapSnapshotNode=this;return cell;},_prefixObjectCell:function(div)
912 {},queryObjectContent:function(callback,objectGroupName)
913 {function formatResult(error,object)
914 {if(!error&&object.type)
915 callback(WebInspector.RemoteObject.fromPayload(object),!!error);else
916 callback(WebInspector.RemoteObject.fromPrimitiveValue(WebInspector.UIString("Preview is not available")));}
917 if(this._type==="string")
918 callback(WebInspector.RemoteObject.fromPrimitiveValue(this._name));else
919 HeapProfilerAgent.getObjectByHeapObjectId(String(this.snapshotNodeId),objectGroupName,formatResult);},updateHasChildren:function()
920 {function isEmptyCallback(isEmpty)
921 {this.hasChildren=!isEmpty;}
922 this._provider().isEmpty(isEmptyCallback.bind(this));},shortenWindowURL:function(fullName,hasObjectId)
923 {var startPos=fullName.indexOf("/");var endPos=hasObjectId?fullName.indexOf("@"):fullName.length;if(startPos!==-1&&endPos!==-1){var fullURL=fullName.substring(startPos+1,endPos).trimLeft();var url=fullURL.trimURL();if(url.length>40)
924 url=url.trimMiddle(40);return fullName.substr(0,startPos+2)+url+fullName.substr(endPos);}else
925 return fullName;},__proto__:WebInspector.HeapSnapshotGridNode.prototype}
926 WebInspector.HeapSnapshotObjectNode=function(dataGrid,snapshot,edge,parentGridNode)
927 {WebInspector.HeapSnapshotGenericObjectNode.call(this,dataGrid,edge.node);this._referenceName=edge.name;this._referenceType=edge.type;this.showRetainingEdges=dataGrid.showRetainingEdges;this._snapshot=snapshot;this._parentGridNode=parentGridNode;this._cycledWithAncestorGridNode=this._findAncestorWithSameSnapshotNodeId();if(!this._cycledWithAncestorGridNode)
928 this.updateHasChildren();var data=this.data;data["count"]="";data["addedCount"]="";data["removedCount"]="";data["countDelta"]="";data["addedSize"]="";data["removedSize"]="";data["sizeDelta"]="";}
929 WebInspector.HeapSnapshotObjectNode.prototype={retainersDataSource:function()
930 {return{snapshot:this._snapshot,snapshotNodeIndex:this.snapshotNodeIndex};},createProvider:function()
931 {var tree=this._dataGrid;if(this.showRetainingEdges)
932 return this._snapshot.createRetainingEdgesProvider(this.snapshotNodeIndex);else
933 return this._snapshot.createEdgesProvider(this.snapshotNodeIndex);},_findAncestorWithSameSnapshotNodeId:function()
934 {var ancestor=this._parentGridNode;while(ancestor){if(ancestor.snapshotNodeId===this.snapshotNodeId)
935 return ancestor;ancestor=ancestor._parentGridNode;}
936 return null;},_createChildNode:function(item)
937 {return new WebInspector.HeapSnapshotObjectNode(this._dataGrid,this._snapshot,item,this);},_childHashForEntity:function(edge)
938 {var prefix=this.showRetainingEdges?edge.node.id+"#":"";return prefix+edge.type+"#"+edge.name;},_childHashForNode:function(childNode)
939 {var prefix=this.showRetainingEdges?childNode.snapshotNodeId+"#":"";return prefix+childNode._referenceType+"#"+childNode._referenceName;},comparator:function()
940 {var sortAscending=this._dataGrid.isSortOrderAscending();var sortColumnIdentifier=this._dataGrid.sortColumnIdentifier();var sortFields={object:["!edgeName",sortAscending,"retainedSize",false],count:["!edgeName",true,"retainedSize",false],shallowSize:["selfSize",sortAscending,"!edgeName",true],retainedSize:["retainedSize",sortAscending,"!edgeName",true],distance:["distance",sortAscending,"_name",true]}[sortColumnIdentifier]||["!edgeName",true,"retainedSize",false];return WebInspector.HeapSnapshotGridNode.createComparator(sortFields);},_prefixObjectCell:function(div)
941 {var name=this._referenceName;if(name==="")name="(empty)";var nameClass="name";switch(this._referenceType){case"context":nameClass="console-formatted-number";break;case"internal":case"hidden":case"weak":nameClass="console-formatted-null";break;case"element":name="["+name+"]";break;}
942 if(this._cycledWithAncestorGridNode)
943 div.className+=" cycled-ancessor-node";var nameSpan=document.createElement("span");nameSpan.className=nameClass;nameSpan.textContent=name;div.appendChild(nameSpan);var separatorSpan=document.createElement("span");separatorSpan.className="grayed";separatorSpan.textContent=this.showRetainingEdges?" in ":" :: ";div.appendChild(separatorSpan);},__proto__:WebInspector.HeapSnapshotGenericObjectNode.prototype}
944 WebInspector.HeapSnapshotInstanceNode=function(dataGrid,snapshot,node,isDeletedNode)
945 {WebInspector.HeapSnapshotGenericObjectNode.call(this,dataGrid,node);this._baseSnapshotOrSnapshot=snapshot;this._isDeletedNode=isDeletedNode;this.updateHasChildren();var data=this.data;data["count"]="";data["countDelta"]="";data["sizeDelta"]="";if(this._isDeletedNode){data["addedCount"]="";data["addedSize"]="";data["removedCount"]="\u2022";data["removedSize"]=Number.withThousandsSeparator(this._shallowSize);}else{data["addedCount"]="\u2022";data["addedSize"]=Number.withThousandsSeparator(this._shallowSize);data["removedCount"]="";data["removedSize"]="";}};WebInspector.HeapSnapshotInstanceNode.prototype={retainersDataSource:function()
946 {return{snapshot:this._baseSnapshotOrSnapshot,snapshotNodeIndex:this.snapshotNodeIndex};},createProvider:function()
947 {return this._baseSnapshotOrSnapshot.createEdgesProvider(this.snapshotNodeIndex);},_createChildNode:function(item)
948 {return new WebInspector.HeapSnapshotObjectNode(this._dataGrid,this._baseSnapshotOrSnapshot,item,null);},_childHashForEntity:function(edge)
949 {return edge.type+"#"+edge.name;},_childHashForNode:function(childNode)
950 {return childNode._referenceType+"#"+childNode._referenceName;},comparator:function()
951 {var sortAscending=this._dataGrid.isSortOrderAscending();var sortColumnIdentifier=this._dataGrid.sortColumnIdentifier();var sortFields={object:["!edgeName",sortAscending,"retainedSize",false],distance:["distance",sortAscending,"retainedSize",false],count:["!edgeName",true,"retainedSize",false],addedSize:["selfSize",sortAscending,"!edgeName",true],removedSize:["selfSize",sortAscending,"!edgeName",true],shallowSize:["selfSize",sortAscending,"!edgeName",true],retainedSize:["retainedSize",sortAscending,"!edgeName",true]}[sortColumnIdentifier]||["!edgeName",true,"retainedSize",false];return WebInspector.HeapSnapshotGridNode.createComparator(sortFields);},__proto__:WebInspector.HeapSnapshotGenericObjectNode.prototype}
952 WebInspector.HeapSnapshotConstructorNode=function(dataGrid,className,aggregate,nodeFilter)
953 {WebInspector.HeapSnapshotGridNode.call(this,dataGrid,aggregate.count>0);this._name=className;this._nodeFilter=nodeFilter;this._distance=aggregate.distance;this._count=aggregate.count;this._shallowSize=aggregate.self;this._retainedSize=aggregate.maxRet;var snapshot=dataGrid.snapshot;var countPercent=this._count/snapshot.nodeCount*100.0;var retainedSizePercent=this._retainedSize/snapshot.totalSize*100.0;var shallowSizePercent=this._shallowSize/snapshot.totalSize*100.0;this.data={"object":className,"count":Number.withThousandsSeparator(this._count),"distance":this._distance,"shallowSize":Number.withThousandsSeparator(this._shallowSize),"retainedSize":Number.withThousandsSeparator(this._retainedSize),"count-percent":this._toPercentString(countPercent),"shallowSize-percent":this._toPercentString(shallowSizePercent),"retainedSize-percent":this._toPercentString(retainedSizePercent)};}
954 WebInspector.HeapSnapshotConstructorNode.prototype={createProvider:function()
955 {return this._dataGrid.snapshot.createNodesProviderForClass(this._name,this._nodeFilter)},revealNodeBySnapshotObjectId:function(snapshotObjectId,callback)
956 {function didExpand()
957 {this._provider().nodePosition(snapshotObjectId,didGetNodePosition.bind(this));}
958 function didGetNodePosition(nodePosition)
959 {if(nodePosition===-1){this.collapse();callback(false);}else{this._populateChildren(nodePosition,null,didPopulateChildren.bind(this,nodePosition));}}
960 function didPopulateChildren(nodePosition)
961 {var child=this.childForPosition(nodePosition);if(child){this._dataGrid.revealTreeNode([this,child]);this._dataGrid.highlightNode((child));}
962 callback(!!child);}
963 this._dataGrid.resetNameFilter(this.expandWithoutPopulate.bind(this,didExpand.bind(this)));},filteredOut:function()
964 {return this._name.toLowerCase().indexOf(this._dataGrid._nameFilter)===-1;},createCell:function(columnIdentifier)
965 {var cell=columnIdentifier!=="object"?this._createValueCell(columnIdentifier):WebInspector.HeapSnapshotGridNode.prototype.createCell.call(this,columnIdentifier);if(this._searchMatched)
966 cell.classList.add("highlight");return cell;},_createChildNode:function(item)
967 {return new WebInspector.HeapSnapshotInstanceNode(this._dataGrid,this._dataGrid.snapshot,item,false);},comparator:function()
968 {var sortAscending=this._dataGrid.isSortOrderAscending();var sortColumnIdentifier=this._dataGrid.sortColumnIdentifier();var sortFields={object:["id",sortAscending,"retainedSize",false],distance:["distance",sortAscending,"retainedSize",false],count:["id",true,"retainedSize",false],shallowSize:["selfSize",sortAscending,"id",true],retainedSize:["retainedSize",sortAscending,"id",true]}[sortColumnIdentifier];return WebInspector.HeapSnapshotGridNode.createComparator(sortFields);},_childHashForEntity:function(node)
969 {return node.id;},_childHashForNode:function(childNode)
970 {return childNode.snapshotNodeId;},__proto__:WebInspector.HeapSnapshotGridNode.prototype}
971 WebInspector.HeapSnapshotDiffNodesProvider=function(addedNodesProvider,deletedNodesProvider,addedCount,removedCount)
972 {this._addedNodesProvider=addedNodesProvider;this._deletedNodesProvider=deletedNodesProvider;this._addedCount=addedCount;this._removedCount=removedCount;}
973 WebInspector.HeapSnapshotDiffNodesProvider.prototype={dispose:function()
974 {this._addedNodesProvider.dispose();this._deletedNodesProvider.dispose();},nodePosition:function(snapshotObjectId,callback)
975 {throw new Error("Unreachable");},isEmpty:function(callback)
976 {callback(false);},serializeItemsRange:function(beginPosition,endPosition,callback)
977 {function didReceiveAllItems(items)
978 {items.totalLength=this._addedCount+this._removedCount;callback(items);}
979 function didReceiveDeletedItems(addedItems,itemsRange)
980 {var items=itemsRange.items;if(!addedItems.items.length)
981 addedItems.startPosition=this._addedCount+itemsRange.startPosition;for(var i=0;i<items.length;i++){items[i].isAddedNotRemoved=false;addedItems.items.push(items[i]);}
982 addedItems.endPosition=this._addedCount+itemsRange.endPosition;didReceiveAllItems.call(this,addedItems);}
983 function didReceiveAddedItems(itemsRange)
984 {var items=itemsRange.items;for(var i=0;i<items.length;i++)
985 items[i].isAddedNotRemoved=true;if(itemsRange.endPosition<endPosition)
986 return this._deletedNodesProvider.serializeItemsRange(0,endPosition-itemsRange.endPosition,didReceiveDeletedItems.bind(this,itemsRange));itemsRange.totalLength=this._addedCount+this._removedCount;didReceiveAllItems.call(this,itemsRange);}
987 if(beginPosition<this._addedCount){this._addedNodesProvider.serializeItemsRange(beginPosition,endPosition,didReceiveAddedItems.bind(this));}else{var emptyRange=new WebInspector.HeapSnapshotCommon.ItemsRange(0,0,0,[]);this._deletedNodesProvider.serializeItemsRange(beginPosition-this._addedCount,endPosition-this._addedCount,didReceiveDeletedItems.bind(this,emptyRange));}},sortAndRewind:function(comparator,callback)
988 {function afterSort()
989 {this._deletedNodesProvider.sortAndRewind(comparator,callback);}
990 this._addedNodesProvider.sortAndRewind(comparator,afterSort.bind(this));}};WebInspector.HeapSnapshotDiffNode=function(dataGrid,className,diffForClass)
991 {WebInspector.HeapSnapshotGridNode.call(this,dataGrid,true);this._name=className;this._addedCount=diffForClass.addedCount;this._removedCount=diffForClass.removedCount;this._countDelta=diffForClass.countDelta;this._addedSize=diffForClass.addedSize;this._removedSize=diffForClass.removedSize;this._sizeDelta=diffForClass.sizeDelta;this._deletedIndexes=diffForClass.deletedIndexes;this.data={"object":className,"addedCount":Number.withThousandsSeparator(this._addedCount),"removedCount":Number.withThousandsSeparator(this._removedCount),"countDelta":this._signForDelta(this._countDelta)+Number.withThousandsSeparator(Math.abs(this._countDelta)),"addedSize":Number.withThousandsSeparator(this._addedSize),"removedSize":Number.withThousandsSeparator(this._removedSize),"sizeDelta":this._signForDelta(this._sizeDelta)+Number.withThousandsSeparator(Math.abs(this._sizeDelta))};}
992 WebInspector.HeapSnapshotDiffNode.prototype={createProvider:function()
993 {var tree=this._dataGrid;return new WebInspector.HeapSnapshotDiffNodesProvider(tree.snapshot.createAddedNodesProvider(tree.baseSnapshot.uid,this._name),tree.baseSnapshot.createDeletedNodesProvider(this._deletedIndexes),this._addedCount,this._removedCount);},_createChildNode:function(item)
994 {if(item.isAddedNotRemoved)
995 return new WebInspector.HeapSnapshotInstanceNode(this._dataGrid,this._dataGrid.snapshot,item,false);else
996 return new WebInspector.HeapSnapshotInstanceNode(this._dataGrid,this._dataGrid.baseSnapshot,item,true);},_childHashForEntity:function(node)
997 {return node.id;},_childHashForNode:function(childNode)
998 {return childNode.snapshotNodeId;},comparator:function()
999 {var sortAscending=this._dataGrid.isSortOrderAscending();var sortColumnIdentifier=this._dataGrid.sortColumnIdentifier();var sortFields={object:["id",sortAscending,"selfSize",false],addedCount:["selfSize",sortAscending,"id",true],removedCount:["selfSize",sortAscending,"id",true],countDelta:["selfSize",sortAscending,"id",true],addedSize:["selfSize",sortAscending,"id",true],removedSize:["selfSize",sortAscending,"id",true],sizeDelta:["selfSize",sortAscending,"id",true]}[sortColumnIdentifier];return WebInspector.HeapSnapshotGridNode.createComparator(sortFields);},filteredOut:function()
1000 {return this._name.toLowerCase().indexOf(this._dataGrid._nameFilter)===-1;},_signForDelta:function(delta)
1001 {if(delta===0)
1002 return"";if(delta>0)
1003 return"+";else
1004 return"\u2212";},__proto__:WebInspector.HeapSnapshotGridNode.prototype}
1005 WebInspector.HeapSnapshotDominatorObjectNode=function(dataGrid,node)
1006 {WebInspector.HeapSnapshotGenericObjectNode.call(this,dataGrid,node);this.updateHasChildren();};WebInspector.HeapSnapshotDominatorObjectNode.prototype={createProvider:function()
1007 {return this._dataGrid.snapshot.createNodesProviderForDominator(this.snapshotNodeIndex);},retrieveChildBySnapshotObjectId:function(snapshotObjectId,callback)
1008 {function didExpand()
1009 {this._provider().nodePosition(snapshotObjectId,didGetNodePosition.bind(this));}
1010 function didGetNodePosition(nodePosition)
1011 {if(nodePosition===-1){this.collapse();callback(null);}else
1012 this._populateChildren(nodePosition,null,didPopulateChildren.bind(this,nodePosition));}
1013 function didPopulateChildren(nodePosition)
1014 {var child=this.childForPosition(nodePosition);callback(child);}
1015 this.hasChildren=true;this.expandWithoutPopulate(didExpand.bind(this));},_createChildNode:function(item)
1016 {return new WebInspector.HeapSnapshotDominatorObjectNode(this._dataGrid,item);},_childHashForEntity:function(node)
1017 {return node.id;},_childHashForNode:function(childNode)
1018 {return childNode.snapshotNodeId;},comparator:function()
1019 {var sortAscending=this._dataGrid.isSortOrderAscending();var sortColumnIdentifier=this._dataGrid.sortColumnIdentifier();var sortFields={object:["id",sortAscending,"retainedSize",false],shallowSize:["selfSize",sortAscending,"id",true],retainedSize:["retainedSize",sortAscending,"id",true]}[sortColumnIdentifier];return WebInspector.HeapSnapshotGridNode.createComparator(sortFields);},__proto__:WebInspector.HeapSnapshotGenericObjectNode.prototype}
1020 WebInspector.AllocationGridNode=function(dataGrid,data)
1021 {WebInspector.DataGridNode.call(this,data,data.hasChildren);this._dataGrid=dataGrid;this._populated=false;}
1022 WebInspector.AllocationGridNode.prototype={populate:function()
1023 {if(this._populated)
1024 return;this._populated=true;this._dataGrid.snapshot.allocationNodeCallers(this.data.id,didReceiveCallers.bind(this));function didReceiveCallers(callers)
1025 {var callersChain=callers.nodesWithSingleCaller;var parentNode=this;for(var i=0;i<callersChain.length;i++){var child=new WebInspector.AllocationGridNode(this._dataGrid,callersChain[i]);parentNode.appendChild(child);parentNode=child;parentNode._populated=true;if(this.expanded)
1026 parentNode.expand();}
1027 var callersBranch=callers.branchingCallers;callersBranch.sort(this._dataGrid._createComparator());for(var i=0;i<callersBranch.length;i++)
1028 parentNode.appendChild(new WebInspector.AllocationGridNode(this._dataGrid,callersBranch[i]));}},expand:function()
1029 {WebInspector.DataGridNode.prototype.expand.call(this);if(this.children.length===1)
1030 this.children[0].expand();},createCell:function(columnIdentifier)
1031 {var cell=WebInspector.DataGridNode.prototype.createCell.call(this,columnIdentifier);if(columnIdentifier!=="name")
1032 return cell;var functionInfo=this.data;if(functionInfo.scriptName){var urlElement=this._dataGrid._linkifier.linkifyLocation(functionInfo.scriptName,functionInfo.line-1,functionInfo.column-1,"profile-node-file");urlElement.style.maxWidth="75%";cell.insertBefore(urlElement,cell.firstChild);}
1033 return cell;},allocationNodeId:function()
1034 {return this.data.id;},__proto__:WebInspector.DataGridNode.prototype};WebInspector.HeapSnapshotView=function(profile)
1035 {WebInspector.VBox.call(this);this.element.classList.add("heap-snapshot-view");profile.profileType().addEventListener(WebInspector.HeapSnapshotProfileType.SnapshotReceived,this._onReceiveSnapshot,this);profile.profileType().addEventListener(WebInspector.ProfileType.Events.RemoveProfileHeader,this._onProfileHeaderRemoved,this);if(profile._profileType.id===WebInspector.TrackingHeapSnapshotProfileType.TypeId){this._trackingOverviewGrid=new WebInspector.HeapTrackingOverviewGrid(profile);this._trackingOverviewGrid.addEventListener(WebInspector.HeapTrackingOverviewGrid.IdsRangeChanged,this._onIdsRangeChanged.bind(this));}
1036 this._splitView=new WebInspector.SplitView(false,true,"heapSnapshotSplitViewState",200,200);this._splitView.show(this.element);this._containmentView=new WebInspector.VBox();this._containmentView.setMinimumSize(50,25);this._containmentDataGrid=new WebInspector.HeapSnapshotContainmentDataGrid();this._containmentDataGrid.show(this._containmentView.element);this._containmentDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._selectionChanged,this);this._statisticsView=new WebInspector.HeapSnapshotStatisticsView();this._constructorsView=new WebInspector.VBox();this._constructorsView.setMinimumSize(50,25);this._constructorsDataGrid=new WebInspector.HeapSnapshotConstructorsDataGrid();this._constructorsDataGrid.show(this._constructorsView.element);this._constructorsDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._selectionChanged,this);this._diffView=new WebInspector.VBox();this._diffView.setMinimumSize(50,25);this._diffDataGrid=new WebInspector.HeapSnapshotDiffDataGrid();this._diffDataGrid.show(this._diffView.element);this._diffDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._selectionChanged,this);this._dominatorView=new WebInspector.VBox();this._dominatorView.setMinimumSize(50,25);this._dominatorDataGrid=new WebInspector.HeapSnapshotDominatorsDataGrid();this._dominatorDataGrid.show(this._dominatorView.element);this._dominatorDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._selectionChanged,this);if(WebInspector.experimentsSettings.allocationProfiler.isEnabled()&&profile.profileType()===WebInspector.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType){this._allocationView=new WebInspector.VBox();this._allocationView.setMinimumSize(50,25);this._allocationDataGrid=new WebInspector.AllocationDataGrid();this._allocationDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._onSelectAllocationNode,this);this._allocationDataGrid.show(this._allocationView.element);}
1037 this._retainmentViewHeader=document.createElementWithClass("div","retainers-view-header");var retainingPathsTitleDiv=this._retainmentViewHeader.createChild("div","title");var retainingPathsTitle=retainingPathsTitleDiv.createChild("span");retainingPathsTitle.textContent=WebInspector.UIString("Object's retaining tree");this._splitView.hideDefaultResizer();this._splitView.installResizer(this._retainmentViewHeader);this._retainmentView=new WebInspector.VBox();this._retainmentView.setMinimumSize(50,21);this._retainmentView.element.classList.add("retaining-paths-view");this._retainmentView.element.appendChild(this._retainmentViewHeader);this._retainmentDataGrid=new WebInspector.HeapSnapshotRetainmentDataGrid();this._retainmentDataGrid.show(this._retainmentView.element);this._retainmentDataGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._inspectedObjectChanged,this);this._retainmentDataGrid.reset();this._perspectives=[];this._perspectives.push(new WebInspector.HeapSnapshotView.SummaryPerspective());if(profile.profileType()!==WebInspector.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType)
1038 this._perspectives.push(new WebInspector.HeapSnapshotView.ComparisonPerspective());this._perspectives.push(new WebInspector.HeapSnapshotView.ContainmentPerspective());if(WebInspector.settings.showAdvancedHeapSnapshotProperties.get())
1039 this._perspectives.push(new WebInspector.HeapSnapshotView.DominatorPerspective());if(this._allocationView)
1040 this._perspectives.push(new WebInspector.HeapSnapshotView.AllocationPerspective());if(WebInspector.experimentsSettings.heapSnapshotStatistics.isEnabled())
1041 this._perspectives.push(new WebInspector.HeapSnapshotView.StatisticsPerspective());this._perspectiveSelect=new WebInspector.StatusBarComboBox(this._onSelectedPerspectiveChanged.bind(this));for(var i=0;i<this._perspectives.length;++i)
1042 this._perspectiveSelect.createOption(this._perspectives[i].title());this._profile=profile;this._baseSelect=new WebInspector.StatusBarComboBox(this._changeBase.bind(this));this._baseSelect.visible=false;this._updateBaseOptions();this._filterSelect=new WebInspector.StatusBarComboBox(this._changeFilter.bind(this));this._filterSelect.visible=false;this._updateFilterOptions();this._classNameFilter=new WebInspector.StatusBarInput("Class filter");this._classNameFilter.visible=false;this._classNameFilter.setOnChangeHandler(this._onClassFilterChanged.bind(this));this._selectedSizeText=new WebInspector.StatusBarText("");this._popoverHelper=new WebInspector.ObjectPopoverHelper(this.element,this._getHoverAnchor.bind(this),this._resolveObjectForPopover.bind(this),undefined,true);this._currentPerspectiveIndex=0;this._currentPerspective=this._perspectives[0];this._currentPerspective.activate(this);this._dataGrid=this._currentPerspective.masterGrid(this);this._dataGrid.addEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ResetFilter,this._onResetClassNameFilter,this);this._refreshView();}
1043 WebInspector.HeapSnapshotView.Perspective=function(title)
1044 {this._title=title;}
1045 WebInspector.HeapSnapshotView.Perspective.prototype={activate:function(heapSnapshotView){},deactivate:function(heapSnapshotView)
1046 {heapSnapshotView._baseSelect.visible=false;heapSnapshotView._filterSelect.visible=false;heapSnapshotView._classNameFilter.visible=false;if(heapSnapshotView._trackingOverviewGrid)
1047 heapSnapshotView._trackingOverviewGrid.detach();if(heapSnapshotView._allocationView)
1048 heapSnapshotView._allocationView.detach();if(heapSnapshotView._statisticsView)
1049 heapSnapshotView._statisticsView.detach();heapSnapshotView._splitView.detach();heapSnapshotView._splitView.detachChildViews();},masterGrid:function(heapSnapshotView)
1050 {return null;},title:function()
1051 {return this._title;},supportsSearch:function()
1052 {return false;}}
1053 WebInspector.HeapSnapshotView.SummaryPerspective=function()
1054 {WebInspector.HeapSnapshotView.Perspective.call(this,WebInspector.UIString("Summary"));}
1055 WebInspector.HeapSnapshotView.SummaryPerspective.prototype={activate:function(heapSnapshotView)
1056 {heapSnapshotView._constructorsView.show(heapSnapshotView._splitView.mainElement());heapSnapshotView._retainmentView.show(heapSnapshotView._splitView.sidebarElement());heapSnapshotView._splitView.show(heapSnapshotView.element);heapSnapshotView._filterSelect.visible=true;heapSnapshotView._classNameFilter.visible=true;if(heapSnapshotView._trackingOverviewGrid){heapSnapshotView._trackingOverviewGrid.show(heapSnapshotView.element,heapSnapshotView._splitView.element);heapSnapshotView._trackingOverviewGrid.update();heapSnapshotView._trackingOverviewGrid._updateGrid();}},masterGrid:function(heapSnapshotView)
1057 {return heapSnapshotView._constructorsDataGrid;},supportsSearch:function()
1058 {return true;},__proto__:WebInspector.HeapSnapshotView.Perspective.prototype}
1059 WebInspector.HeapSnapshotView.ComparisonPerspective=function()
1060 {WebInspector.HeapSnapshotView.Perspective.call(this,WebInspector.UIString("Comparison"));}
1061 WebInspector.HeapSnapshotView.ComparisonPerspective.prototype={activate:function(heapSnapshotView)
1062 {heapSnapshotView._diffView.show(heapSnapshotView._splitView.mainElement());heapSnapshotView._retainmentView.show(heapSnapshotView._splitView.sidebarElement());heapSnapshotView._splitView.show(heapSnapshotView.element);heapSnapshotView._baseSelect.visible=true;heapSnapshotView._classNameFilter.visible=true;},masterGrid:function(heapSnapshotView)
1063 {return heapSnapshotView._diffDataGrid;},supportsSearch:function()
1064 {return true;},__proto__:WebInspector.HeapSnapshotView.Perspective.prototype}
1065 WebInspector.HeapSnapshotView.ContainmentPerspective=function()
1066 {WebInspector.HeapSnapshotView.Perspective.call(this,WebInspector.UIString("Containment"));}
1067 WebInspector.HeapSnapshotView.ContainmentPerspective.prototype={activate:function(heapSnapshotView)
1068 {heapSnapshotView._containmentView.show(heapSnapshotView._splitView.mainElement());heapSnapshotView._retainmentView.show(heapSnapshotView._splitView.sidebarElement());heapSnapshotView._splitView.show(heapSnapshotView.element);},masterGrid:function(heapSnapshotView)
1069 {return heapSnapshotView._containmentDataGrid;},__proto__:WebInspector.HeapSnapshotView.Perspective.prototype}
1070 WebInspector.HeapSnapshotView.DominatorPerspective=function()
1071 {WebInspector.HeapSnapshotView.Perspective.call(this,WebInspector.UIString("Dominators"));}
1072 WebInspector.HeapSnapshotView.DominatorPerspective.prototype={activate:function(heapSnapshotView)
1073 {heapSnapshotView._dominatorView.show(heapSnapshotView._splitView.mainElement());heapSnapshotView._retainmentView.show(heapSnapshotView._splitView.sidebarElement());heapSnapshotView._splitView.show(heapSnapshotView.element);},masterGrid:function(heapSnapshotView)
1074 {return heapSnapshotView._dominatorDataGrid;},__proto__:WebInspector.HeapSnapshotView.Perspective.prototype}
1075 WebInspector.HeapSnapshotView.AllocationPerspective=function()
1076 {WebInspector.HeapSnapshotView.Perspective.call(this,WebInspector.UIString("Allocation"));this._allocationSplitView=new WebInspector.SplitView(false,true,"heapSnapshotAllocationSplitViewState",200,200);}
1077 WebInspector.HeapSnapshotView.AllocationPerspective.prototype={activate:function(heapSnapshotView)
1078 {heapSnapshotView._allocationView.show(this._allocationSplitView.mainElement());heapSnapshotView._constructorsView.show(heapSnapshotView._splitView.mainElement());heapSnapshotView._retainmentView.show(heapSnapshotView._splitView.sidebarElement());heapSnapshotView._splitView.show(this._allocationSplitView.sidebarElement());this._allocationSplitView.show(heapSnapshotView.element);heapSnapshotView._constructorsDataGrid.clear();var selectedNode=heapSnapshotView._allocationDataGrid.selectedNode;if(selectedNode)
1079 heapSnapshotView._constructorsDataGrid.setAllocationNodeId(selectedNode.allocationNodeId());},deactivate:function(heapSnapshotView)
1080 {this._allocationSplitView.detach();WebInspector.HeapSnapshotView.Perspective.prototype.deactivate.call(this,heapSnapshotView);},masterGrid:function(heapSnapshotView)
1081 {return heapSnapshotView._allocationDataGrid;},__proto__:WebInspector.HeapSnapshotView.Perspective.prototype}
1082 WebInspector.HeapSnapshotView.StatisticsPerspective=function()
1083 {WebInspector.HeapSnapshotView.Perspective.call(this,WebInspector.UIString("Statistics"));}
1084 WebInspector.HeapSnapshotView.StatisticsPerspective.prototype={activate:function(heapSnapshotView)
1085 {heapSnapshotView._statisticsView.show(heapSnapshotView.element);},masterGrid:function(heapSnapshotView)
1086 {return null;},__proto__:WebInspector.HeapSnapshotView.Perspective.prototype}
1087 WebInspector.HeapSnapshotView.prototype={_refreshView:function()
1088 {this._profile.load(profileCallback.bind(this));function profileCallback(heapSnapshotProxy)
1089 {heapSnapshotProxy.getStatistics(this._gotStatistics.bind(this));var list=this._profiles();var profileIndex=list.indexOf(this._profile);this._baseSelect.setSelectedIndex(Math.max(0,profileIndex-1));this._dataGrid.setDataSource(heapSnapshotProxy);if(this._trackingOverviewGrid)
1090 this._trackingOverviewGrid._updateGrid();}},_gotStatistics:function(statistics){this._statisticsView.setTotal(statistics.total);this._statisticsView.addRecord(statistics.code,WebInspector.UIString("Code"),"#f77");this._statisticsView.addRecord(statistics.strings,WebInspector.UIString("Strings"),"#5e5");this._statisticsView.addRecord(statistics.jsArrays,WebInspector.UIString("JS Arrays"),"#7af");this._statisticsView.addRecord(statistics.native,WebInspector.UIString("Typed Arrays"),"#fc5");this._statisticsView.addRecord(statistics.total,WebInspector.UIString("Total"));},_onIdsRangeChanged:function(event)
1091 {var minId=event.data.minId;var maxId=event.data.maxId;this._selectedSizeText.setText(WebInspector.UIString("Selected size: %s",Number.bytesToString(event.data.size)));if(this._constructorsDataGrid.snapshot)
1092 this._constructorsDataGrid.setSelectionRange(minId,maxId);},get statusBarItems()
1093 {var result=[this._perspectiveSelect.element,this._classNameFilter.element];if(this._profile.profileType()!==WebInspector.ProfileTypeRegistry.instance.trackingHeapSnapshotProfileType)
1094 result.push(this._baseSelect.element,this._filterSelect.element);result.push(this._selectedSizeText.element);return result;},wasShown:function()
1095 {this._profile.load(profileCallback.bind(this));function profileCallback(){this._profile._wasShown();if(this._baseProfile)
1096 this._baseProfile.load(function(){});}},willHide:function()
1097 {this._currentSearchResultIndex=-1;this._popoverHelper.hidePopover();if(this.helpPopover&&this.helpPopover.isShowing())
1098 this.helpPopover.hide();},searchCanceled:function()
1099 {if(this._searchResults){for(var i=0;i<this._searchResults.length;++i){var node=this._searchResults[i].node;delete node._searchMatched;node.refresh();}}
1100 delete this._searchFinishedCallback;this._currentSearchResultIndex=-1;this._searchResults=[];},performSearch:function(query,finishedCallback)
1101 {this.searchCanceled();query=query.trim();if(!query)
1102 return;if(!this._currentPerspective.supportsSearch())
1103 return;function didHighlight(found)
1104 {finishedCallback(this,found?1:0);}
1105 if(query.charAt(0)==="@"){var snapshotNodeId=parseInt(query.substring(1),10);if(!isNaN(snapshotNodeId))
1106 this._dataGrid.highlightObjectByHeapSnapshotId(String(snapshotNodeId),didHighlight.bind(this));else
1107 finishedCallback(this,0);return;}
1108 this._searchFinishedCallback=finishedCallback;var nameRegExp=createPlainTextSearchRegex(query,"i");function matchesByName(gridNode){return("_name"in gridNode)&&nameRegExp.test(gridNode._name);}
1109 function matchesQuery(gridNode)
1110 {delete gridNode._searchMatched;if(matchesByName(gridNode)){gridNode._searchMatched=true;gridNode.refresh();return true;}
1111 return false;}
1112 var current=this._dataGrid.rootNode().children[0];var depth=0;var info={};const maxDepth=1;while(current){if(matchesQuery(current))
1113 this._searchResults.push({node:current});current=current.traverseNextNode(false,null,(depth>=maxDepth),info);depth+=info.depthChange;}
1114 finishedCallback(this,this._searchResults.length);},jumpToFirstSearchResult:function()
1115 {if(!this._searchResults||!this._searchResults.length)
1116 return;this._currentSearchResultIndex=0;this._jumpToSearchResult(this._currentSearchResultIndex);},jumpToLastSearchResult:function()
1117 {if(!this._searchResults||!this._searchResults.length)
1118 return;this._currentSearchResultIndex=(this._searchResults.length-1);this._jumpToSearchResult(this._currentSearchResultIndex);},jumpToNextSearchResult:function()
1119 {if(!this._searchResults||!this._searchResults.length)
1120 return;if(++this._currentSearchResultIndex>=this._searchResults.length)
1121 this._currentSearchResultIndex=0;this._jumpToSearchResult(this._currentSearchResultIndex);},jumpToPreviousSearchResult:function()
1122 {if(!this._searchResults||!this._searchResults.length)
1123 return;if(--this._currentSearchResultIndex<0)
1124 this._currentSearchResultIndex=(this._searchResults.length-1);this._jumpToSearchResult(this._currentSearchResultIndex);},showingFirstSearchResult:function()
1125 {return(this._currentSearchResultIndex===0);},showingLastSearchResult:function()
1126 {return(this._searchResults&&this._currentSearchResultIndex===(this._searchResults.length-1));},currentSearchResultIndex:function(){return this._currentSearchResultIndex;},_jumpToSearchResult:function(index)
1127 {var searchResult=this._searchResults[index];if(!searchResult)
1128 return;var node=searchResult.node;node.revealAndSelect();},refreshVisibleData:function()
1129 {if(!this._dataGrid)
1130 return;var child=this._dataGrid.rootNode().children[0];while(child){child.refresh();child=child.traverseNextNode(false,null,true);}},_changeBase:function()
1131 {if(this._baseProfile===this._profiles()[this._baseSelect.selectedIndex()])
1132 return;this._baseProfile=this._profiles()[this._baseSelect.selectedIndex()];var dataGrid=(this._dataGrid);if(dataGrid.snapshot)
1133 this._baseProfile.load(dataGrid.setBaseDataSource.bind(dataGrid));if(!this.currentQuery||!this._searchFinishedCallback||!this._searchResults)
1134 return;this._searchFinishedCallback(this,-this._searchResults.length);this.performSearch(this.currentQuery,this._searchFinishedCallback);},_changeFilter:function()
1135 {var profileIndex=this._filterSelect.selectedIndex()-1;this._dataGrid.filterSelectIndexChanged(this._profiles(),profileIndex);WebInspector.notifications.dispatchEventToListeners(WebInspector.UserMetrics.UserAction,{action:WebInspector.UserMetrics.UserActionNames.HeapSnapshotFilterChanged,label:this._filterSelect.selectedOption().label});if(!this.currentQuery||!this._searchFinishedCallback||!this._searchResults)
1136 return;this._searchFinishedCallback(this,-this._searchResults.length);this.performSearch(this.currentQuery,this._searchFinishedCallback);},_onClassFilterChanged:function(value)
1137 {this._dataGrid.changeNameFilter(value);},_onResetClassNameFilter:function()
1138 {this._classNameFilter.setValue("");},_profiles:function()
1139 {return this._profile.profileType().getProfiles();},populateContextMenu:function(contextMenu,event)
1140 {if(this._dataGrid)
1141 this._dataGrid.populateContextMenu(contextMenu,event);},_selectionChanged:function(event)
1142 {var selectedNode=event.target.selectedNode;this._setRetainmentDataGridSource(selectedNode);this._inspectedObjectChanged(event);},_onSelectAllocationNode:function(event)
1143 {var selectedNode=event.target.selectedNode;this._constructorsDataGrid.setAllocationNodeId(selectedNode.allocationNodeId());},_inspectedObjectChanged:function(event)
1144 {var selectedNode=event.target.selectedNode;if(!this._profile.fromFile()&&selectedNode instanceof WebInspector.HeapSnapshotGenericObjectNode)
1145 ConsoleAgent.addInspectedHeapObject(selectedNode.snapshotNodeId);},_setRetainmentDataGridSource:function(nodeItem)
1146 {var dataSource=nodeItem&&nodeItem.retainersDataSource();if(dataSource)
1147 this._retainmentDataGrid.setDataSource(dataSource.snapshot,dataSource.snapshotNodeIndex);else
1148 this._retainmentDataGrid.reset();},_changePerspectiveAndWait:function(perspectiveTitle,callback)
1149 {var perspectiveIndex=null;for(var i=0;i<this._perspectives.length;++i){if(this._perspectives[i].title()===perspectiveTitle){perspectiveIndex=i;break;}}
1150 if(this._currentPerspectiveIndex===perspectiveIndex||perspectiveIndex===null){setTimeout(callback,0);return;}
1151 function dataGridContentShown(event)
1152 {var dataGrid=event.data;dataGrid.removeEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown,dataGridContentShown,this);if(dataGrid===this._dataGrid)
1153 callback();}
1154 this._perspectives[perspectiveIndex].masterGrid(this).addEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ContentShown,dataGridContentShown,this);this._perspectiveSelect.setSelectedIndex(perspectiveIndex);this._changePerspective(perspectiveIndex);},_updateDataSourceAndView:function()
1155 {var dataGrid=this._dataGrid;if(!dataGrid||dataGrid.snapshot)
1156 return;this._profile.load(didLoadSnapshot.bind(this));function didLoadSnapshot(snapshotProxy)
1157 {if(this._dataGrid!==dataGrid)
1158 return;if(dataGrid.snapshot!==snapshotProxy)
1159 dataGrid.setDataSource(snapshotProxy);if(dataGrid===this._diffDataGrid){if(!this._baseProfile)
1160 this._baseProfile=this._profiles()[this._baseSelect.selectedIndex()];this._baseProfile.load(didLoadBaseSnaphot.bind(this));}}
1161 function didLoadBaseSnaphot(baseSnapshotProxy)
1162 {if(this._diffDataGrid.baseSnapshot!==baseSnapshotProxy)
1163 this._diffDataGrid.setBaseDataSource(baseSnapshotProxy);}},_onSelectedPerspectiveChanged:function(event)
1164 {this._changePerspective(event.target.selectedIndex);this._onSelectedViewChanged(event);},_onSelectedViewChanged:function(event)
1165 {},_changePerspective:function(selectedIndex)
1166 {if(selectedIndex===this._currentPerspectiveIndex)
1167 return;if(this._dataGrid)
1168 this._dataGrid.removeEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ResetFilter,this._onResetClassNameFilter,this);this._currentPerspectiveIndex=selectedIndex;this._currentPerspective.deactivate(this);var perspective=this._perspectives[selectedIndex];this._currentPerspective=perspective;this._dataGrid=perspective.masterGrid(this);perspective.activate(this);this.refreshVisibleData();if(this._dataGrid){this._dataGrid.addEventListener(WebInspector.HeapSnapshotSortableDataGrid.Events.ResetFilter,this._onResetClassNameFilter,this);this._dataGrid.updateWidths();}
1169 this._updateDataSourceAndView();if(!this.currentQuery||!this._searchFinishedCallback||!this._searchResults)
1170 return;this._searchFinishedCallback(this,-this._searchResults.length);this.performSearch(this.currentQuery,this._searchFinishedCallback);},highlightLiveObject:function(perspectiveName,snapshotObjectId)
1171 {this._changePerspectiveAndWait(perspectiveName,didChangePerspective.bind(this));function didChangePerspective()
1172 {this._dataGrid.highlightObjectByHeapSnapshotId(snapshotObjectId,didHighlightObject);}
1173 function didHighlightObject(found)
1174 {if(!found)
1175 WebInspector.console.log("Cannot find corresponding heap snapshot node",WebInspector.ConsoleMessage.MessageLevel.Error,true);}},_getHoverAnchor:function(target)
1176 {var span=target.enclosingNodeOrSelfWithNodeName("span");if(!span)
1177 return;var row=target.enclosingNodeOrSelfWithNodeName("tr");if(!row)
1178 return;span.node=row._dataGridNode;return span;},_resolveObjectForPopover:function(element,showCallback,objectGroupName)
1179 {if(this._profile.fromFile())
1180 return;element.node.queryObjectContent(showCallback,objectGroupName);},_updateBaseOptions:function()
1181 {var list=this._profiles();if(this._baseSelect.size()===list.length)
1182 return;for(var i=this._baseSelect.size(),n=list.length;i<n;++i){var title=list[i].title;this._baseSelect.createOption(title);}},_updateFilterOptions:function()
1183 {var list=this._profiles();if(this._filterSelect.size()-1===list.length)
1184 return;if(!this._filterSelect.size())
1185 this._filterSelect.createOption(WebInspector.UIString("All objects"));for(var i=this._filterSelect.size()-1,n=list.length;i<n;++i){var title=list[i].title;if(!i)
1186 title=WebInspector.UIString("Objects allocated before %s",title);else
1187 title=WebInspector.UIString("Objects allocated between %s and %s",list[i-1].title,title);this._filterSelect.createOption(title);}},_updateControls:function()
1188 {this._updateBaseOptions();this._updateFilterOptions();},_onReceiveSnapshot:function(event)
1189 {this._updateControls();},_onProfileHeaderRemoved:function(event)
1190 {var profile=event.data;if(this._profile===profile){this.detach();this._profile.profileType().removeEventListener(WebInspector.HeapSnapshotProfileType.SnapshotReceived,this._onReceiveSnapshot,this);this._profile.profileType().removeEventListener(WebInspector.ProfileType.Events.RemoveProfileHeader,this._onProfileHeaderRemoved,this);}else{this._updateControls();}},__proto__:WebInspector.VBox.prototype}
1191 WebInspector.HeapProfilerDispatcher=function()
1192 {this._dispatchers=[];InspectorBackend.registerHeapProfilerDispatcher(this);}
1193 WebInspector.HeapProfilerDispatcher.prototype={register:function(dispatcher)
1194 {this._dispatchers.push(dispatcher);},_genericCaller:function(eventName)
1195 {var args=Array.prototype.slice.call(arguments.callee.caller.arguments);for(var i=0;i<this._dispatchers.length;++i)
1196 this._dispatchers[i][eventName].apply(this._dispatchers[i],args);},heapStatsUpdate:function(samples)
1197 {this._genericCaller("heapStatsUpdate");},lastSeenObjectId:function(lastSeenObjectId,timestamp)
1198 {this._genericCaller("lastSeenObjectId");},addHeapSnapshotChunk:function(chunk)
1199 {this._genericCaller("addHeapSnapshotChunk");},reportHeapSnapshotProgress:function(done,total,finished)
1200 {this._genericCaller("reportHeapSnapshotProgress");},resetProfiles:function()
1201 {this._genericCaller("resetProfiles");}}
1202 WebInspector.HeapProfilerDispatcher._dispatcher=new WebInspector.HeapProfilerDispatcher();WebInspector.HeapSnapshotProfileType=function(id,title)
1203 {WebInspector.ProfileType.call(this,id||WebInspector.HeapSnapshotProfileType.TypeId,title||WebInspector.UIString("Take Heap Snapshot"));WebInspector.HeapProfilerDispatcher._dispatcher.register(this);}
1204 WebInspector.HeapSnapshotProfileType.TypeId="HEAP";WebInspector.HeapSnapshotProfileType.SnapshotReceived="SnapshotReceived";WebInspector.HeapSnapshotProfileType.prototype={fileExtension:function()
1205 {return".heapsnapshot";},get buttonTooltip()
1206 {return WebInspector.UIString("Take heap snapshot.");},isInstantProfile:function()
1207 {return true;},buttonClicked:function()
1208 {this._takeHeapSnapshot(function(){});WebInspector.userMetrics.ProfilesHeapProfileTaken.record();return false;},heapStatsUpdate:function(samples)
1209 {},lastSeenObjectId:function(lastSeenObjectId,timestamp)
1210 {},get treeItemTitle()
1211 {return WebInspector.UIString("HEAP SNAPSHOTS");},get description()
1212 {return WebInspector.UIString("Heap snapshot profiles show memory distribution among your page's JavaScript objects and related DOM nodes.");},createProfileLoadedFromFile:function(title)
1213 {return new WebInspector.HeapProfileHeader(this,title);},_takeHeapSnapshot:function(callback)
1214 {if(this.profileBeingRecorded())
1215 return;this._profileBeingRecorded=new WebInspector.HeapProfileHeader(this);this.addProfile(this._profileBeingRecorded);this._profileBeingRecorded.updateStatus(WebInspector.UIString("Snapshotting\u2026"));function didTakeHeapSnapshot(error)
1216 {var profile=this._profileBeingRecorded;profile.title=WebInspector.UIString("Snapshot %d",profile.uid);profile._finishLoad();this._profileBeingRecorded=null;WebInspector.panels.profiles.showProfile(profile);callback();}
1217 HeapProfilerAgent.takeHeapSnapshot(true,didTakeHeapSnapshot.bind(this));},addHeapSnapshotChunk:function(chunk)
1218 {if(!this.profileBeingRecorded())
1219 return;this.profileBeingRecorded().transferChunk(chunk);},reportHeapSnapshotProgress:function(done,total,finished)
1220 {var profile=this.profileBeingRecorded();if(!profile)
1221 return;profile.updateStatus(WebInspector.UIString("%.0f%",(done/total)*100),true);if(finished)
1222 profile._prepareToLoad();},resetProfiles:function()
1223 {this._reset();},_snapshotReceived:function(profile)
1224 {if(this._profileBeingRecorded===profile)
1225 this._profileBeingRecorded=null;this.dispatchEventToListeners(WebInspector.HeapSnapshotProfileType.SnapshotReceived,profile);},__proto__:WebInspector.ProfileType.prototype}
1226 WebInspector.TrackingHeapSnapshotProfileType=function()
1227 {WebInspector.HeapSnapshotProfileType.call(this,WebInspector.TrackingHeapSnapshotProfileType.TypeId,WebInspector.UIString("Record Heap Allocations"));}
1228 WebInspector.TrackingHeapSnapshotProfileType.TypeId="HEAP-RECORD";WebInspector.TrackingHeapSnapshotProfileType.HeapStatsUpdate="HeapStatsUpdate";WebInspector.TrackingHeapSnapshotProfileType.TrackingStarted="TrackingStarted";WebInspector.TrackingHeapSnapshotProfileType.TrackingStopped="TrackingStopped";WebInspector.TrackingHeapSnapshotProfileType.prototype={heapStatsUpdate:function(samples)
1229 {if(!this._profileSamples)
1230 return;var index;for(var i=0;i<samples.length;i+=3){index=samples[i];var count=samples[i+1];var size=samples[i+2];this._profileSamples.sizes[index]=size;if(!this._profileSamples.max[index])
1231 this._profileSamples.max[index]=size;}},lastSeenObjectId:function(lastSeenObjectId,timestamp)
1232 {var profileSamples=this._profileSamples;if(!profileSamples)
1233 return;var currentIndex=Math.max(profileSamples.ids.length,profileSamples.max.length-1);profileSamples.ids[currentIndex]=lastSeenObjectId;if(!profileSamples.max[currentIndex]){profileSamples.max[currentIndex]=0;profileSamples.sizes[currentIndex]=0;}
1234 profileSamples.timestamps[currentIndex]=timestamp;if(profileSamples.totalTime<timestamp-profileSamples.timestamps[0])
1235 profileSamples.totalTime*=2;this.dispatchEventToListeners(WebInspector.TrackingHeapSnapshotProfileType.HeapStatsUpdate,this._profileSamples);this._profileBeingRecorded.updateStatus(null,true);},hasTemporaryView:function()
1236 {return true;},get buttonTooltip()
1237 {return this._recording?WebInspector.UIString("Stop recording heap profile."):WebInspector.UIString("Start recording heap profile.");},isInstantProfile:function()
1238 {return false;},buttonClicked:function()
1239 {return this._toggleRecording();},_startRecordingProfile:function()
1240 {if(this.profileBeingRecorded())
1241 return;this._addNewProfile();HeapProfilerAgent.startTrackingHeapObjects(WebInspector.experimentsSettings.allocationProfiler.isEnabled());},_addNewProfile:function()
1242 {this._profileBeingRecorded=new WebInspector.HeapProfileHeader(this);this._lastSeenIndex=-1;this._profileSamples={'sizes':[],'ids':[],'timestamps':[],'max':[],'totalTime':30000};this._profileBeingRecorded._profileSamples=this._profileSamples;this._recording=true;this.addProfile(this._profileBeingRecorded);this._profileBeingRecorded.updateStatus(WebInspector.UIString("Recording\u2026"));this.dispatchEventToListeners(WebInspector.TrackingHeapSnapshotProfileType.TrackingStarted);},_stopRecordingProfile:function()
1243 {this._profileBeingRecorded.updateStatus(WebInspector.UIString("Snapshotting\u2026"));function didTakeHeapSnapshot(error)
1244 {var profile=this._profileBeingRecorded;if(!profile)
1245 return;profile._finishLoad();this._profileSamples=null;this._profileBeingRecorded=null;WebInspector.panels.profiles.showProfile(profile);}
1246 HeapProfilerAgent.stopTrackingHeapObjects(true,didTakeHeapSnapshot.bind(this));this._recording=false;this.dispatchEventToListeners(WebInspector.TrackingHeapSnapshotProfileType.TrackingStopped);},_toggleRecording:function()
1247 {if(this._recording)
1248 this._stopRecordingProfile();else
1249 this._startRecordingProfile();return this._recording;},get treeItemTitle()
1250 {return WebInspector.UIString("HEAP TIMELINES");},get description()
1251 {return WebInspector.UIString("Record JavaScript object allocations over time. Use this profile type to isolate memory leaks.");},resetProfiles:function()
1252 {var wasRecording=this._recording;this._profileBeingRecorded=null;WebInspector.HeapSnapshotProfileType.prototype.resetProfiles.call(this);this._profileSamples=null;this._lastSeenIndex=-1;if(wasRecording)
1253 this._addNewProfile();},profileBeingRecordedRemoved:function()
1254 {this._stopRecordingProfile();this._profileSamples=null;},__proto__:WebInspector.HeapSnapshotProfileType.prototype}
1255 WebInspector.HeapProfileHeader=function(type,title)
1256 {WebInspector.ProfileHeader.call(this,type,title||WebInspector.UIString("Snapshot %d",type._nextProfileUid));this.maxJSObjectId=-1;this._workerProxy=null;this._receiver=null;this._snapshotProxy=null;this._loadCallbacks=[];this._totalNumberOfChunks=0;this._bufferedWriter=null;}
1257 WebInspector.HeapProfileHeader.prototype={createSidebarTreeElement:function()
1258 {return new WebInspector.ProfileSidebarTreeElement(this,"heap-snapshot-sidebar-tree-item");},createView:function()
1259 {return new WebInspector.HeapSnapshotView(this);},load:function(callback)
1260 {if(this.uid===-1)
1261 return;if(this._snapshotProxy){callback(this._snapshotProxy);return;}
1262 this._loadCallbacks.push(callback);},_prepareToLoad:function()
1263 {console.assert(!this._receiver,"Already loading");this._setupWorker();this.updateStatus(WebInspector.UIString("Loading\u2026"),true);},_finishLoad:function()
1264 {if(!this._wasDisposed)
1265 this._receiver.close(function(){});if(this._bufferedWriter){this._bufferedWriter.close(this._didWriteToTempFile.bind(this));this._bufferedWriter=null;}},_didWriteToTempFile:function(tempFile)
1266 {if(this._wasDisposed){if(tempFile)
1267 tempFile.remove();return;}
1268 this._tempFile=tempFile;if(!tempFile)
1269 this._failedToCreateTempFile=true;if(this._onTempFileReady){this._onTempFileReady();this._onTempFileReady=null;}},_setupWorker:function()
1270 {function setProfileWait(event)
1271 {this.updateStatus(null,event.data);}
1272 console.assert(!this._workerProxy,"HeapSnapshotWorkerProxy already exists");this._workerProxy=new WebInspector.HeapSnapshotWorkerProxy(this._handleWorkerEvent.bind(this));this._workerProxy.addEventListener("wait",setProfileWait,this);this._receiver=this._workerProxy.createLoader(this.uid,this._snapshotReceived.bind(this));},_handleWorkerEvent:function(eventName,data)
1273 {if(WebInspector.HeapSnapshotProgressEvent.Update!==eventName)
1274 return;var subtitle=(data);this.updateStatus(subtitle);},dispose:function()
1275 {if(this._workerProxy)
1276 this._workerProxy.dispose();this.removeTempFile();this._wasDisposed=true;},_didCompleteSnapshotTransfer:function()
1277 {if(!this._snapshotProxy)
1278 return;this.updateStatus(Number.bytesToString(this._snapshotProxy.totalSize),false);},transferChunk:function(chunk)
1279 {if(!this._bufferedWriter)
1280 this._bufferedWriter=new WebInspector.BufferedTempFileWriter("heap-profiler",this.uid);this._bufferedWriter.write(chunk);++this._totalNumberOfChunks;this._receiver.write(chunk,function(){});},_snapshotReceived:function(snapshotProxy)
1281 {if(this._wasDisposed)
1282 return;this._receiver=null;this._snapshotProxy=snapshotProxy;this.maxJSObjectId=snapshotProxy.maxJSObjectId();this._didCompleteSnapshotTransfer();this._workerProxy.startCheckingForLongRunningCalls();this.notifySnapshotReceived();},notifySnapshotReceived:function()
1283 {for(var i=0;i<this._loadCallbacks.length;i++)
1284 this._loadCallbacks[i](this._snapshotProxy);this._loadCallbacks=null;this._profileType._snapshotReceived(this);if(this.canSaveToFile())
1285 this.dispatchEventToListeners(WebInspector.ProfileHeader.Events.ProfileReceived);},_wasShown:function()
1286 {},canSaveToFile:function()
1287 {return!this.fromFile()&&this._snapshotProxy;},saveToFile:function()
1288 {var fileOutputStream=new WebInspector.FileOutputStream();function onOpen(accepted)
1289 {if(!accepted)
1290 return;if(this._failedToCreateTempFile){WebInspector.console.log("Failed to open temp file with heap snapshot",WebInspector.ConsoleMessage.MessageLevel.Error);fileOutputStream.close();}else if(this._tempFile){var delegate=new WebInspector.SaveSnapshotOutputStreamDelegate(this);this._tempFile.writeToOutputSteam(fileOutputStream,delegate);}else{this._onTempFileReady=onOpen.bind(this,accepted);this._updateSaveProgress(0,1);}}
1291 this._fileName=this._fileName||"Heap-"+new Date().toISO8601Compact()+this._profileType.fileExtension();fileOutputStream.open(this._fileName,onOpen.bind(this));},_updateSaveProgress:function(value,total)
1292 {var percentValue=((total?(value/total):0)*100).toFixed(0);this.updateStatus(WebInspector.UIString("Saving\u2026 %d\%",percentValue));},loadFromFile:function(file)
1293 {this.updateStatus(WebInspector.UIString("Loading\u2026"),true);this._setupWorker();var delegate=new WebInspector.HeapSnapshotLoadFromFileDelegate(this);var fileReader=this._createFileReader(file,delegate);fileReader.start(this._receiver);},_createFileReader:function(file,delegate)
1294 {return new WebInspector.ChunkedFileReader(file,10000000,delegate);},__proto__:WebInspector.ProfileHeader.prototype}
1295 WebInspector.HeapSnapshotLoadFromFileDelegate=function(snapshotHeader)
1296 {this._snapshotHeader=snapshotHeader;}
1297 WebInspector.HeapSnapshotLoadFromFileDelegate.prototype={onTransferStarted:function()
1298 {},onChunkTransferred:function(reader)
1299 {},onTransferFinished:function()
1300 {},onError:function(reader,e)
1301 {var subtitle;switch(e.target.error.code){case e.target.error.NOT_FOUND_ERR:subtitle=WebInspector.UIString("'%s' not found.",reader.fileName());break;case e.target.error.NOT_READABLE_ERR:subtitle=WebInspector.UIString("'%s' is not readable",reader.fileName());break;case e.target.error.ABORT_ERR:return;default:subtitle=WebInspector.UIString("'%s' error %d",reader.fileName(),e.target.error.code);}
1302 this._snapshotHeader.updateStatus(subtitle);}}
1303 WebInspector.SaveSnapshotOutputStreamDelegate=function(profileHeader)
1304 {this._profileHeader=profileHeader;}
1305 WebInspector.SaveSnapshotOutputStreamDelegate.prototype={onTransferStarted:function()
1306 {this._profileHeader._updateSaveProgress(0,1);},onTransferFinished:function()
1307 {this._profileHeader._didCompleteSnapshotTransfer();},onChunkTransferred:function(reader)
1308 {this._profileHeader._updateSaveProgress(reader.loadedSize(),reader.fileSize());},onError:function(reader,event)
1309 {WebInspector.console.log("Failed to read heap snapshot from temp file: "+event.message,WebInspector.ConsoleMessage.MessageLevel.Error);this.onTransferFinished();}}
1310 WebInspector.HeapTrackingOverviewGrid=function(heapProfileHeader)
1311 {WebInspector.VBox.call(this);this.registerRequiredCSS("flameChart.css");this.element.id="heap-recording-view";this.element.classList.add("heap-tracking-overview");this._overviewContainer=this.element.createChild("div","overview-container");this._overviewGrid=new WebInspector.OverviewGrid("heap-recording");this._overviewGrid.element.classList.add("fill");this._overviewCanvas=this._overviewContainer.createChild("canvas","heap-recording-overview-canvas");this._overviewContainer.appendChild(this._overviewGrid.element);this._overviewCalculator=new WebInspector.HeapTrackingOverviewGrid.OverviewCalculator();this._overviewGrid.addEventListener(WebInspector.OverviewGrid.Events.WindowChanged,this._onWindowChanged,this);this._profileSamples=heapProfileHeader._profileSamples;if(heapProfileHeader.profileType().profileBeingRecorded()===heapProfileHeader){this._profileType=heapProfileHeader._profileType;this._profileType.addEventListener(WebInspector.TrackingHeapSnapshotProfileType.HeapStatsUpdate,this._onHeapStatsUpdate,this);this._profileType.addEventListener(WebInspector.TrackingHeapSnapshotProfileType.TrackingStopped,this._onStopTracking,this);}
1312 var timestamps=this._profileSamples.timestamps;var totalTime=this._profileSamples.totalTime;this._windowLeft=0.0;this._windowRight=totalTime&&timestamps.length?(timestamps[timestamps.length-1]-timestamps[0])/totalTime:1.0;this._overviewGrid.setWindow(this._windowLeft,this._windowRight);this._yScale=new WebInspector.HeapTrackingOverviewGrid.SmoothScale();this._xScale=new WebInspector.HeapTrackingOverviewGrid.SmoothScale();}
1313 WebInspector.HeapTrackingOverviewGrid.IdsRangeChanged="IdsRangeChanged";WebInspector.HeapTrackingOverviewGrid.prototype={_onStopTracking:function(event)
1314 {this._profileType.removeEventListener(WebInspector.TrackingHeapSnapshotProfileType.HeapStatsUpdate,this._onHeapStatsUpdate,this);this._profileType.removeEventListener(WebInspector.TrackingHeapSnapshotProfileType.TrackingStopped,this._onStopTracking,this);},_onHeapStatsUpdate:function(event)
1315 {this._profileSamples=event.data;this._scheduleUpdate();},_drawOverviewCanvas:function(width,height)
1316 {if(!this._profileSamples)
1317 return;var profileSamples=this._profileSamples;var sizes=profileSamples.sizes;var topSizes=profileSamples.max;var timestamps=profileSamples.timestamps;var startTime=timestamps[0];var endTime=timestamps[timestamps.length-1];var scaleFactor=this._xScale.nextScale(width/profileSamples.totalTime);var maxSize=0;function aggregateAndCall(sizes,callback)
1318 {var size=0;var currentX=0;for(var i=1;i<timestamps.length;++i){var x=Math.floor((timestamps[i]-startTime)*scaleFactor);if(x!==currentX){if(size)
1319 callback(currentX,size);size=0;currentX=x;}
1320 size+=sizes[i];}
1321 callback(currentX,size);}
1322 function maxSizeCallback(x,size)
1323 {maxSize=Math.max(maxSize,size);}
1324 aggregateAndCall(sizes,maxSizeCallback);var yScaleFactor=this._yScale.nextScale(maxSize?height/(maxSize*1.1):0.0);this._overviewCanvas.width=width*window.devicePixelRatio;this._overviewCanvas.height=height*window.devicePixelRatio;this._overviewCanvas.style.width=width+"px";this._overviewCanvas.style.height=height+"px";var context=this._overviewCanvas.getContext("2d");context.scale(window.devicePixelRatio,window.devicePixelRatio);context.beginPath();context.lineWidth=2;context.strokeStyle="rgba(192, 192, 192, 0.6)";var currentX=(endTime-startTime)*scaleFactor;context.moveTo(currentX,height-1);context.lineTo(currentX,0);context.stroke();context.closePath();var gridY;var gridValue;var gridLabelHeight=14;if(yScaleFactor){const maxGridValue=(height-gridLabelHeight)/yScaleFactor;gridValue=Math.pow(1024,Math.floor(Math.log(maxGridValue)/Math.log(1024)));gridValue*=Math.pow(10,Math.floor(Math.log(maxGridValue/gridValue)/Math.LN10));if(gridValue*5<=maxGridValue)
1325 gridValue*=5;gridY=Math.round(height-gridValue*yScaleFactor-0.5)+0.5;context.beginPath();context.lineWidth=1;context.strokeStyle="rgba(0, 0, 0, 0.2)";context.moveTo(0,gridY);context.lineTo(width,gridY);context.stroke();context.closePath();}
1326 function drawBarCallback(x,size)
1327 {context.moveTo(x,height-1);context.lineTo(x,Math.round(height-size*yScaleFactor-1));}
1328 context.beginPath();context.lineWidth=2;context.strokeStyle="rgba(192, 192, 192, 0.6)";aggregateAndCall(topSizes,drawBarCallback);context.stroke();context.closePath();context.beginPath();context.lineWidth=2;context.strokeStyle="rgba(0, 0, 192, 0.8)";aggregateAndCall(sizes,drawBarCallback);context.stroke();context.closePath();if(gridValue){var label=Number.bytesToString(gridValue);var labelPadding=4;var labelX=0;var labelY=gridY-0.5;var labelWidth=2*labelPadding+context.measureText(label).width;context.beginPath();context.textBaseline="bottom";context.font="10px "+window.getComputedStyle(this.element,null).getPropertyValue("font-family");context.fillStyle="rgba(255, 255, 255, 0.75)";context.fillRect(labelX,labelY-gridLabelHeight,labelWidth,gridLabelHeight);context.fillStyle="rgb(64, 64, 64)";context.fillText(label,labelX+labelPadding,labelY);context.fill();context.closePath();}},onResize:function()
1329 {this._updateOverviewCanvas=true;this._scheduleUpdate();},_onWindowChanged:function()
1330 {if(!this._updateGridTimerId)
1331 this._updateGridTimerId=setTimeout(this._updateGrid.bind(this),10);},_scheduleUpdate:function()
1332 {if(this._updateTimerId)
1333 return;this._updateTimerId=setTimeout(this.update.bind(this),10);},_updateBoundaries:function()
1334 {this._windowLeft=this._overviewGrid.windowLeft();this._windowRight=this._overviewGrid.windowRight();this._windowWidth=this._windowRight-this._windowLeft;},update:function()
1335 {this._updateTimerId=null;if(!this.isShowing())
1336 return;this._updateBoundaries();this._overviewCalculator._updateBoundaries(this);this._overviewGrid.updateDividers(this._overviewCalculator);this._drawOverviewCanvas(this._overviewContainer.clientWidth,this._overviewContainer.clientHeight-20);},_updateGrid:function()
1337 {this._updateGridTimerId=0;this._updateBoundaries();var ids=this._profileSamples.ids;var timestamps=this._profileSamples.timestamps;var sizes=this._profileSamples.sizes;var startTime=timestamps[0];var totalTime=this._profileSamples.totalTime;var timeLeft=startTime+totalTime*this._windowLeft;var timeRight=startTime+totalTime*this._windowRight;var minId=0;var maxId=ids[ids.length-1]+1;var size=0;for(var i=0;i<timestamps.length;++i){if(!timestamps[i])
1338 continue;if(timestamps[i]>timeRight)
1339 break;maxId=ids[i];if(timestamps[i]<timeLeft){minId=ids[i];continue;}
1340 size+=sizes[i];}
1341 this.dispatchEventToListeners(WebInspector.HeapTrackingOverviewGrid.IdsRangeChanged,{minId:minId,maxId:maxId,size:size});},__proto__:WebInspector.VBox.prototype}
1342 WebInspector.HeapTrackingOverviewGrid.SmoothScale=function()
1343 {this._lastUpdate=0;this._currentScale=0.0;}
1344 WebInspector.HeapTrackingOverviewGrid.SmoothScale.prototype={nextScale:function(target){target=target||this._currentScale;if(this._currentScale){var now=Date.now();var timeDeltaMs=now-this._lastUpdate;this._lastUpdate=now;var maxChangePerSec=20;var maxChangePerDelta=Math.pow(maxChangePerSec,timeDeltaMs/1000);var scaleChange=target/this._currentScale;this._currentScale*=Number.constrain(scaleChange,1/maxChangePerDelta,maxChangePerDelta);}else
1345 this._currentScale=target;return this._currentScale;}}
1346 WebInspector.HeapTrackingOverviewGrid.OverviewCalculator=function()
1347 {}
1348 WebInspector.HeapTrackingOverviewGrid.OverviewCalculator.prototype={paddingLeft:function()
1349 {return 0;},_updateBoundaries:function(chart)
1350 {this._minimumBoundaries=0;this._maximumBoundaries=chart._profileSamples.totalTime;this._xScaleFactor=chart._overviewContainer.clientWidth/this._maximumBoundaries;},computePosition:function(time)
1351 {return(time-this._minimumBoundaries)*this._xScaleFactor;},formatTime:function(value,precision)
1352 {return Number.secondsToString(value/1000,!!precision);},maximumBoundary:function()
1353 {return this._maximumBoundaries;},minimumBoundary:function()
1354 {return this._minimumBoundaries;},zeroTime:function()
1355 {return this._minimumBoundaries;},boundarySpan:function()
1356 {return this._maximumBoundaries-this._minimumBoundaries;}}
1357 WebInspector.HeapSnapshotStatisticsView=function()
1358 {WebInspector.VBox.call(this);this.setMinimumSize(50,25);this._pieChart=new WebInspector.PieChart();this._pieChart.setSize(150);this.element.appendChild(this._pieChart.element);this._labels=this.element.createChild("div","heap-snapshot-stats-legend");}
1359 WebInspector.HeapSnapshotStatisticsView.prototype={setTotal:function(value)
1360 {this._pieChart.setTotal(value);},addRecord:function(value,name,color)
1361 {if(color)
1362 this._pieChart.addSlice(value,color);var node=this._labels.createChild("div");var swatchDiv=node.createChild("div","heap-snapshot-stats-swatch");var nameDiv=node.createChild("div","heap-snapshot-stats-name");var sizeDiv=node.createChild("div","heap-snapshot-stats-size");if(color)
1363 swatchDiv.style.backgroundColor=color;else
1364 swatchDiv.classList.add("heap-snapshot-stats-empty-swatch");nameDiv.textContent=name;sizeDiv.textContent=WebInspector.UIString("%s KB",Number.withThousandsSeparator(Math.round(value/1024)));},__proto__:WebInspector.VBox.prototype};WebInspector.ProfileLauncherView=function(profilesPanel)
1365 {WebInspector.VBox.call(this);this._panel=profilesPanel;this.element.classList.add("profile-launcher-view");this.element.classList.add("panel-enabler-view");this._contentElement=this.element.createChild("div","profile-launcher-view-content");this._innerContentElement=this._contentElement.createChild("div");this._controlButton=this._contentElement.createChild("button","control-profiling");this._controlButton.addEventListener("click",this._controlButtonClicked.bind(this),false);this._loadButton=this._contentElement.createChild("button","load-profile");this._loadButton.textContent=WebInspector.UIString("Load");this._loadButton.addEventListener("click",this._loadButtonClicked.bind(this),false);}
1366 WebInspector.ProfileLauncherView.prototype={addProfileType:function(profileType)
1367 {var descriptionElement=this._innerContentElement.createChild("h1");descriptionElement.textContent=profileType.description;var decorationElement=profileType.decorationElement();if(decorationElement)
1368 this._innerContentElement.appendChild(decorationElement);this._isInstantProfile=profileType.isInstantProfile();this._isEnabled=profileType.isEnabled();this._profileTypeId=profileType.id;},_controlButtonClicked:function()
1369 {this._panel.toggleRecordButton();},_loadButtonClicked:function()
1370 {this._panel.showLoadFromFileDialog();},_updateControls:function()
1371 {if(this._isEnabled)
1372 this._controlButton.removeAttribute("disabled");else
1373 this._controlButton.setAttribute("disabled","");if(this._isInstantProfile){this._controlButton.classList.remove("running");this._controlButton.textContent=WebInspector.UIString("Take Snapshot");}else if(this._isProfiling){this._controlButton.classList.add("running");this._controlButton.textContent=WebInspector.UIString("Stop");}else{this._controlButton.classList.remove("running");this._controlButton.textContent=WebInspector.UIString("Start");}},profileStarted:function()
1374 {this._isProfiling=true;this._updateControls();},profileFinished:function()
1375 {this._isProfiling=false;this._updateControls();},updateProfileType:function(profileType)
1376 {this._isInstantProfile=profileType.isInstantProfile();this._isEnabled=profileType.isEnabled();this._profileTypeId=profileType.id;this._updateControls();},__proto__:WebInspector.VBox.prototype}
1377 WebInspector.MultiProfileLauncherView=function(profilesPanel)
1378 {WebInspector.ProfileLauncherView.call(this,profilesPanel);WebInspector.settings.selectedProfileType=WebInspector.settings.createSetting("selectedProfileType","CPU");var header=this._innerContentElement.createChild("h1");header.textContent=WebInspector.UIString("Select profiling type");this._profileTypeSelectorForm=this._innerContentElement.createChild("form");this._innerContentElement.createChild("div","flexible-space");this._typeIdToOptionElement={};}
1379 WebInspector.MultiProfileLauncherView.EventTypes={ProfileTypeSelected:"profile-type-selected"}
1380 WebInspector.MultiProfileLauncherView.prototype={addProfileType:function(profileType)
1381 {var labelElement=this._profileTypeSelectorForm.createChild("label");labelElement.textContent=profileType.name;var optionElement=document.createElement("input");labelElement.insertBefore(optionElement,labelElement.firstChild);this._typeIdToOptionElement[profileType.id]=optionElement;optionElement._profileType=profileType;optionElement.type="radio";optionElement.name="profile-type";optionElement.style.hidden=true;optionElement.addEventListener("change",this._profileTypeChanged.bind(this,profileType),false);var descriptionElement=labelElement.createChild("p");descriptionElement.textContent=profileType.description;var decorationElement=profileType.decorationElement();if(decorationElement)
1382 labelElement.appendChild(decorationElement);},restoreSelectedProfileType:function()
1383 {var typeId=WebInspector.settings.selectedProfileType.get();if(!(typeId in this._typeIdToOptionElement))
1384 typeId=Object.keys(this._typeIdToOptionElement)[0];this._typeIdToOptionElement[typeId].checked=true;var type=this._typeIdToOptionElement[typeId]._profileType;this.dispatchEventToListeners(WebInspector.MultiProfileLauncherView.EventTypes.ProfileTypeSelected,type);},_controlButtonClicked:function()
1385 {this._panel.toggleRecordButton();},_updateControls:function()
1386 {WebInspector.ProfileLauncherView.prototype._updateControls.call(this);var items=this._profileTypeSelectorForm.elements;for(var i=0;i<items.length;++i){if(items[i].type==="radio")
1387 items[i].disabled=this._isProfiling;}},_profileTypeChanged:function(profileType,event)
1388 {this.dispatchEventToListeners(WebInspector.MultiProfileLauncherView.EventTypes.ProfileTypeSelected,profileType);this._isInstantProfile=profileType.isInstantProfile();this._isEnabled=profileType.isEnabled();this._profileTypeId=profileType.id;this._updateControls();WebInspector.settings.selectedProfileType.set(profileType.id);},profileStarted:function()
1389 {this._isProfiling=true;this._updateControls();},profileFinished:function()
1390 {this._isProfiling=false;this._updateControls();},__proto__:WebInspector.ProfileLauncherView.prototype};WebInspector.TopDownProfileDataGridNode=function(profileNode,owningTree)
1391 {var hasChildren=!!(profileNode.children&&profileNode.children.length);WebInspector.ProfileDataGridNode.call(this,profileNode,owningTree,hasChildren);this._remainingChildren=profileNode.children;}
1392 WebInspector.TopDownProfileDataGridNode.prototype={_sharedPopulate:function()
1393 {var children=this._remainingChildren;var childrenLength=children.length;for(var i=0;i<childrenLength;++i)
1394 this.appendChild(new WebInspector.TopDownProfileDataGridNode(children[i],this.tree));this._remainingChildren=null;},_exclude:function(aCallUID)
1395 {if(this._remainingChildren)
1396 this.populate();this._save();var children=this.children;var index=this.children.length;while(index--)
1397 children[index]._exclude(aCallUID);var child=this.childrenByCallUID[aCallUID];if(child)
1398 this._merge(child,true);},__proto__:WebInspector.ProfileDataGridNode.prototype}
1399 WebInspector.TopDownProfileDataGridTree=function(profileView,rootProfileNode)
1400 {WebInspector.ProfileDataGridTree.call(this,profileView,rootProfileNode);this._remainingChildren=rootProfileNode.children;var any=(this);var node=(any);WebInspector.TopDownProfileDataGridNode.prototype.populate.call(node);}
1401 WebInspector.TopDownProfileDataGridTree.prototype={focus:function(profileDataGridNode)
1402 {if(!profileDataGridNode)
1403 return;this._save();profileDataGridNode.savePosition();this.children=[profileDataGridNode];this.totalTime=profileDataGridNode.totalTime;},exclude:function(profileDataGridNode)
1404 {if(!profileDataGridNode)
1405 return;this._save();var excludedCallUID=profileDataGridNode.callUID;var any=(this);var node=(any);WebInspector.TopDownProfileDataGridNode.prototype._exclude.call(node,excludedCallUID);if(this.lastComparator)
1406 this.sort(this.lastComparator,true);},restore:function()
1407 {if(!this._savedChildren)
1408 return;this.children[0].restorePosition();WebInspector.ProfileDataGridTree.prototype.restore.call(this);},_merge:WebInspector.TopDownProfileDataGridNode.prototype._merge,_sharedPopulate:WebInspector.TopDownProfileDataGridNode.prototype._sharedPopulate,__proto__:WebInspector.ProfileDataGridTree.prototype};WebInspector.CanvasProfileView=function(profile)
1409 {WebInspector.VBox.call(this);this.registerRequiredCSS("canvasProfiler.css");this.element.classList.add("canvas-profile-view");this._profile=profile;this._traceLogId=profile.traceLogId();this._traceLogPlayer=(profile.traceLogPlayer());this._linkifier=new WebInspector.Linkifier();this._replayInfoSplitView=new WebInspector.SplitView(true,true,"canvasProfileViewReplaySplitViewState",0.34);this._replayInfoSplitView.show(this.element);this._imageSplitView=new WebInspector.SplitView(false,true,"canvasProfileViewSplitViewState",300);this._imageSplitView.show(this._replayInfoSplitView.mainElement());var replayImageContainerView=new WebInspector.VBox();replayImageContainerView.setMinimumSize(50,28);replayImageContainerView.show(this._imageSplitView.mainElement());var replayImageContainer=replayImageContainerView.element.createChild("div");replayImageContainer.id="canvas-replay-image-container";this._replayImageElement=replayImageContainer.createChild("img","canvas-replay-image");this._debugInfoElement=replayImageContainer.createChild("div","canvas-debug-info hidden");this._spinnerIcon=replayImageContainer.createChild("div","spinner-icon small hidden");var replayLogContainerView=new WebInspector.VBox();replayLogContainerView.setMinimumSize(22,22);replayLogContainerView.show(this._imageSplitView.sidebarElement());var replayLogContainer=replayLogContainerView.element;var controlsContainer=replayLogContainer.createChild("div","status-bar");var logGridContainer=replayLogContainer.createChild("div","canvas-replay-log");this._createControlButton(controlsContainer,"canvas-replay-first-step",WebInspector.UIString("First call."),this._onReplayFirstStepClick.bind(this));this._createControlButton(controlsContainer,"canvas-replay-prev-step",WebInspector.UIString("Previous call."),this._onReplayStepClick.bind(this,false));this._createControlButton(controlsContainer,"canvas-replay-next-step",WebInspector.UIString("Next call."),this._onReplayStepClick.bind(this,true));this._createControlButton(controlsContainer,"canvas-replay-prev-draw",WebInspector.UIString("Previous drawing call."),this._onReplayDrawingCallClick.bind(this,false));this._createControlButton(controlsContainer,"canvas-replay-next-draw",WebInspector.UIString("Next drawing call."),this._onReplayDrawingCallClick.bind(this,true));this._createControlButton(controlsContainer,"canvas-replay-last-step",WebInspector.UIString("Last call."),this._onReplayLastStepClick.bind(this));this._replayContextSelector=new WebInspector.StatusBarComboBox(this._onReplayContextChanged.bind(this));this._replayContextSelector.createOption(WebInspector.UIString("<screenshot auto>"),WebInspector.UIString("Show screenshot of the last replayed resource."),"");controlsContainer.appendChild(this._replayContextSelector.element);this._installReplayInfoSidebarWidgets(controlsContainer);this._replayStateView=new WebInspector.CanvasReplayStateView(this._traceLogPlayer);this._replayStateView.show(this._replayInfoSplitView.sidebarElement());this._replayContexts={};var columns=[{title:"#",sortable:false,width:"5%"},{title:WebInspector.UIString("Call"),sortable:false,width:"75%",disclosure:true},{title:WebInspector.UIString("Location"),sortable:false,width:"20%"}];this._logGrid=new WebInspector.DataGrid(columns);this._logGrid.element.classList.add("fill");this._logGrid.show(logGridContainer);this._logGrid.addEventListener(WebInspector.DataGrid.Events.SelectedNode,this._replayTraceLog,this);this.element.addEventListener("mousedown",this._onMouseClick.bind(this),true);this._popoverHelper=new WebInspector.ObjectPopoverHelper(this.element,this._popoverAnchor.bind(this),this._resolveObjectForPopover.bind(this),this._onHidePopover.bind(this),true);this._popoverHelper.setRemoteObjectFormatter(this._hexNumbersFormatter.bind(this));this._requestTraceLog(0);}
1410 WebInspector.CanvasProfileView.TraceLogPollingInterval=500;WebInspector.CanvasProfileView.prototype={dispose:function()
1411 {this._linkifier.reset();},get statusBarItems()
1412 {return[];},get profile()
1413 {return this._profile;},elementsToRestoreScrollPositionsFor:function()
1414 {return[this._logGrid.scrollContainer];},_installReplayInfoSidebarWidgets:function(controlsContainer)
1415 {this._replayInfoResizeWidgetElement=controlsContainer.createChild("div","resizer-widget");this._replayInfoSplitView.addEventListener(WebInspector.SplitView.Events.ShowModeChanged,this._updateReplayInfoResizeWidget,this);this._updateReplayInfoResizeWidget();this._replayInfoSplitView.installResizer(this._replayInfoResizeWidgetElement);this._toggleReplayStateSidebarButton=this._replayInfoSplitView.createShowHideSidebarButton("sidebar","canvas-sidebar-show-hide-button");controlsContainer.appendChild(this._toggleReplayStateSidebarButton.element);this._replayInfoSplitView.hideSidebar();},_updateReplayInfoResizeWidget:function()
1416 {this._replayInfoResizeWidgetElement.classList.toggle("hidden",this._replayInfoSplitView.showMode()!==WebInspector.SplitView.ShowMode.Both);},_onMouseClick:function(event)
1417 {var resourceLinkElement=event.target.enclosingNodeOrSelfWithClass("canvas-formatted-resource");if(resourceLinkElement){this._replayInfoSplitView.showBoth();this._replayStateView.selectResource(resourceLinkElement.__resourceId);event.consume(true);return;}
1418 if(event.target.enclosingNodeOrSelfWithClass("webkit-html-resource-link"))
1419 event.consume(false);},_createControlButton:function(parent,className,title,clickCallback)
1420 {var button=new WebInspector.StatusBarButton(title,className+" canvas-replay-button");parent.appendChild(button.element);button.makeLongClickEnabled();button.addEventListener("click",clickCallback,this);button.addEventListener("longClickDown",clickCallback,this);button.addEventListener("longClickPress",clickCallback,this);},_onReplayContextChanged:function()
1421 {var selectedContextId=this._replayContextSelector.selectedOption().value;function didReceiveResourceState(resourceState)
1422 {this._enableWaitIcon(false);if(selectedContextId!==this._replayContextSelector.selectedOption().value)
1423 return;var imageURL=(resourceState&&resourceState.imageURL)||"";this._replayImageElement.src=imageURL;this._replayImageElement.style.visibility=imageURL?"":"hidden";}
1424 this._enableWaitIcon(true);this._traceLogPlayer.getResourceState(selectedContextId,didReceiveResourceState.bind(this));},_onReplayStepClick:function(forward)
1425 {var selectedNode=this._logGrid.selectedNode;if(!selectedNode)
1426 return;var nextNode=selectedNode;do{nextNode=forward?nextNode.traverseNextNode(false):nextNode.traversePreviousNode(false);}while(nextNode&&typeof nextNode.index!=="number");(nextNode||selectedNode).revealAndSelect();},_onReplayDrawingCallClick:function(forward)
1427 {var selectedNode=this._logGrid.selectedNode;if(!selectedNode)
1428 return;var nextNode=selectedNode;while(nextNode){var sibling=forward?nextNode.nextSibling:nextNode.previousSibling;if(sibling){nextNode=sibling;if(nextNode.hasChildren||nextNode.call.isDrawingCall)
1429 break;}else{nextNode=nextNode.parent;if(!forward)
1430 break;}}
1431 if(!nextNode&&forward)
1432 this._onReplayLastStepClick();else
1433 (nextNode||selectedNode).revealAndSelect();},_onReplayFirstStepClick:function()
1434 {var firstNode=this._logGrid.rootNode().children[0];if(firstNode)
1435 firstNode.revealAndSelect();},_onReplayLastStepClick:function()
1436 {var lastNode=this._logGrid.rootNode().children.peekLast();if(!lastNode)
1437 return;while(lastNode.expanded){var lastChild=lastNode.children.peekLast();if(!lastChild)
1438 break;lastNode=lastChild;}
1439 lastNode.revealAndSelect();},_enableWaitIcon:function(enable)
1440 {this._spinnerIcon.classList.toggle("hidden",!enable);this._debugInfoElement.classList.toggle("hidden",enable);},_replayTraceLog:function()
1441 {if(this._pendingReplayTraceLogEvent)
1442 return;var index=this._selectedCallIndex();if(index===-1||index===this._lastReplayCallIndex)
1443 return;this._lastReplayCallIndex=index;this._pendingReplayTraceLogEvent=true;function didReplayTraceLog(resourceState,replayTime)
1444 {delete this._pendingReplayTraceLogEvent;this._enableWaitIcon(false);this._debugInfoElement.textContent=WebInspector.UIString("Replay time: %s",Number.secondsToString(replayTime/1000,true));this._onReplayContextChanged();if(index!==this._selectedCallIndex())
1445 this._replayTraceLog();}
1446 this._enableWaitIcon(true);this._traceLogPlayer.replayTraceLog(index,didReplayTraceLog.bind(this));},_requestTraceLog:function(offset)
1447 {function didReceiveTraceLog(traceLog)
1448 {this._enableWaitIcon(false);if(!traceLog)
1449 return;var callNodes=[];var calls=traceLog.calls;var index=traceLog.startOffset;for(var i=0,n=calls.length;i<n;++i)
1450 callNodes.push(this._createCallNode(index++,calls[i]));var contexts=traceLog.contexts;for(var i=0,n=contexts.length;i<n;++i){var contextId=contexts[i].resourceId||"";var description=contexts[i].description||"";if(this._replayContexts[contextId])
1451 continue;this._replayContexts[contextId]=true;this._replayContextSelector.createOption(description,WebInspector.UIString("Show screenshot of this context's canvas."),contextId);}
1452 this._appendCallNodes(callNodes);if(traceLog.alive)
1453 setTimeout(this._requestTraceLog.bind(this,index),WebInspector.CanvasProfileView.TraceLogPollingInterval);else
1454 this._flattenSingleFrameNode();this._profile._updateCapturingStatus(traceLog);this._onReplayLastStepClick();}
1455 this._enableWaitIcon(true);this._traceLogPlayer.getTraceLog(offset,undefined,didReceiveTraceLog.bind(this));},_selectedCallIndex:function()
1456 {var node=this._logGrid.selectedNode;return node?this._peekLastRecursively(node).index:-1;},_peekLastRecursively:function(node)
1457 {var lastChild;while((lastChild=node.children.peekLast()))
1458 node=lastChild;return node;},_appendCallNodes:function(callNodes)
1459 {var rootNode=this._logGrid.rootNode();var frameNode=rootNode.children.peekLast();if(frameNode&&this._peekLastRecursively(frameNode).call.isFrameEndCall)
1460 frameNode=null;for(var i=0,n=callNodes.length;i<n;++i){if(!frameNode){var index=rootNode.children.length;var data={};data[0]="";data[1]=WebInspector.UIString("Frame #%d",index+1);data[2]="";frameNode=new WebInspector.DataGridNode(data);frameNode.selectable=true;rootNode.appendChild(frameNode);}
1461 var nextFrameCallIndex=i+1;while(nextFrameCallIndex<n&&!callNodes[nextFrameCallIndex-1].call.isFrameEndCall)
1462 ++nextFrameCallIndex;this._appendCallNodesToFrameNode(frameNode,callNodes,i,nextFrameCallIndex);i=nextFrameCallIndex-1;frameNode=null;}},_appendCallNodesToFrameNode:function(frameNode,callNodes,fromIndex,toIndex)
1463 {var self=this;function appendDrawCallGroup()
1464 {var index=self._drawCallGroupsCount||0;var data={};data[0]="";data[1]=WebInspector.UIString("Draw call group #%d",index+1);data[2]="";var node=new WebInspector.DataGridNode(data);node.selectable=true;self._drawCallGroupsCount=index+1;frameNode.appendChild(node);return node;}
1465 function splitDrawCallGroup(drawCallGroup)
1466 {var splitIndex=0;var splitNode;while((splitNode=drawCallGroup.children[splitIndex])){if(splitNode.call.isDrawingCall)
1467 break;++splitIndex;}
1468 var newDrawCallGroup=appendDrawCallGroup();var lastNode;while((lastNode=drawCallGroup.children[splitIndex+1]))
1469 newDrawCallGroup.appendChild(lastNode);return newDrawCallGroup;}
1470 var drawCallGroup=frameNode.children.peekLast();var groupHasDrawCall=false;if(drawCallGroup){for(var i=0,n=drawCallGroup.children.length;i<n;++i){if(drawCallGroup.children[i].call.isDrawingCall){groupHasDrawCall=true;break;}}}else
1471 drawCallGroup=appendDrawCallGroup();for(var i=fromIndex;i<toIndex;++i){var node=callNodes[i];drawCallGroup.appendChild(node);if(node.call.isDrawingCall){if(groupHasDrawCall)
1472 drawCallGroup=splitDrawCallGroup(drawCallGroup);else
1473 groupHasDrawCall=true;}}},_createCallNode:function(index,call)
1474 {var callViewElement=document.createElement("div");var data={};data[0]=index+1;data[1]=callViewElement;data[2]="";if(call.sourceURL){var lineNumber=Math.max(0,call.lineNumber-1)||0;var columnNumber=Math.max(0,call.columnNumber-1)||0;data[2]=this._linkifier.linkifyLocation(call.sourceURL,lineNumber,columnNumber);}
1475 callViewElement.createChild("span","canvas-function-name").textContent=call.functionName||"context."+call.property;if(call.arguments){callViewElement.createTextChild("(");for(var i=0,n=call.arguments.length;i<n;++i){var argument=(call.arguments[i]);if(i)
1476 callViewElement.createTextChild(", ");var element=WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(argument);element.__argumentIndex=i;callViewElement.appendChild(element);}
1477 callViewElement.createTextChild(")");}else if(call.value){callViewElement.createTextChild(" = ");callViewElement.appendChild(WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(call.value));}
1478 if(call.result){callViewElement.createTextChild(" => ");callViewElement.appendChild(WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(call.result));}
1479 var node=new WebInspector.DataGridNode(data);node.index=index;node.selectable=true;node.call=call;return node;},_popoverAnchor:function(element,event)
1480 {var argumentElement=element.enclosingNodeOrSelfWithClass("canvas-call-argument");if(!argumentElement||argumentElement.__suppressPopover)
1481 return null;return argumentElement;},_resolveObjectForPopover:function(argumentElement,showCallback,objectGroupName)
1482 {function showObjectPopover(error,result,resourceState)
1483 {if(error)
1484 return;if(!result)
1485 return;this._popoverAnchorElement=argumentElement.cloneNode(true);this._popoverAnchorElement.classList.add("canvas-popover-anchor");this._popoverAnchorElement.classList.add("source-frame-eval-expression");argumentElement.parentElement.appendChild(this._popoverAnchorElement);var diffLeft=this._popoverAnchorElement.boxInWindow().x-argumentElement.boxInWindow().x;this._popoverAnchorElement.style.left=this._popoverAnchorElement.offsetLeft-diffLeft+"px";showCallback(WebInspector.RemoteObject.fromPayload(result),false,this._popoverAnchorElement);}
1486 var evalResult=argumentElement.__evalResult;if(evalResult)
1487 showObjectPopover.call(this,null,evalResult);else{var dataGridNode=this._logGrid.dataGridNodeFromNode(argumentElement);if(!dataGridNode||typeof dataGridNode.index!=="number"){this._popoverHelper.hidePopover();return;}
1488 var callIndex=dataGridNode.index;var argumentIndex=argumentElement.__argumentIndex;if(typeof argumentIndex!=="number")
1489 argumentIndex=-1;CanvasAgent.evaluateTraceLogCallArgument(this._traceLogId,callIndex,argumentIndex,objectGroupName,showObjectPopover.bind(this));}},_hexNumbersFormatter:function(object)
1490 {if(object.type==="number"){var str="0000"+Number(object.description).toString(16).toUpperCase();str=str.replace(/^0+(.{4,})$/,"$1");return"0x"+str;}
1491 return object.description||"";},_onHidePopover:function()
1492 {if(this._popoverAnchorElement){this._popoverAnchorElement.remove()
1493 delete this._popoverAnchorElement;}},_flattenSingleFrameNode:function()
1494 {var rootNode=this._logGrid.rootNode();if(rootNode.children.length!==1)
1495 return;var frameNode=rootNode.children[0];while(frameNode.children[0])
1496 rootNode.appendChild(frameNode.children[0]);rootNode.removeChild(frameNode);},__proto__:WebInspector.VBox.prototype}
1497 WebInspector.CanvasProfileType=function()
1498 {WebInspector.ProfileType.call(this,WebInspector.CanvasProfileType.TypeId,WebInspector.UIString("Capture Canvas Frame"));this._recording=false;this._lastProfileHeader=null;this._capturingModeSelector=new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));this._capturingModeSelector.element.title=WebInspector.UIString("Canvas capture mode.");this._capturingModeSelector.createOption(WebInspector.UIString("Single Frame"),WebInspector.UIString("Capture a single canvas frame."),"");this._capturingModeSelector.createOption(WebInspector.UIString("Consecutive Frames"),WebInspector.UIString("Capture consecutive canvas frames."),"1");this._frameOptions={};this._framesWithCanvases={};this._frameSelector=new WebInspector.StatusBarComboBox(this._dispatchViewUpdatedEvent.bind(this));this._frameSelector.element.title=WebInspector.UIString("Frame containing the canvases to capture.");this._frameSelector.element.classList.add("hidden");WebInspector.resourceTreeModel.frames().forEach(this._addFrame,this);WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameAdded,this._frameAdded,this);WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.FrameDetached,this._frameRemoved,this);this._dispatcher=new WebInspector.CanvasDispatcher(this);this._canvasAgentEnabled=false;this._decorationElement=document.createElement("div");this._decorationElement.className="profile-canvas-decoration";this._updateDecorationElement();}
1499 WebInspector.CanvasProfileType.TypeId="CANVAS_PROFILE";WebInspector.CanvasProfileType.prototype={get statusBarItems()
1500 {return[this._capturingModeSelector.element,this._frameSelector.element];},get buttonTooltip()
1501 {if(this._isSingleFrameMode())
1502 return WebInspector.UIString("Capture next canvas frame.");else
1503 return this._recording?WebInspector.UIString("Stop capturing canvas frames."):WebInspector.UIString("Start capturing canvas frames.");},buttonClicked:function()
1504 {if(!this._canvasAgentEnabled)
1505 return false;if(this._recording){this._recording=false;this._stopFrameCapturing();}else if(this._isSingleFrameMode()){this._recording=false;this._runSingleFrameCapturing();}else{this._recording=true;this._startFrameCapturing();}
1506 return this._recording;},_runSingleFrameCapturing:function()
1507 {var frameId=this._selectedFrameId();CanvasAgent.captureFrame(frameId,this._didStartCapturingFrame.bind(this,frameId));},_startFrameCapturing:function()
1508 {var frameId=this._selectedFrameId();CanvasAgent.startCapturing(frameId,this._didStartCapturingFrame.bind(this,frameId));},_stopFrameCapturing:function()
1509 {if(!this._lastProfileHeader)
1510 return;var profileHeader=this._lastProfileHeader;var traceLogId=profileHeader.traceLogId();this._lastProfileHeader=null;function didStopCapturing()
1511 {profileHeader._updateCapturingStatus();}
1512 CanvasAgent.stopCapturing(traceLogId,didStopCapturing);},_didStartCapturingFrame:function(frameId,error,traceLogId)
1513 {if(error||this._lastProfileHeader&&this._lastProfileHeader.traceLogId()===traceLogId)
1514 return;var profileHeader=new WebInspector.CanvasProfileHeader(this,traceLogId,frameId);this._lastProfileHeader=profileHeader;this.addProfile(profileHeader);profileHeader._updateCapturingStatus();},get treeItemTitle()
1515 {return WebInspector.UIString("CANVAS PROFILE");},get description()
1516 {return WebInspector.UIString("Canvas calls instrumentation");},decorationElement:function()
1517 {return this._decorationElement;},removeProfile:function(profile)
1518 {WebInspector.ProfileType.prototype.removeProfile.call(this,profile);if(this._recording&&profile===this._lastProfileHeader)
1519 this._recording=false;},_updateDecorationElement:function(forcePageReload)
1520 {this._decorationElement.removeChildren();this._decorationElement.createChild("div","warning-icon-small");this._decorationElement.appendChild(document.createTextNode(this._canvasAgentEnabled?WebInspector.UIString("Canvas Profiler is enabled."):WebInspector.UIString("Canvas Profiler is disabled.")));var button=this._decorationElement.createChild("button");button.type="button";button.textContent=this._canvasAgentEnabled?WebInspector.UIString("Disable"):WebInspector.UIString("Enable");button.addEventListener("click",this._onProfilerEnableButtonClick.bind(this,!this._canvasAgentEnabled),false);function hasUninstrumentedCanvasesCallback(error,result)
1521 {if(error||result)
1522 WebInspector.resourceTreeModel.reloadPage();}
1523 if(forcePageReload){if(this._canvasAgentEnabled){CanvasAgent.hasUninstrumentedCanvases(hasUninstrumentedCanvasesCallback);}else{for(var frameId in this._framesWithCanvases){if(this._framesWithCanvases.hasOwnProperty(frameId)){WebInspector.resourceTreeModel.reloadPage();break;}}}}},_onProfilerEnableButtonClick:function(enable)
1524 {if(this._canvasAgentEnabled===enable)
1525 return;function callback(error)
1526 {if(error)
1527 return;this._canvasAgentEnabled=enable;this._updateDecorationElement(true);this._dispatchViewUpdatedEvent();}
1528 if(enable)
1529 CanvasAgent.enable(callback.bind(this));else
1530 CanvasAgent.disable(callback.bind(this));},_isSingleFrameMode:function()
1531 {return!this._capturingModeSelector.selectedOption().value;},_frameAdded:function(event)
1532 {var frame=(event.data);this._addFrame(frame);},_addFrame:function(frame)
1533 {var frameId=frame.id;var option=document.createElement("option");option.text=frame.displayName();option.title=frame.url;option.value=frameId;this._frameOptions[frameId]=option;if(this._framesWithCanvases[frameId]){this._frameSelector.addOption(option);this._dispatchViewUpdatedEvent();}},_frameRemoved:function(event)
1534 {var frame=(event.data);var frameId=frame.id;var option=this._frameOptions[frameId];if(option&&this._framesWithCanvases[frameId]){this._frameSelector.removeOption(option);this._dispatchViewUpdatedEvent();}
1535 delete this._frameOptions[frameId];delete this._framesWithCanvases[frameId];},_contextCreated:function(frameId)
1536 {if(this._framesWithCanvases[frameId])
1537 return;this._framesWithCanvases[frameId]=true;var option=this._frameOptions[frameId];if(option){this._frameSelector.addOption(option);this._dispatchViewUpdatedEvent();}},_traceLogsRemoved:function(frameId,traceLogId)
1538 {var sidebarElementsToDelete=[];var sidebarElements=((this.treeElement&&this.treeElement.children)||[]);for(var i=0,n=sidebarElements.length;i<n;++i){var header=(sidebarElements[i].profile);if(!header)
1539 continue;if(frameId&&frameId!==header.frameId())
1540 continue;if(traceLogId&&traceLogId!==header.traceLogId())
1541 continue;sidebarElementsToDelete.push(sidebarElements[i]);}
1542 for(var i=0,n=sidebarElementsToDelete.length;i<n;++i)
1543 sidebarElementsToDelete[i].ondelete();},_selectedFrameId:function()
1544 {var option=this._frameSelector.selectedOption();return option?option.value:undefined;},_dispatchViewUpdatedEvent:function()
1545 {this._frameSelector.element.classList.toggle("hidden",this._frameSelector.size()<=1);this.dispatchEventToListeners(WebInspector.ProfileType.Events.ViewUpdated);},isInstantProfile:function()
1546 {return this._isSingleFrameMode();},isEnabled:function()
1547 {return this._canvasAgentEnabled;},__proto__:WebInspector.ProfileType.prototype}
1548 WebInspector.CanvasDispatcher=function(profileType)
1549 {this._profileType=profileType;InspectorBackend.registerCanvasDispatcher(this);}
1550 WebInspector.CanvasDispatcher.prototype={contextCreated:function(frameId)
1551 {this._profileType._contextCreated(frameId);},traceLogsRemoved:function(frameId,traceLogId)
1552 {this._profileType._traceLogsRemoved(frameId,traceLogId);}}
1553 WebInspector.CanvasProfileHeader=function(type,traceLogId,frameId)
1554 {WebInspector.ProfileHeader.call(this,type,WebInspector.UIString("Trace Log %d",type._nextProfileUid));this._traceLogId=traceLogId||"";this._frameId=frameId;this._alive=true;this._traceLogSize=0;this._traceLogPlayer=traceLogId?new WebInspector.CanvasTraceLogPlayerProxy(traceLogId):null;}
1555 WebInspector.CanvasProfileHeader.prototype={traceLogId:function()
1556 {return this._traceLogId;},traceLogPlayer:function()
1557 {return this._traceLogPlayer;},frameId:function()
1558 {return this._frameId;},createSidebarTreeElement:function()
1559 {return new WebInspector.ProfileSidebarTreeElement(this,"profile-sidebar-tree-item");},createView:function()
1560 {return new WebInspector.CanvasProfileView(this);},dispose:function()
1561 {if(this._traceLogPlayer)
1562 this._traceLogPlayer.dispose();clearTimeout(this._requestStatusTimer);this._alive=false;},_updateCapturingStatus:function(traceLog)
1563 {if(!this._traceLogId)
1564 return;if(traceLog){this._alive=traceLog.alive;this._traceLogSize=traceLog.totalAvailableCalls;}
1565 var subtitle=this._alive?WebInspector.UIString("Capturing\u2026 %d calls",this._traceLogSize):WebInspector.UIString("Captured %d calls",this._traceLogSize);this.updateStatus(subtitle,this._alive);if(this._alive){clearTimeout(this._requestStatusTimer);this._requestStatusTimer=setTimeout(this._requestCapturingStatus.bind(this),WebInspector.CanvasProfileView.TraceLogPollingInterval);}},_requestCapturingStatus:function()
1566 {function didReceiveTraceLog(traceLog)
1567 {if(!traceLog)
1568 return;this._alive=traceLog.alive;this._traceLogSize=traceLog.totalAvailableCalls;this._updateCapturingStatus();}
1569 this._traceLogPlayer.getTraceLog(0,0,didReceiveTraceLog.bind(this));},__proto__:WebInspector.ProfileHeader.prototype}
1570 WebInspector.CanvasProfileDataGridHelper={createCallArgumentElement:function(callArgument)
1571 {if(callArgument.enumName)
1572 return WebInspector.CanvasProfileDataGridHelper.createEnumValueElement(callArgument.enumName,+callArgument.description);var element=document.createElement("span");element.className="canvas-call-argument";var description=callArgument.description;if(callArgument.type==="string"){const maxStringLength=150;element.createTextChild("\"");element.createChild("span","canvas-formatted-string").textContent=description.trimMiddle(maxStringLength);element.createTextChild("\"");element.__suppressPopover=(description.length<=maxStringLength&&!/[\r\n]/.test(description));if(!element.__suppressPopover)
1573 element.__evalResult=WebInspector.RemoteObject.fromPrimitiveValue(description);}else{var type=callArgument.subtype||callArgument.type;if(type){element.classList.add("canvas-formatted-"+type);if(["null","undefined","boolean","number"].indexOf(type)>=0)
1574 element.__suppressPopover=true;}
1575 element.textContent=description;if(callArgument.remoteObject)
1576 element.__evalResult=WebInspector.RemoteObject.fromPayload(callArgument.remoteObject);}
1577 if(callArgument.resourceId){element.classList.add("canvas-formatted-resource");element.__resourceId=callArgument.resourceId;}
1578 return element;},createEnumValueElement:function(enumName,enumValue)
1579 {var element=document.createElement("span");element.className="canvas-call-argument canvas-formatted-number";element.textContent=enumName;element.__evalResult=WebInspector.RemoteObject.fromPrimitiveValue(enumValue);return element;}}
1580 WebInspector.CanvasTraceLogPlayerProxy=function(traceLogId)
1581 {this._traceLogId=traceLogId;this._currentResourceStates={};this._defaultResourceId=null;}
1582 WebInspector.CanvasTraceLogPlayerProxy.Events={CanvasTraceLogReceived:"CanvasTraceLogReceived",CanvasReplayStateChanged:"CanvasReplayStateChanged",CanvasResourceStateReceived:"CanvasResourceStateReceived",}
1583 WebInspector.CanvasTraceLogPlayerProxy.prototype={getTraceLog:function(startOffset,maxLength,userCallback)
1584 {function callback(error,traceLog)
1585 {if(error||!traceLog){userCallback(null);return;}
1586 userCallback(traceLog);this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasTraceLogReceived,traceLog);}
1587 CanvasAgent.getTraceLog(this._traceLogId,startOffset,maxLength,callback.bind(this));},dispose:function()
1588 {this._currentResourceStates={};CanvasAgent.dropTraceLog(this._traceLogId);this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);},getResourceState:function(resourceId,userCallback)
1589 {resourceId=resourceId||this._defaultResourceId;if(!resourceId){userCallback(null);return;}
1590 var effectiveResourceId=(resourceId);if(this._currentResourceStates[effectiveResourceId]){userCallback(this._currentResourceStates[effectiveResourceId]);return;}
1591 function callback(error,resourceState)
1592 {if(error||!resourceState){userCallback(null);return;}
1593 this._currentResourceStates[effectiveResourceId]=resourceState;userCallback(resourceState);this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived,resourceState);}
1594 CanvasAgent.getResourceState(this._traceLogId,effectiveResourceId,callback.bind(this));},replayTraceLog:function(index,userCallback)
1595 {function callback(error,resourceState,replayTime)
1596 {this._currentResourceStates={};if(error){userCallback(null,replayTime);}else{this._defaultResourceId=resourceState.id;this._currentResourceStates[resourceState.id]=resourceState;userCallback(resourceState,replayTime);}
1597 this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);if(!error)
1598 this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived,resourceState);}
1599 CanvasAgent.replayTraceLog(this._traceLogId,index,callback.bind(this));},clearResourceStates:function()
1600 {this._currentResourceStates={};this.dispatchEventToListeners(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged);},__proto__:WebInspector.Object.prototype};WebInspector.CanvasReplayStateView=function(traceLogPlayer)
1601 {WebInspector.VBox.call(this);this.registerRequiredCSS("canvasProfiler.css");this.element.classList.add("canvas-replay-state-view");this._traceLogPlayer=traceLogPlayer;var controlsContainer=this.element.createChild("div","status-bar");this._prevButton=this._createControlButton(controlsContainer,"canvas-replay-state-prev",WebInspector.UIString("Previous resource."),this._onResourceNavigationClick.bind(this,false));this._nextButton=this._createControlButton(controlsContainer,"canvas-replay-state-next",WebInspector.UIString("Next resource."),this._onResourceNavigationClick.bind(this,true));this._createControlButton(controlsContainer,"canvas-replay-state-refresh",WebInspector.UIString("Refresh."),this._onStateRefreshClick.bind(this));this._resourceSelector=new WebInspector.StatusBarComboBox(this._onReplayResourceChanged.bind(this));this._currentOption=this._resourceSelector.createOption(WebInspector.UIString("<auto>"),WebInspector.UIString("Show state of the last replayed resource."),"");controlsContainer.appendChild(this._resourceSelector.element);this._resourceIdToDescription={};this._gridNodesExpandedState={};this._gridScrollPositions={};this._currentResourceId=null;this._prevOptionsStack=[];this._nextOptionsStack=[];this._highlightedGridNodes=[];var columns=[{title:WebInspector.UIString("Name"),sortable:false,width:"50%",disclosure:true},{title:WebInspector.UIString("Value"),sortable:false,width:"50%"}];this._stateGrid=new WebInspector.DataGrid(columns);this._stateGrid.element.classList.add("fill");this._stateGrid.show(this.element);this._traceLogPlayer.addEventListener(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasReplayStateChanged,this._onReplayResourceChanged,this);this._traceLogPlayer.addEventListener(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasTraceLogReceived,this._onCanvasTraceLogReceived,this);this._traceLogPlayer.addEventListener(WebInspector.CanvasTraceLogPlayerProxy.Events.CanvasResourceStateReceived,this._onCanvasResourceStateReceived,this);this._updateButtonsEnabledState();}
1602 WebInspector.CanvasReplayStateView.prototype={selectResource:function(resourceId)
1603 {if(resourceId===this._resourceSelector.selectedOption().value)
1604 return;var option=this._resourceSelector.selectElement().firstChild;for(var index=0;option;++index,option=option.nextSibling){if(resourceId===option.value){this._resourceSelector.setSelectedIndex(index);this._onReplayResourceChanged();break;}}},_createControlButton:function(parent,className,title,clickCallback)
1605 {var button=new WebInspector.StatusBarButton(title,className+" canvas-replay-button");parent.appendChild(button.element);button.makeLongClickEnabled();button.addEventListener("click",clickCallback,this);button.addEventListener("longClickDown",clickCallback,this);button.addEventListener("longClickPress",clickCallback,this);return button;},_onResourceNavigationClick:function(forward)
1606 {var newOption=forward?this._nextOptionsStack.pop():this._prevOptionsStack.pop();if(!newOption)
1607 return;(forward?this._prevOptionsStack:this._nextOptionsStack).push(this._currentOption);this._isNavigationButton=true;this.selectResource(newOption.value);delete this._isNavigationButton;this._updateButtonsEnabledState();},_onStateRefreshClick:function()
1608 {this._traceLogPlayer.clearResourceStates();},_updateButtonsEnabledState:function()
1609 {this._prevButton.setEnabled(this._prevOptionsStack.length>0);this._nextButton.setEnabled(this._nextOptionsStack.length>0);},_updateCurrentOption:function()
1610 {const maxStackSize=256;var selectedOption=this._resourceSelector.selectedOption();if(this._currentOption===selectedOption)
1611 return;if(!this._isNavigationButton){this._prevOptionsStack.push(this._currentOption);this._nextOptionsStack=[];if(this._prevOptionsStack.length>maxStackSize)
1612 this._prevOptionsStack.shift();this._updateButtonsEnabledState();}
1613 this._currentOption=selectedOption;},_collectResourcesFromTraceLog:function(traceLog)
1614 {var collectedResources=[];var calls=traceLog.calls;for(var i=0,n=calls.length;i<n;++i){var call=calls[i];var args=call.arguments||[];for(var j=0;j<args.length;++j)
1615 this._collectResourceFromCallArgument(args[j],collectedResources);this._collectResourceFromCallArgument(call.result,collectedResources);this._collectResourceFromCallArgument(call.value,collectedResources);}
1616 var contexts=traceLog.contexts;for(var i=0,n=contexts.length;i<n;++i)
1617 this._collectResourceFromCallArgument(contexts[i],collectedResources);this._addCollectedResourcesToSelector(collectedResources);},_collectResourcesFromResourceState:function(resourceState)
1618 {var collectedResources=[];this._collectResourceFromResourceStateDescriptors(resourceState.descriptors,collectedResources);this._addCollectedResourcesToSelector(collectedResources);},_collectResourceFromResourceStateDescriptors:function(descriptors,output)
1619 {if(!descriptors)
1620 return;for(var i=0,n=descriptors.length;i<n;++i){var descriptor=descriptors[i];this._collectResourceFromCallArgument(descriptor.value,output);this._collectResourceFromResourceStateDescriptors(descriptor.values,output);}},_collectResourceFromCallArgument:function(argument,output)
1621 {if(!argument)
1622 return;var resourceId=argument.resourceId;if(!resourceId||this._resourceIdToDescription[resourceId])
1623 return;this._resourceIdToDescription[resourceId]=argument.description;output.push(argument);},_addCollectedResourcesToSelector:function(collectedResources)
1624 {if(!collectedResources.length)
1625 return;function comparator(arg1,arg2)
1626 {var a=arg1.description;var b=arg2.description;return String.naturalOrderComparator(a,b);}
1627 collectedResources.sort(comparator);var selectElement=this._resourceSelector.selectElement();var currentOption=selectElement.firstChild;currentOption=currentOption.nextSibling;for(var i=0,n=collectedResources.length;i<n;++i){var argument=collectedResources[i];while(currentOption&&String.naturalOrderComparator(currentOption.text,argument.description)<0)
1628 currentOption=currentOption.nextSibling;var option=this._resourceSelector.createOption(argument.description,WebInspector.UIString("Show state of this resource."),argument.resourceId);if(currentOption)
1629 selectElement.insertBefore(option,currentOption);}},_onReplayResourceChanged:function()
1630 {this._updateCurrentOption();var selectedResourceId=this._resourceSelector.selectedOption().value;function didReceiveResourceState(resourceState)
1631 {if(selectedResourceId!==this._resourceSelector.selectedOption().value)
1632 return;this._showResourceState(resourceState);}
1633 this._traceLogPlayer.getResourceState(selectedResourceId,didReceiveResourceState.bind(this));},_onCanvasTraceLogReceived:function(event)
1634 {var traceLog=(event.data);console.assert(traceLog);this._collectResourcesFromTraceLog(traceLog);},_onCanvasResourceStateReceived:function(event)
1635 {var resourceState=(event.data);console.assert(resourceState);this._collectResourcesFromResourceState(resourceState);},_showResourceState:function(resourceState)
1636 {this._saveExpandedState();this._saveScrollState();var rootNode=this._stateGrid.rootNode();if(!resourceState){this._currentResourceId=null;this._updateDataGridHighlights([]);rootNode.removeChildren();return;}
1637 var nodesToHighlight=[];var nameToOldGridNodes={};function populateNameToNodesMap(map,node)
1638 {if(!node)
1639 return;for(var i=0,child;child=node.children[i];++i){var item={node:child,children:{}};map[child.name]=item;populateNameToNodesMap(item.children,child);}}
1640 populateNameToNodesMap(nameToOldGridNodes,rootNode);rootNode.removeChildren();function comparator(d1,d2)
1641 {var hasChildren1=!!d1.values;var hasChildren2=!!d2.values;if(hasChildren1!==hasChildren2)
1642 return hasChildren1?1:-1;return String.naturalOrderComparator(d1.name,d2.name);}
1643 function appendResourceStateDescriptors(descriptors,parent,nameToOldChildren)
1644 {descriptors=descriptors||[];descriptors.sort(comparator);var oldChildren=nameToOldChildren||{};for(var i=0,n=descriptors.length;i<n;++i){var descriptor=descriptors[i];var childNode=this._createDataGridNode(descriptor);parent.appendChild(childNode);var oldChildrenItem=oldChildren[childNode.name]||{};var oldChildNode=oldChildrenItem.node;if(!oldChildNode||oldChildNode.element.textContent!==childNode.element.textContent)
1645 nodesToHighlight.push(childNode);appendResourceStateDescriptors.call(this,descriptor.values,childNode,oldChildrenItem.children);}}
1646 appendResourceStateDescriptors.call(this,resourceState.descriptors,rootNode,nameToOldGridNodes);var shouldHighlightChanges=(this._resourceKindId(this._currentResourceId)===this._resourceKindId(resourceState.id));this._currentResourceId=resourceState.id;this._restoreExpandedState();this._updateDataGridHighlights(shouldHighlightChanges?nodesToHighlight:[]);this._restoreScrollState();},_updateDataGridHighlights:function(nodes)
1647 {for(var i=0,n=this._highlightedGridNodes.length;i<n;++i)
1648 this._highlightedGridNodes[i].element.classList.remove("canvas-grid-node-highlighted");this._highlightedGridNodes=nodes;for(var i=0,n=this._highlightedGridNodes.length;i<n;++i){var node=this._highlightedGridNodes[i];WebInspector.runCSSAnimationOnce(node.element,"canvas-grid-node-highlighted");node.reveal();}},_resourceKindId:function(resourceId)
1649 {var description=(resourceId&&this._resourceIdToDescription[resourceId])||"";return description.replace(/\d+/g,"");},_forEachGridNode:function(callback)
1650 {function processRecursively(node,key)
1651 {for(var i=0,child;child=node.children[i];++i){var childKey=key+"#"+child.name;callback(child,childKey);processRecursively(child,childKey);}}
1652 processRecursively(this._stateGrid.rootNode(),"");},_saveExpandedState:function()
1653 {if(!this._currentResourceId)
1654 return;var expandedState={};var key=this._resourceKindId(this._currentResourceId);this._gridNodesExpandedState[key]=expandedState;function callback(node,key)
1655 {if(node.expanded)
1656 expandedState[key]=true;}
1657 this._forEachGridNode(callback);},_restoreExpandedState:function()
1658 {if(!this._currentResourceId)
1659 return;var key=this._resourceKindId(this._currentResourceId);var expandedState=this._gridNodesExpandedState[key];if(!expandedState)
1660 return;function callback(node,key)
1661 {if(expandedState[key])
1662 node.expand();}
1663 this._forEachGridNode(callback);},_saveScrollState:function()
1664 {if(!this._currentResourceId)
1665 return;var key=this._resourceKindId(this._currentResourceId);this._gridScrollPositions[key]={scrollTop:this._stateGrid.scrollContainer.scrollTop,scrollLeft:this._stateGrid.scrollContainer.scrollLeft};},_restoreScrollState:function()
1666 {if(!this._currentResourceId)
1667 return;var key=this._resourceKindId(this._currentResourceId);var scrollState=this._gridScrollPositions[key];if(!scrollState)
1668 return;this._stateGrid.scrollContainer.scrollTop=scrollState.scrollTop;this._stateGrid.scrollContainer.scrollLeft=scrollState.scrollLeft;},_createDataGridNode:function(descriptor)
1669 {var name=descriptor.name;var callArgument=descriptor.value;var valueElement=callArgument?WebInspector.CanvasProfileDataGridHelper.createCallArgumentElement(callArgument):"";var nameElement=name;if(typeof descriptor.enumValueForName!=="undefined")
1670 nameElement=WebInspector.CanvasProfileDataGridHelper.createEnumValueElement(name,+descriptor.enumValueForName);if(descriptor.isArray&&descriptor.values){if(typeof nameElement==="string")
1671 nameElement+="["+descriptor.values.length+"]";else{var element=document.createElement("span");element.appendChild(nameElement);element.createTextChild("["+descriptor.values.length+"]");nameElement=element;}}
1672 var data={};data[0]=nameElement;data[1]=valueElement;var node=new WebInspector.DataGridNode(data);node.selectable=false;node.name=name;return node;},__proto__:WebInspector.VBox.prototype};WebInspector.PieChart=function(totalValue,formatter)
1673 {const shadowOffset=0.04;this.element=document.createElementWithClass("div","pie-chart");var svg=this._createSVGChild(this.element,"svg");svg.setAttribute("width","100%");svg.setAttribute("height",(100*(1+shadowOffset))+"%");this._group=this._createSVGChild(svg,"g");var shadow=this._createSVGChild(this._group,"circle");shadow.setAttribute("r",1);shadow.setAttribute("cy",shadowOffset);shadow.setAttribute("fill","hsl(0,0%,70%)");var background=this._createSVGChild(this._group,"circle");background.setAttribute("r",1);background.setAttribute("fill","hsl(0,0%,92%)");if(totalValue){var totalString=formatter?formatter(totalValue):totalValue;this._totalElement=this.element.createChild("div","pie-chart-foreground");this._totalElement.textContent=totalString;this._totalValue=totalValue;}
1674 this._lastAngle=-Math.PI/2;this.setSize(100);}
1675 WebInspector.PieChart.prototype={setTotal:function(value)
1676 {this._totalValue=value;},setSize:function(value)
1677 {this._group.setAttribute("transform","scale("+(value/2)+") translate(1,1)");var size=value+"px";this.element.style.width=size;this.element.style.height=size;if(this._totalElement)
1678 this._totalElement.style.lineHeight=size;},addSlice:function(value,color)
1679 {var sliceAngle=value/this._totalValue*2*Math.PI;if(!isFinite(sliceAngle))
1680 return;sliceAngle=Math.min(sliceAngle,2*Math.PI*0.9999);var path=this._createSVGChild(this._group,"path");var x1=Math.cos(this._lastAngle);var y1=Math.sin(this._lastAngle);this._lastAngle+=sliceAngle;var x2=Math.cos(this._lastAngle);var y2=Math.sin(this._lastAngle);var largeArc=sliceAngle>Math.PI?1:0;path.setAttribute("d","M0,0 L"+x1+","+y1+" A1,1,0,"+largeArc+",1,"+x2+","+y2+" Z");path.setAttribute("fill",color);},_createSVGChild:function(parent,childType)
1681 {var child=document.createElementNS("http://www.w3.org/2000/svg",childType);parent.appendChild(child);return child;}};WebInspector.ProfileTypeRegistry.instance=new WebInspector.ProfileTypeRegistry();