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