@yuebai008/cli
Version:
Command line interface for rapid qg-minigame development
1 lines • 38.4 kB
JavaScript
import*as Common from"../../core/common/common.js";import*as Host from"../../core/host/host.js";import*as i18n from"../../core/i18n/i18n.js";import*as Platform from"../../core/platform/platform.js";import*as Root from"../../core/root/root.js";import*as SDK from"../../core/sdk/sdk.js";import*as Bindings from"../../models/bindings/bindings.js";import*as HeapSnapshotModel from"../../models/heap_snapshot_model/heap_snapshot_model.js";import*as DataGrid from"../../ui/legacy/components/data_grid/data_grid.js";import*as ObjectUI from"../../ui/legacy/components/object_ui/object_ui.js";import*as PerfUI from"../../ui/legacy/components/perf_ui/perf_ui.js";import*as Components from"../../ui/legacy/components/utils/utils.js";import*as UI from"../../ui/legacy/legacy.js";import{AllocationDataGrid,HeapSnapshotSortableDataGridEvents,HeapSnapshotConstructorsDataGrid,HeapSnapshotDiffDataGrid,HeapSnapshotRetainmentDataGrid,HeapSnapshotContainmentDataGrid}from"./HeapSnapshotDataGrids.js";import{HeapSnapshotGenericObjectNode}from"./HeapSnapshotGridNodes.js";import{HeapSnapshotWorkerProxy}from"./HeapSnapshotProxy.js";import{HeapTimelineOverview,Samples}from"./HeapTimelineOverview.js";import*as ModuleUIStrings from"./ModuleUIStrings.js";import{Events as ProfileHeaderEvents,ProfileEvents as ProfileTypeEvents,ProfileHeader,ProfileType}from"./ProfileHeader.js";import{ProfileSidebarTreeElement}from"./ProfileSidebarTreeElement.js";import{instance}from"./ProfileTypeRegistry.js";const UIStrings={find:"Find",containment:"Containment",retainers:"Retainers",allocationStack:"Allocation stack",perspective:"Perspective",baseSnapshot:"Base snapshot",filter:"Filter",classFilter:"Class filter",code:"Code",strings:"Strings",jsArrays:"JS arrays",typedArrays:"Typed arrays",systemObjects:"System objects",selectedSizeS:"Selected size: {PH1}",allObjects:"All objects",objectsAllocatedBeforeS:"Objects allocated before {PH1}",objectsAllocatedBetweenSAndS:"Objects allocated between {PH1} and {PH2}",summary:"Summary",comparison:"Comparison",allocation:"Allocation",liveObjects:"Live objects",statistics:"Statistics",heapSnapshot:"Heap snapshot",takeHeapSnapshot:"Take heap snapshot",heapSnapshots:"HEAP SNAPSHOTS",heapSnapshotProfilesShowMemory:"Heap snapshot profiles show memory distribution among your page's JavaScript objects and related DOM nodes.",exposeInternals:"Expose internals (includes additional implementation-specific details)",captureNumericValue:"Include numerical values in capture",snapshotting:"Snapshotting…",snapshotD:"Snapshot {PH1}",percentagePlaceholder:"{PH1}%",allocationInstrumentationOn:"Allocation instrumentation on timeline",stopRecordingHeapProfile:"Stop recording heap profile",startRecordingHeapProfile:"Start recording heap profile",recordAllocationStacksExtra:"Record stack traces of allocations (extra performance overhead)",recording:"Recording…",allocationTimelines:"ALLOCATION TIMELINES",AllocationTimelinesShowInstrumented:"Allocation timelines show instrumented JavaScript memory allocations over time. Once profile is recorded you can select a time interval to see objects that were allocated within it and still alive by the end of recording. Use this profile type to isolate memory leaks.",loading:"Loading…",savingD:"Saving… {PH1}%",sKb:"{PH1} kB",heapMemoryUsage:"Heap memory usage",stackWasNotRecordedForThisObject:"Stack was not recorded for this object because it had been allocated before this profile recording started."},str_=i18n.i18n.registerUIStrings("panels/profiler/HeapSnapshotView.ts",UIStrings),i18nString=i18n.i18n.getLocalizedString.bind(void 0,str_),moduleUIstr_=i18n.i18n.registerUIStrings("panels/profiler/ModuleUIStrings.ts",ModuleUIStrings.UIStrings),moduleI18nString=i18n.i18n.getLocalizedString.bind(void 0,moduleUIstr_);export class HeapSnapshotView extends UI.View.SimpleView{searchResults;profile;linkifier;parentDataDisplayDelegate;searchableViewInternal;splitWidget;containmentDataGrid;containmentWidget;statisticsView;constructorsDataGrid;constructorsWidget;diffDataGrid;diffWidget;allocationDataGrid;allocationWidget;allocationStackView;tabbedPane;retainmentDataGrid;retainmentWidget;objectDetailsView;perspectives;comparisonPerspective;perspectiveSelect;baseSelect;filterSelect;classNameFilter;selectedSizeText;popoverHelper;currentPerspectiveIndex;currentPerspective;dataGrid;searchThrottler;baseProfile;trackingOverviewGrid;currentSearchResultIndex=-1;currentQuery;constructor(e,t){super(i18nString(UIStrings.heapSnapshot)),this.searchResults=[],this.element.classList.add("heap-snapshot-view"),this.profile=t,this.linkifier=new Components.Linkifier.Linkifier;const i=t.profileType();i.addEventListener("SnapshotReceived",this.onReceiveSnapshot,this),i.addEventListener(ProfileTypeEvents.RemoveProfileHeader,this.onProfileHeaderRemoved,this);const s=i.id===TrackingHeapSnapshotProfileType.TypeId;s&&this.createOverview();const r=instance.trackingHeapSnapshotProfileType.recordAllocationStacksSetting().get();this.parentDataDisplayDelegate=e,this.searchableViewInternal=new UI.SearchableView.SearchableView(this,null),this.searchableViewInternal.setPlaceholder(i18nString(UIStrings.find),i18nString(UIStrings.find)),this.searchableViewInternal.show(this.element),this.splitWidget=new UI.SplitWidget.SplitWidget(!1,!0,"heapSnapshotSplitViewState",200,200),this.splitWidget.show(this.searchableViewInternal.element);const a=t.heapProfilerModel();let n;if(this.containmentDataGrid=new HeapSnapshotContainmentDataGrid(a,this,i18nString(UIStrings.containment)),this.containmentDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this.selectionChanged,this),this.containmentWidget=this.containmentDataGrid.asWidget(),this.containmentWidget.setMinimumSize(50,25),this.statisticsView=new HeapSnapshotStatisticsView,this.constructorsDataGrid=new HeapSnapshotConstructorsDataGrid(a,this),this.constructorsDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this.selectionChanged,this),this.constructorsWidget=this.constructorsDataGrid.asWidget(),this.constructorsWidget.setMinimumSize(50,25),this.diffDataGrid=new HeapSnapshotDiffDataGrid(a,this),this.diffDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this.selectionChanged,this),this.diffWidget=this.diffDataGrid.asWidget(),this.diffWidget.setMinimumSize(50,25),this.allocationDataGrid=null,s&&r&&(this.allocationDataGrid=new AllocationDataGrid(a,this),this.allocationDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this.onSelectAllocationNode,this),this.allocationWidget=this.allocationDataGrid.asWidget(),this.allocationWidget.setMinimumSize(50,25),this.allocationStackView=new HeapAllocationStackView(a),this.allocationStackView.setMinimumSize(50,25),this.tabbedPane=new UI.TabbedPane.TabbedPane),this.retainmentDataGrid=new HeapSnapshotRetainmentDataGrid(a,this),this.retainmentWidget=this.retainmentDataGrid.asWidget(),this.retainmentWidget.setMinimumSize(50,21),this.retainmentWidget.element.classList.add("retaining-paths-view"),this.allocationStackView)this.tabbedPane=new UI.TabbedPane.TabbedPane,this.tabbedPane.appendTab("retainers",i18nString(UIStrings.retainers),this.retainmentWidget),this.tabbedPane.appendTab("allocation-stack",i18nString(UIStrings.allocationStack),this.allocationStackView),n=this.tabbedPane.headerElement(),this.objectDetailsView=this.tabbedPane;else{const e=document.createElement("div");e.classList.add("heap-snapshot-view-resizer");const t=e.createChild("div","title");e.createChild("div","verticalResizerIcon");t.createChild("span").textContent=i18nString(UIStrings.retainers),n=e,this.objectDetailsView=new UI.Widget.VBox,this.objectDetailsView.element.appendChild(e),this.retainmentWidget.show(this.objectDetailsView.element)}this.splitWidget.hideDefaultResizer(),this.splitWidget.installResizer(n),this.retainmentDataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this.inspectedObjectChanged,this),this.retainmentDataGrid.reset(),this.perspectives=[],this.comparisonPerspective=new ComparisonPerspective,this.perspectives.push(new SummaryPerspective),t.profileType()!==instance.trackingHeapSnapshotProfileType&&this.perspectives.push(this.comparisonPerspective),this.perspectives.push(new ContainmentPerspective),this.allocationWidget&&this.perspectives.push(new AllocationPerspective),this.perspectives.push(new StatisticsPerspective),this.perspectiveSelect=new UI.Toolbar.ToolbarComboBox(this.onSelectedPerspectiveChanged.bind(this),i18nString(UIStrings.perspective)),this.updatePerspectiveOptions(),this.baseSelect=new UI.Toolbar.ToolbarComboBox(this.changeBase.bind(this),i18nString(UIStrings.baseSnapshot)),this.baseSelect.setVisible(!1),this.updateBaseOptions(),this.filterSelect=new UI.Toolbar.ToolbarComboBox(this.changeFilter.bind(this),i18nString(UIStrings.filter)),this.filterSelect.setVisible(!1),this.updateFilterOptions(),this.classNameFilter=new UI.Toolbar.ToolbarInput(i18nString(UIStrings.classFilter)),this.classNameFilter.setVisible(!1),this.constructorsDataGrid.setNameFilter(this.classNameFilter),this.diffDataGrid.setNameFilter(this.classNameFilter),this.selectedSizeText=new UI.Toolbar.ToolbarText,this.popoverHelper=new UI.PopoverHelper.PopoverHelper(this.element,this.getPopoverRequest.bind(this)),this.popoverHelper.setDisableOnClick(!0),this.popoverHelper.setHasPadding(!0),this.element.addEventListener("scroll",this.popoverHelper.hidePopover.bind(this.popoverHelper),!0),this.currentPerspectiveIndex=0,this.currentPerspective=this.perspectives[0],this.currentPerspective.activate(this),this.dataGrid=this.currentPerspective.masterGrid(this),this.populate(),this.searchThrottler=new Common.Throttler.Throttler(0);for(const e of this.profiles())e.addEventListener(ProfileHeaderEvents.ProfileTitleChanged,this.updateControls,this)}createOverview(){const e=this.profile.profileType();this.trackingOverviewGrid=new HeapTimelineOverview,this.trackingOverviewGrid.addEventListener("IdsRangeChanged",this.onIdsRangeChanged.bind(this)),this.profile.fromFile()||e.profileBeingRecorded()!==this.profile||(e.addEventListener("HeapStatsUpdate",this.onHeapStatsUpdate,this),e.addEventListener("TrackingStopped",this.onStopTracking,this),this.trackingOverviewGrid.start())}onStopTracking(){const e=this.profile.profileType();e.removeEventListener("HeapStatsUpdate",this.onHeapStatsUpdate,this),e.removeEventListener("TrackingStopped",this.onStopTracking,this),this.trackingOverviewGrid&&this.trackingOverviewGrid.stop()}onHeapStatsUpdate({data:e}){this.trackingOverviewGrid&&this.trackingOverviewGrid.setSamples(e)}searchableView(){return this.searchableViewInternal}showProfile(e){return this.parentDataDisplayDelegate.showProfile(e)}showObject(e,t){Number(e)<=this.profile.maxJSObjectId?this.selectLiveObject(t,e):this.parentDataDisplayDelegate.showObject(e,t)}async linkifyObject(e){const t=this.profile.heapProfilerModel();if(!t)return null;const i=await this.profile.getLocation(e);if(!i)return null;const s=t.runtimeModel().debuggerModel().createRawLocationByScriptId(String(i.scriptId),i.lineNumber,i.columnNumber);if(!s)return null;const r=s.script(),a=r&&r.sourceURL;return a&&this.linkifier?this.linkifier.linkifyRawLocation(s,a):null}async populate(){const e=await this.profile.loadPromise;if(this.retrieveStatistics(e),this.dataGrid&&this.dataGrid.setDataSource(e,0),this.profile.profileType().id===TrackingHeapSnapshotProfileType.TypeId&&this.profile.fromFile()){const t=await e.getSamples();if(t){console.assert(Boolean(t.timestamps.length));const e=new Samples;e.sizes=t.sizes,e.ids=t.lastAssignedIds,e.timestamps=t.timestamps,e.max=t.sizes,e.totalTime=Math.max(t.timestamps[t.timestamps.length-1]||0,1e4),this.trackingOverviewGrid&&this.trackingOverviewGrid.setSamples(e)}}const t=this.profiles().indexOf(this.profile);this.baseSelect.setSelectedIndex(Math.max(0,t-1)),this.trackingOverviewGrid&&this.trackingOverviewGrid.updateGrid()}async retrieveStatistics(e){const t=await e.getStatistics(),i=[{value:t.code,color:"#f77",title:i18nString(UIStrings.code)},{value:t.strings,color:"#5e5",title:i18nString(UIStrings.strings)},{value:t.jsArrays,color:"#7af",title:i18nString(UIStrings.jsArrays)},{value:t.native,color:"#fc5",title:i18nString(UIStrings.typedArrays)},{value:t.system,color:"#98f",title:i18nString(UIStrings.systemObjects)}];return this.statisticsView.setTotalAndRecords(t.total,i),t}onIdsRangeChanged(e){const{minId:t,maxId:i}=e.data;this.selectedSizeText.setText(i18nString(UIStrings.selectedSizeS,{PH1:Platform.NumberUtilities.bytesToString(e.data.size)})),this.constructorsDataGrid.snapshot&&this.constructorsDataGrid.setSelectionRange(t,i)}async toolbarItems(){const e=[this.perspectiveSelect,this.classNameFilter];return this.profile.profileType()!==instance.trackingHeapSnapshotProfileType&&e.push(this.baseSelect,this.filterSelect),e.push(this.selectedSizeText),e}willHide(){this.currentSearchResultIndex=-1,this.popoverHelper.hidePopover()}supportsCaseSensitiveSearch(){return!0}supportsRegexSearch(){return!1}onSearchCanceled(){this.currentSearchResultIndex=-1,this.searchResults=[]}selectRevealedNode(e){e&&e.select()}performSearch(e,t,i){const s=new HeapSnapshotModel.HeapSnapshotModel.SearchConfig(e.query.trim(),e.caseSensitive,e.isRegex,t,i||!1);this.searchThrottler.schedule(this.performSearchInternal.bind(this,s))}async performSearchInternal(e){if(this.onSearchCanceled(),!this.currentPerspective.supportsSearch())return;this.currentQuery=e;const t=e.query.trim();if(!t)return;if("@"===t.charAt(0)){const e=parseInt(t.substring(1),10);if(isNaN(e))return;if(!this.dataGrid)return;const i=await this.dataGrid.revealObjectByHeapSnapshotId(String(e));return void this.selectRevealedNode(i)}if(!this.profile.snapshotProxy||!this.dataGrid)return;const i=this.dataGrid.nodeFilter();this.searchResults=i?await this.profile.snapshotProxy.search(this.currentQuery,i):[],this.searchableViewInternal.updateSearchMatchesCount(this.searchResults.length),this.searchResults.length&&(this.currentSearchResultIndex=e.jumpBackward?this.searchResults.length-1:0),await this.jumpToSearchResult(this.currentSearchResultIndex)}jumpToNextSearchResult(){this.searchResults.length&&(this.currentSearchResultIndex=(this.currentSearchResultIndex+1)%this.searchResults.length,this.searchThrottler.schedule(this.jumpToSearchResult.bind(this,this.currentSearchResultIndex)))}jumpToPreviousSearchResult(){this.searchResults.length&&(this.currentSearchResultIndex=(this.currentSearchResultIndex+this.searchResults.length-1)%this.searchResults.length,this.searchThrottler.schedule(this.jumpToSearchResult.bind(this,this.currentSearchResultIndex)))}async jumpToSearchResult(e){if(this.searchableViewInternal.updateCurrentMatchIndex(e),-1===e)return;if(!this.dataGrid)return;const t=await this.dataGrid.revealObjectByHeapSnapshotId(String(this.searchResults[e]));this.selectRevealedNode(t)}refreshVisibleData(){if(!this.dataGrid)return;let e=this.dataGrid.rootNode().children[0];for(;e;)e.refresh(),e=e.traverseNextNode(!1,null,!0)}changeBase(){if(this.baseProfile===this.profiles()[this.baseSelect.selectedIndex()])return;this.baseProfile=this.profiles()[this.baseSelect.selectedIndex()];const e=this.dataGrid;e.snapshot&&this.baseProfile.loadPromise.then(e.setBaseDataSource.bind(e)),this.currentQuery&&this.searchResults&&this.performSearch(this.currentQuery,!1)}changeFilter(){const e=this.filterSelect.selectedIndex()-1;this.dataGrid&&(this.dataGrid.filterSelectIndexChanged(this.profiles(),e),this.currentQuery&&this.searchResults&&this.performSearch(this.currentQuery,!1))}profiles(){return this.profile.profileType().getProfiles()}selectionChanged(e){const t=e.data;this.setSelectedNodeForDetailsView(t),this.inspectedObjectChanged(e)}onSelectAllocationNode(e){const t=e.data;this.constructorsDataGrid.setAllocationNodeId(t.allocationNodeId()),this.setSelectedNodeForDetailsView(null)}inspectedObjectChanged(e){const t=e.data,i=this.profile.heapProfilerModel();i&&t instanceof HeapSnapshotGenericObjectNode&&i.addInspectedHeapObject(String(t.snapshotNodeId))}setSelectedNodeForDetailsView(e){const t=e&&e.retainersDataSource();t?(this.retainmentDataGrid.setDataSource(t.snapshot,t.snapshotNodeIndex),this.allocationStackView&&this.allocationStackView.setAllocatedObject(t.snapshot,t.snapshotNodeIndex)):(this.allocationStackView&&this.allocationStackView.clear(),this.retainmentDataGrid.reset())}async changePerspectiveAndWait(e){const t=this.perspectives.findIndex((t=>t.title()===e));if(-1===t||this.currentPerspectiveIndex===t)return;const i=this.perspectives[t].masterGrid(this);if(!i)return;const s=i.once(HeapSnapshotSortableDataGridEvents.ContentShown),r=this.perspectiveSelect.options().find((e=>e.value===String(t)));this.perspectiveSelect.select(r),this.changePerspective(t),await s}async updateDataSourceAndView(){const e=this.dataGrid;if(!e||e.snapshot)return;const t=await this.profile.loadPromise;if(this.dataGrid!==e)return;if(e.snapshot!==t&&e.setDataSource(t,0),e!==this.diffDataGrid)return;this.baseProfile||(this.baseProfile=this.profiles()[this.baseSelect.selectedIndex()]);const i=await this.baseProfile.loadPromise;this.diffDataGrid.baseSnapshot!==i&&this.diffDataGrid.setBaseDataSource(i)}onSelectedPerspectiveChanged(e){this.changePerspective(Number(e.target.selectedOptions[0].value))}changePerspective(e){if(e===this.currentPerspectiveIndex)return;this.currentPerspectiveIndex=e,this.currentPerspective.deactivate(this);const t=this.perspectives[e];this.currentPerspective=t,this.dataGrid=t.masterGrid(this),t.activate(this),this.refreshVisibleData(),this.dataGrid&&this.dataGrid.updateWidths(),this.updateDataSourceAndView(),this.currentQuery&&this.searchResults&&this.performSearch(this.currentQuery,!1)}async selectLiveObject(e,t){if(await this.changePerspectiveAndWait(e),!this.dataGrid)return;const i=await this.dataGrid.revealObjectByHeapSnapshotId(t);i?i.select():Common.Console.Console.instance().error("Cannot find corresponding heap snapshot node")}getPopoverRequest(e){const t=UI.UIUtils.enclosingNodeOrSelfWithNodeName(e.target,"span"),i=UI.UIUtils.enclosingNodeOrSelfWithNodeName(e.target,"tr");if(!i)return null;if(!this.dataGrid)return null;const s=this.dataGrid.dataGridNodeFromNode(i)||this.containmentDataGrid.dataGridNodeFromNode(i)||this.constructorsDataGrid.dataGridNodeFromNode(i)||this.diffDataGrid.dataGridNodeFromNode(i)||this.allocationDataGrid&&this.allocationDataGrid.dataGridNodeFromNode(i)||this.retainmentDataGrid.dataGridNodeFromNode(i),r=this.profile.heapProfilerModel();if(!s||!t||!r)return null;let a;return{box:t.boxInWindow(),show:async e=>{if(!r)return!1;const t=await s.queryObjectContent(r,"popover");return!!t&&(a=await ObjectUI.ObjectPopoverHelper.ObjectPopoverHelper.buildObjectPopover(t,e),!!a||(r.runtimeModel().releaseObjectGroup("popover"),!1))},hide:()=>{r.runtimeModel().releaseObjectGroup("popover"),a&&a.dispose()}}}updatePerspectiveOptions(){const e=this.profiles().length>1;this.perspectiveSelect.removeOptions(),this.perspectives.forEach(((t,i)=>{if(e||t!==this.comparisonPerspective){const e=this.perspectiveSelect.createOption(t.title(),String(i));t===this.currentPerspective&&this.perspectiveSelect.select(e)}}))}updateBaseOptions(){const e=this.profiles(),t=this.baseSelect.selectedIndex();this.baseSelect.removeOptions();for(const t of e)this.baseSelect.createOption(t.title);t>-1&&this.baseSelect.setSelectedIndex(t)}updateFilterOptions(){const e=this.profiles(),t=this.filterSelect.selectedIndex();this.filterSelect.removeOptions(),this.filterSelect.createOption(i18nString(UIStrings.allObjects));for(let t=0;t<e.length;++t){let i;i=t?i18nString(UIStrings.objectsAllocatedBetweenSAndS,{PH1:e[t-1].title,PH2:e[t].title}):i18nString(UIStrings.objectsAllocatedBeforeS,{PH1:e[t].title}),this.filterSelect.createOption(i)}t>-1&&this.filterSelect.setSelectedIndex(t)}updateControls(){this.updatePerspectiveOptions(),this.updateBaseOptions(),this.updateFilterOptions()}onReceiveSnapshot(e){this.updateControls();e.data.addEventListener(ProfileHeaderEvents.ProfileTitleChanged,this.updateControls,this)}onProfileHeaderRemoved(e){const t=e.data;t.removeEventListener(ProfileHeaderEvents.ProfileTitleChanged,this.updateControls,this),this.profile===t?(this.detach(),this.profile.profileType().removeEventListener("SnapshotReceived",this.onReceiveSnapshot,this),this.profile.profileType().removeEventListener(ProfileTypeEvents.RemoveProfileHeader,this.onProfileHeaderRemoved,this),this.dispose()):this.updateControls()}dispose(){this.linkifier.dispose(),this.popoverHelper.dispose(),this.allocationStackView&&(this.allocationStackView.clear(),this.allocationDataGrid&&this.allocationDataGrid.dispose()),this.onStopTracking(),this.trackingOverviewGrid&&this.trackingOverviewGrid.removeEventListener("IdsRangeChanged",this.onIdsRangeChanged.bind(this))}}export class Perspective{titleInternal;constructor(e){this.titleInternal=e}activate(e){}deactivate(e){e.baseSelect.setVisible(!1),e.filterSelect.setVisible(!1),e.classNameFilter.setVisible(!1),e.trackingOverviewGrid&&e.trackingOverviewGrid.detach(),e.allocationWidget&&e.allocationWidget.detach(),e.statisticsView&&e.statisticsView.detach(),e.splitWidget.detach(),e.splitWidget.detachChildWidgets()}masterGrid(e){return null}title(){return this.titleInternal}supportsSearch(){return!1}}export class SummaryPerspective extends Perspective{constructor(){super(i18nString(UIStrings.summary))}activate(e){e.splitWidget.setMainWidget(e.constructorsWidget),e.splitWidget.setSidebarWidget(e.objectDetailsView),e.splitWidget.show(e.searchableViewInternal.element),e.filterSelect.setVisible(!0),e.classNameFilter.setVisible(!0),e.trackingOverviewGrid&&(e.trackingOverviewGrid.show(e.searchableViewInternal.element,e.splitWidget.element),e.trackingOverviewGrid.update(),e.trackingOverviewGrid.updateGrid())}masterGrid(e){return e.constructorsDataGrid}supportsSearch(){return!0}}export class ComparisonPerspective extends Perspective{constructor(){super(i18nString(UIStrings.comparison))}activate(e){e.splitWidget.setMainWidget(e.diffWidget),e.splitWidget.setSidebarWidget(e.objectDetailsView),e.splitWidget.show(e.searchableViewInternal.element),e.baseSelect.setVisible(!0),e.classNameFilter.setVisible(!0)}masterGrid(e){return e.diffDataGrid}supportsSearch(){return!0}}export class ContainmentPerspective extends Perspective{constructor(){super(i18nString(UIStrings.containment))}activate(e){e.splitWidget.setMainWidget(e.containmentWidget),e.splitWidget.setSidebarWidget(e.objectDetailsView),e.splitWidget.show(e.searchableViewInternal.element)}masterGrid(e){return e.containmentDataGrid}}export class AllocationPerspective extends Perspective{allocationSplitWidget;constructor(){super(i18nString(UIStrings.allocation)),this.allocationSplitWidget=new UI.SplitWidget.SplitWidget(!1,!0,"heapSnapshotAllocationSplitViewState",200,200),this.allocationSplitWidget.setSidebarWidget(new UI.Widget.VBox)}activate(e){e.allocationWidget&&this.allocationSplitWidget.setMainWidget(e.allocationWidget),e.splitWidget.setMainWidget(e.constructorsWidget),e.splitWidget.setSidebarWidget(e.objectDetailsView);const t=new UI.Widget.VBox,i=document.createElement("div");i.classList.add("heap-snapshot-view-resizer");const s=i.createChild("div","title").createChild("span");if(i.createChild("div","verticalResizerIcon"),s.textContent=i18nString(UIStrings.liveObjects),this.allocationSplitWidget.hideDefaultResizer(),this.allocationSplitWidget.installResizer(i),t.element.appendChild(i),e.splitWidget.show(t.element),this.allocationSplitWidget.setSidebarWidget(t),this.allocationSplitWidget.show(e.searchableViewInternal.element),e.constructorsDataGrid.clear(),e.allocationDataGrid){const t=e.allocationDataGrid.selectedNode;t&&e.constructorsDataGrid.setAllocationNodeId(t.allocationNodeId())}}deactivate(e){this.allocationSplitWidget.detach(),super.deactivate(e)}masterGrid(e){return e.allocationDataGrid}}export class StatisticsPerspective extends Perspective{constructor(){super(i18nString(UIStrings.statistics))}activate(e){e.statisticsView.show(e.searchableViewInternal.element)}masterGrid(e){return null}}export class HeapSnapshotProfileType extends(Common.ObjectWrapper.eventMixin(ProfileType)){exposeInternals;captureNumericValue;customContentInternal;constructor(e,t){super(e||HeapSnapshotProfileType.TypeId,t||i18nString(UIStrings.heapSnapshot)),SDK.TargetManager.TargetManager.instance().observeModels(SDK.HeapProfilerModel.HeapProfilerModel,this),SDK.TargetManager.TargetManager.instance().addModelListener(SDK.HeapProfilerModel.HeapProfilerModel,SDK.HeapProfilerModel.Events.ResetProfiles,this.resetProfiles,this),SDK.TargetManager.TargetManager.instance().addModelListener(SDK.HeapProfilerModel.HeapProfilerModel,SDK.HeapProfilerModel.Events.AddHeapSnapshotChunk,this.addHeapSnapshotChunk,this),SDK.TargetManager.TargetManager.instance().addModelListener(SDK.HeapProfilerModel.HeapProfilerModel,SDK.HeapProfilerModel.Events.ReportHeapSnapshotProgress,this.reportHeapSnapshotProgress,this),this.exposeInternals=Common.Settings.Settings.instance().createSetting("exposeInternals",!1),this.captureNumericValue=Common.Settings.Settings.instance().createSetting("captureNumericValue",!1),this.customContentInternal=null}modelAdded(e){e.enable()}modelRemoved(e){}getProfiles(){return super.getProfiles()}fileExtension(){return".heapsnapshot"}get buttonTooltip(){return i18nString(UIStrings.takeHeapSnapshot)}isInstantProfile(){return!0}buttonClicked(){return this.takeHeapSnapshot(),Host.userMetrics.actionTaken(Host.UserMetrics.Action.ProfilesHeapProfileTaken),!1}get treeItemTitle(){return i18nString(UIStrings.heapSnapshots)}get description(){return i18nString(UIStrings.heapSnapshotProfilesShowMemory)}customContent(){const e=document.createElement("div"),t=Root.Runtime.experiments.isEnabled("showOptionToExposeInternalsInHeapSnapshot"),i=!t;if(t){const t=UI.SettingsUI.createSettingCheckbox(i18nString(UIStrings.exposeInternals),this.exposeInternals,i);e.appendChild(t)}const s=UI.SettingsUI.createSettingCheckbox(i18nString(UIStrings.captureNumericValue),this.captureNumericValue,i);return e.appendChild(s),this.customContentInternal=e,e}setCustomContentEnabled(e){this.customContentInternal&&this.customContentInternal.querySelectorAll("[is=dt-checkbox]").forEach((t=>{t.checkboxElement.disabled=!e}))}createProfileLoadedFromFile(e){return new HeapProfileHeader(null,this,e)}async takeHeapSnapshot(){if(this.profileBeingRecorded())return;const e=UI.Context.Context.instance().flavor(SDK.HeapProfilerModel.HeapProfilerModel);if(!e)return;let t=new HeapProfileHeader(e,this);this.setProfileBeingRecorded(t),this.addProfile(t),t.updateStatus(i18nString(UIStrings.snapshotting)),await e.takeHeapSnapshot({reportProgress:!0,captureNumericValue:this.captureNumericValue.get(),exposeInternals:this.exposeInternals.get()}),t=this.profileBeingRecorded(),t&&(t.title=i18nString(UIStrings.snapshotD,{PH1:t.uid}),t.finishLoad(),this.setProfileBeingRecorded(null),this.dispatchEventToListeners(ProfileTypeEvents.ProfileComplete,t))}addHeapSnapshotChunk(e){const t=this.profileBeingRecorded();t&&t.transferChunk(e.data)}reportHeapSnapshotProgress(e){const t=this.profileBeingRecorded();if(!t)return;const{done:i,total:s,finished:r}=e.data;t.updateStatus(i18nString(UIStrings.percentagePlaceholder,{PH1:(i/s*100).toFixed(0)}),!0),r&&t.prepareToLoad()}resetProfiles(e){const t=e.data;for(const e of this.getProfiles())e.heapProfilerModel()===t&&this.removeProfile(e)}snapshotReceived(e){this.profileBeingRecorded()===e&&this.setProfileBeingRecorded(null),this.dispatchEventToListeners("SnapshotReceived",e)}static TypeId="HEAP";static SnapshotReceived="SnapshotReceived"}export class TrackingHeapSnapshotProfileType extends(Common.ObjectWrapper.eventMixin(HeapSnapshotProfileType)){recordAllocationStacksSettingInternal;customContentInternal;recording;profileSamples;constructor(){super(TrackingHeapSnapshotProfileType.TypeId,i18nString(UIStrings.allocationInstrumentationOn)),this.recordAllocationStacksSettingInternal=Common.Settings.Settings.instance().createSetting("recordAllocationStacks",!1),this.customContentInternal=null,this.recording=!1}modelAdded(e){super.modelAdded(e),e.addEventListener(SDK.HeapProfilerModel.Events.HeapStatsUpdate,this.heapStatsUpdate,this),e.addEventListener(SDK.HeapProfilerModel.Events.LastSeenObjectId,this.lastSeenObjectId,this)}modelRemoved(e){super.modelRemoved(e),e.removeEventListener(SDK.HeapProfilerModel.Events.HeapStatsUpdate,this.heapStatsUpdate,this),e.removeEventListener(SDK.HeapProfilerModel.Events.LastSeenObjectId,this.lastSeenObjectId,this)}heapStatsUpdate(e){if(!this.profileSamples)return;const t=e.data;let i;for(let e=0;e<t.length;e+=3){i=t[e];const s=t[e+2];this.profileSamples.sizes[i]=s,this.profileSamples.max[i]||(this.profileSamples.max[i]=s)}}lastSeenObjectId(e){const t=this.profileSamples;if(!t)return;const{lastSeenObjectId:i,timestamp:s}=e.data,r=Math.max(t.ids.length,t.max.length-1);t.ids[r]=i,t.max[r]||(t.max[r]=0,t.sizes[r]=0),t.timestamps[r]=s,t.totalTime<s-t.timestamps[0]&&(t.totalTime*=2),this.profileSamples&&this.dispatchEventToListeners("HeapStatsUpdate",this.profileSamples);const a=this.profileBeingRecorded();a&&a.updateStatus(null,!0)}hasTemporaryView(){return!0}get buttonTooltip(){return this.recording?i18nString(UIStrings.stopRecordingHeapProfile):i18nString(UIStrings.startRecordingHeapProfile)}isInstantProfile(){return!1}buttonClicked(){return this.toggleRecording()}startRecordingProfile(){if(this.profileBeingRecorded())return;const e=this.addNewProfile();e&&e.startTrackingHeapObjects(this.recordAllocationStacksSettingInternal.get())}customContent(){const e=UI.SettingsUI.createSettingCheckbox(i18nString(UIStrings.recordAllocationStacksExtra),this.recordAllocationStacksSettingInternal,!0);return this.customContentInternal=e,e}setCustomContentEnabled(e){this.customContentInternal&&(this.customContentInternal.checkboxElement.disabled=!e)}recordAllocationStacksSetting(){return this.recordAllocationStacksSettingInternal}addNewProfile(){const e=UI.Context.Context.instance().flavor(SDK.HeapProfilerModel.HeapProfilerModel);return e?(this.setProfileBeingRecorded(new HeapProfileHeader(e,this,void 0)),this.profileSamples=new Samples,this.profileBeingRecorded()._profileSamples=this.profileSamples,this.recording=!0,this.addProfile(this.profileBeingRecorded()),this.profileBeingRecorded().updateStatus(i18nString(UIStrings.recording)),this.dispatchEventToListeners("TrackingStarted"),e):null}async stopRecordingProfile(){let e=this.profileBeingRecorded();e.updateStatus(i18nString(UIStrings.snapshotting));const t=e.heapProfilerModel().stopTrackingHeapObjects(!0);this.recording=!1,this.dispatchEventToListeners("TrackingStopped"),await t,e=this.profileBeingRecorded(),e&&(e.finishLoad(),this.profileSamples=null,this.setProfileBeingRecorded(null),this.dispatchEventToListeners(ProfileTypeEvents.ProfileComplete,e))}toggleRecording(){return this.recording?this.stopRecordingProfile():this.startRecordingProfile(),this.recording}fileExtension(){return".heaptimeline"}get treeItemTitle(){return i18nString(UIStrings.allocationTimelines)}get description(){return i18nString(UIStrings.AllocationTimelinesShowInstrumented)}resetProfiles(e){const t=this.recording;this.setProfileBeingRecorded(null),super.resetProfiles(e),this.profileSamples=null,t&&this.addNewProfile()}profileBeingRecordedRemoved(){this.stopRecordingProfile(),this.profileSamples=null}static TypeId="HEAP-RECORD";static HeapStatsUpdate="HeapStatsUpdate";static TrackingStarted="TrackingStarted";static TrackingStopped="TrackingStopped"}export class HeapProfileHeader extends ProfileHeader{heapProfilerModelInternal;maxJSObjectId;workerProxy;receiver;snapshotProxy;loadPromise;fulfillLoad;totalNumberOfChunks;bufferedWriter;onTempFileReady;failedToCreateTempFile;wasDisposed;fileName;constructor(e,t,i){super(t,i||i18nString(UIStrings.snapshotD,{PH1:t.nextProfileUid()})),this.heapProfilerModelInternal=e,this.maxJSObjectId=-1,this.workerProxy=null,this.receiver=null,this.snapshotProxy=null,this.loadPromise=new Promise((e=>{this.fulfillLoad=e})),this.totalNumberOfChunks=0,this.bufferedWriter=null,this.onTempFileReady=null}heapProfilerModel(){return this.heapProfilerModelInternal}async getLocation(e){return this.snapshotProxy?this.snapshotProxy.getLocation(e):null}createSidebarTreeElement(e){return new ProfileSidebarTreeElement(e,this,"heap-snapshot-sidebar-tree-item")}createView(e){return new HeapSnapshotView(e,this)}prepareToLoad(){console.assert(!this.receiver,"Already loading"),this.setupWorker(),this.updateStatus(i18nString(UIStrings.loading),!0)}finishLoad(){!this.wasDisposed&&this.receiver&&this.receiver.close(),this.bufferedWriter&&this.didWriteToTempFile(this.bufferedWriter)}didWriteToTempFile(e){this.wasDisposed?e&&e.remove():(this.tempFile=e,e||(this.failedToCreateTempFile=!0),this.onTempFileReady&&(this.onTempFileReady(),this.onTempFileReady=null))}setupWorker(){console.assert(!this.workerProxy,"HeapSnapshotWorkerProxy already exists"),this.workerProxy=new HeapSnapshotWorkerProxy(this.handleWorkerEvent.bind(this)),this.workerProxy.addEventListener("Wait",(e=>{this.updateStatus(null,e.data)}),this),this.receiver=this.workerProxy.createLoader(this.uid,this.snapshotReceived.bind(this))}handleWorkerEvent(e,t){if(HeapSnapshotModel.HeapSnapshotModel.HeapSnapshotProgressEvent.BrokenSnapshot===e){const e=t;return void Common.Console.Console.instance().error(e)}if(HeapSnapshotModel.HeapSnapshotModel.HeapSnapshotProgressEvent.Update!==e)return;const i=t,s=i18n.i18n.deserializeUIString(i);this.updateStatus(moduleI18nString(s.string,s.values))}dispose(){this.workerProxy&&this.workerProxy.dispose(),this.removeTempFile(),this.wasDisposed=!0}didCompleteSnapshotTransfer(){this.snapshotProxy&&this.updateStatus(Platform.NumberUtilities.bytesToString(this.snapshotProxy.totalSize),!1)}transferChunk(e){this.bufferedWriter||(this.bufferedWriter=new Bindings.TempFile.TempFile),this.bufferedWriter.write([e]),++this.totalNumberOfChunks,this.receiver&&this.receiver.write(e)}snapshotReceived(e){this.wasDisposed||(this.receiver=null,this.snapshotProxy=e,this.maxJSObjectId=e.maxJSObjectId(),this.didCompleteSnapshotTransfer(),this.workerProxy&&this.workerProxy.startCheckingForLongRunningCalls(),this.notifySnapshotReceived())}notifySnapshotReceived(){this.snapshotProxy&&this.fulfillLoad&&this.fulfillLoad(this.snapshotProxy),this.profileType().snapshotReceived(this),this.canSaveToFile()&&this.dispatchEventToListeners(ProfileHeaderEvents.ProfileReceived)}canSaveToFile(){return!this.fromFile()&&Boolean(this.snapshotProxy)}saveToFile(){const e=new Bindings.FileUtils.FileOutputStream;this.fileName=this.fileName||"Heap-"+Platform.DateUtilities.toISO8601Compact(new Date)+this.profileType().fileExtension();const t=async i=>{if(i){if(this.failedToCreateTempFile)return Common.Console.Console.instance().error("Failed to open temp file with heap snapshot"),void e.close();if(this.tempFile){const t=await this.tempFile.copyToOutputStream(e,this.onChunkTransferred.bind(this));return t&&Common.Console.Console.instance().error("Failed to read heap snapshot from temp file: "+t.message),void this.didCompleteSnapshotTransfer()}this.onTempFileReady=()=>{t(i)},this.updateSaveProgress(0,1)}};e.open(this.fileName).then(t.bind(this))}onChunkTransferred(e){this.updateSaveProgress(e.loadedSize(),e.fileSize())}updateSaveProgress(e,t){const i=(100*(t&&e/t)).toFixed(0);this.updateStatus(i18nString(UIStrings.savingD,{PH1:i}))}async loadFromFile(e){this.updateStatus(i18nString(UIStrings.loading),!0),this.setupWorker();const t=new Bindings.FileUtils.ChunkedFileReader(e,1e7),i=await t.read(this.receiver);if(!i){const e=t.error();e&&this.updateStatus(e.message)}return i?null:t.error()}profileType(){return super.profileType()}}export class HeapSnapshotStatisticsView extends UI.Widget.VBox{pieChart;constructor(){super(),this.element.classList.add("heap-snapshot-statistics-view"),this.pieChart=new PerfUI.PieChart.PieChart,this.setTotalAndRecords(0,[]),this.pieChart.classList.add("heap-snapshot-stats-pie-chart"),this.element.appendChild(this.pieChart)}static valueFormatter(e){return i18nString(UIStrings.sKb,{PH1:Platform.NumberUtilities.withThousandsSeparator(Math.round(e/1e3))})}setTotalAndRecords(e,t){this.pieChart.data={chartName:i18nString(UIStrings.heapMemoryUsage),size:150,formatter:HeapSnapshotStatisticsView.valueFormatter,showLegend:!0,total:e,slices:t}}}export class HeapAllocationStackView extends UI.Widget.Widget{heapProfilerModel;linkifier;frameElements;constructor(e){super(),this.heapProfilerModel=e,this.linkifier=new Components.Linkifier.Linkifier,this.frameElements=[]}onContextMenu(e,t){const i=new UI.ContextMenu.ContextMenu(t);i.containsTarget(e)||i.appendApplicableItems(e),i.show(),t.consume(!0)}onStackViewKeydown(e){const t=e.target;if(!t)return;if("Enter"===e.key){const i=stackFrameToURLElement.get(t);if(!i)return;const s=Components.Linkifier.Linkifier.linkInfo(i);if(!s)return;return void(Components.Linkifier.Linkifier.invokeFirstAction(s)&&e.consume(!0))}let i;const s=e;if("ArrowUp"===s.key)i=!1;else{if("ArrowDown"!==s.key)return;i=!0}const r=this.frameElements.indexOf(t);if(-1===r)return;const a=i?r+1:r-1;if(a<0||a>=this.frameElements.length)return;const n=this.frameElements[a];n.tabIndex=0,t.tabIndex=-1,n.focus(),e.consume(!0)}async setAllocatedObject(e,t){this.clear();const i=await e.allocationStack(t);if(!i){const e=this.element.createChild("div","no-heap-allocation-stack");return void UI.UIUtils.createTextChild(e,i18nString(UIStrings.stackWasNotRecordedForThisObject))}const s=this.element.createChild("div","heap-allocation-stack");s.addEventListener("keydown",this.onStackViewKeydown.bind(this),!1);for(const e of i){const t=s.createChild("div","stack-frame");this.frameElements.push(t),t.tabIndex=-1;if(t.createChild("div").textContent=UI.UIUtils.beautifyFunctionName(e.functionName),!e.scriptId)continue;const i=this.heapProfilerModel?this.heapProfilerModel.target():null,r={columnNumber:e.column-1,inlineFrameIndex:0},a=this.linkifier.linkifyScriptLocation(i,String(e.scriptId),e.scriptName,e.line-1,r);t.appendChild(a),stackFrameToURLElement.set(t,a),t.addEventListener("contextmenu",this.onContextMenu.bind(this,a))}this.frameElements[0].tabIndex=0}clear(){this.element.removeChildren(),this.frameElements=[],this.linkifier.reset()}}const stackFrameToURLElement=new WeakMap;