Timeline.CountersGraph=class extends UI.VBox{constructor(delegate){super();this.element.id='memory-graphs-container';this._delegate=delegate;this._calculator=new Timeline.CountersGraph.Calculator();this._infoWidget=new UI.HBox();this._infoWidget.element.classList.add('memory-counter-selector-swatches','timeline-toolbar-resizer');this._infoWidget.show(this.element);this._graphsContainer=new UI.VBox();this._graphsContainer.show(this.element);var canvasWidget=new UI.VBoxWithResizeCallback(this._resize.bind(this));canvasWidget.show(this._graphsContainer.element);this._createCurrentValuesBar();this._canvasContainer=canvasWidget.element;this._canvasContainer.id='memory-graphs-canvas-container';this._canvas=this._canvasContainer.createChild('canvas');this._canvas.id='memory-counters-graph';this._canvasContainer.addEventListener('mouseover',this._onMouseMove.bind(this),true);this._canvasContainer.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._canvasContainer.addEventListener('mouseleave',this._onMouseLeave.bind(this),true);this._canvasContainer.addEventListener('click',this._onClick.bind(this),true);this._timelineGrid=new PerfUI.TimelineGrid();this._canvasContainer.appendChild(this._timelineGrid.dividersElement);this._counters=[];this._counterUI=[];this._countersByName={};this._countersByName['jsHeapSizeUsed']=this._createCounter(Common.UIString('JS Heap'),Common.UIString('JS Heap: %s'),'hsl(220, 90%, 43%)',Number.bytesToString);this._countersByName['documents']=this._createCounter(Common.UIString('Documents'),Common.UIString('Documents: %s'),'hsl(0, 90%, 43%)');this._countersByName['nodes']=this._createCounter(Common.UIString('Nodes'),Common.UIString('Nodes: %s'),'hsl(120, 90%, 43%)');this._countersByName['jsEventListeners']=this._createCounter(Common.UIString('Listeners'),Common.UIString('Listeners: %s'),'hsl(38, 90%, 43%)');this._gpuMemoryCounter=this._createCounter(Common.UIString('GPU Memory'),Common.UIString('GPU Memory [KB]: %s'),'hsl(300, 90%, 43%)',Number.bytesToString);this._countersByName['gpuMemoryUsedKB']=this._gpuMemoryCounter;}
setModel(model){this._calculator.setZeroTime(model?model.timelineModel().minimumRecordTime():0);for(var i=0;i<this._counters.length;++i){this._counters[i].reset();this._counterUI[i].reset();}
this.scheduleRefresh();if(!model)
return;var events=model.timelineModel().mainThreadEvents();for(var i=0;i<events.length;++i){var event=events[i];if(event.name!==TimelineModel.TimelineModel.RecordType.UpdateCounters)
continue;var counters=event.args.data;if(!counters)
return;for(var name in counters){var counter=this._countersByName[name];if(counter)
counter.appendSample(event.startTime,counters[name]);}
var gpuMemoryLimitCounterName='gpuMemoryLimitKB';if(gpuMemoryLimitCounterName in counters)
this._gpuMemoryCounter.setLimit(counters[gpuMemoryLimitCounterName]);}}
_createCurrentValuesBar(){this._currentValuesBar=this._graphsContainer.element.createChild('div');this._currentValuesBar.id='counter-values-bar';}
_createCounter(uiName,uiValueTemplate,color,formatter){var counter=new Timeline.CountersGraph.Counter();this._counters.push(counter);this._counterUI.push(new Timeline.CountersGraph.CounterUI(this,uiName,uiValueTemplate,color,counter,formatter));return counter;}
view(){return this;}
resizerElement(){return this._infoWidget.element;}
_resize(){var parentElement=this._canvas.parentElement;this._canvas.width=parentElement.clientWidth*window.devicePixelRatio;this._canvas.height=parentElement.clientHeight*window.devicePixelRatio;this._calculator.setDisplayWidth(this._canvas.width);this.refresh();}
setWindowTimes(startTime,endTime){this._calculator.setWindow(startTime,endTime);this.scheduleRefresh();}
scheduleRefresh(){UI.invokeOnceAfterBatchUpdate(this,this.refresh);}
draw(){for(var i=0;i<this._counters.length;++i){this._counters[i]._calculateVisibleIndexes(this._calculator);this._counters[i]._calculateXValues(this._canvas.width);}
this._clear();for(var i=0;i<this._counterUI.length;i++)
this._counterUI[i]._drawGraph(this._canvas);}
_onClick(event){var x=event.x-this._canvasContainer.totalOffsetLeft();var minDistance=Infinity;var bestTime;for(var i=0;i<this._counterUI.length;++i){var counterUI=this._counterUI[i];if(!counterUI.counter.times.length)
continue;var index=counterUI._recordIndexAt(x);var distance=Math.abs(x*window.devicePixelRatio-counterUI.counter.x[index]);if(distance<minDistance){minDistance=distance;bestTime=counterUI.counter.times[index];}}
if(bestTime!==undefined)
this._delegate.selectEntryAtTime(bestTime);}
_onMouseLeave(event){delete this._markerXPosition;this._clearCurrentValueAndMarker();}
_clearCurrentValueAndMarker(){for(var i=0;i<this._counterUI.length;i++)
this._counterUI[i]._clearCurrentValueAndMarker();}
_onMouseMove(event){var x=event.x-this._canvasContainer.totalOffsetLeft();this._markerXPosition=x;this._refreshCurrentValues();}
_refreshCurrentValues(){if(this._markerXPosition===undefined)
return;for(var i=0;i<this._counterUI.length;++i)
this._counterUI[i].updateCurrentValue(this._markerXPosition);}
refresh(){this._timelineGrid.updateDividers(this._calculator);this.draw();this._refreshCurrentValues();}
_clear(){var ctx=this._canvas.getContext('2d');ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);}
highlightEvent(event){}
setSelection(selection){}};Timeline.CountersGraph.Counter=class{constructor(){this.times=[];this.values=[];}
appendSample(time,value){if(this.values.length&&this.values.peekLast()===value)
return;this.times.push(time);this.values.push(value);}
reset(){this.times=[];this.values=[];}
setLimit(value){this._limitValue=value;}
_calculateBounds(){var maxValue;var minValue;for(var i=this._minimumIndex;i<=this._maximumIndex;i++){var value=this.values[i];if(minValue===undefined||value<minValue)
minValue=value;if(maxValue===undefined||value>maxValue)
maxValue=value;}
minValue=minValue||0;maxValue=maxValue||1;if(this._limitValue){if(maxValue>this._limitValue*0.5)
maxValue=Math.max(maxValue,this._limitValue);minValue=Math.min(minValue,this._limitValue);}
return{min:minValue,max:maxValue};}
_calculateVisibleIndexes(calculator){var start=calculator.minimumBoundary();var end=calculator.maximumBoundary();this._minimumIndex=Number.constrain(this.times.upperBound(start)-1,0,this.times.length-1);this._maximumIndex=Number.constrain(this.times.lowerBound(end),0,this.times.length-1);this._minTime=start;this._maxTime=end;}
_calculateXValues(width){if(!this.values.length)
return;var xFactor=width/(this._maxTime-this._minTime);this.x=new Array(this.values.length);for(var i=this._minimumIndex+1;i<=this._maximumIndex;i++)
this.x[i]=xFactor*(this.times[i]-this._minTime);}};Timeline.CountersGraph.CounterUI=class{constructor(countersPane,title,currentValueLabel,graphColor,counter,formatter){this._countersPane=countersPane;this.counter=counter;this._formatter=formatter||Number.withThousandsSeparator;var container=countersPane._infoWidget.element.createChild('div','memory-counter-selector-info');this._setting=Common.settings.createSetting('timelineCountersGraph-'+title,true);this._setting.setTitle(title);this._filter=new UI.ToolbarSettingCheckbox(this._setting,title);this._filter.inputElement.classList.add('-theme-preserve');var color=Common.Color.parse(graphColor).setAlpha(0.5).asString(Common.Color.Format.RGBA);if(color){this._filter.element.backgroundColor=color;this._filter.element.borderColor='transparent';}
this._filter.inputElement.addEventListener('click',this._toggleCounterGraph.bind(this));container.appendChild(this._filter.element);this._range=this._filter.element.createChild('span','range');this._value=countersPane._currentValuesBar.createChild('span','memory-counter-value');this._value.style.color=graphColor;this.graphColor=graphColor;this.limitColor=Common.Color.parse(graphColor).setAlpha(0.3).asString(Common.Color.Format.RGBA);this.graphYValues=[];this._verticalPadding=10;this._currentValueLabel=currentValueLabel;this._marker=countersPane._canvasContainer.createChild('div','memory-counter-marker');this._marker.style.backgroundColor=graphColor;this._clearCurrentValueAndMarker();}
reset(){this._range.textContent='';}
setRange(minValue,maxValue){var min=this._formatter(minValue);var max=this._formatter(maxValue);this._range.textContent=Common.UIString('[%s\xa0\u2013\xa0%s]',min,max);}
_toggleCounterGraph(event){this._value.classList.toggle('hidden',!this._filter.checked());this._countersPane.refresh();}
_recordIndexAt(x){return this.counter.x.upperBound(x*window.devicePixelRatio,null,this.counter._minimumIndex+1,this.counter._maximumIndex+1)-
1;}
updateCurrentValue(x){if(!this.visible()||!this.counter.values.length||!this.counter.x)
return;var index=this._recordIndexAt(x);var value=Number.withThousandsSeparator(this.counter.values[index]);this._value.textContent=Common.UIString(this._currentValueLabel,value);var y=this.graphYValues[index]/window.devicePixelRatio;this._marker.style.left=x+'px';this._marker.style.top=y+'px';this._marker.classList.remove('hidden');}
_clearCurrentValueAndMarker(){this._value.textContent='';this._marker.classList.add('hidden');}
_drawGraph(canvas){var ctx=canvas.getContext('2d');var width=canvas.width;var height=canvas.height-2*this._verticalPadding;if(height<=0){this.graphYValues=[];return;}
var originY=this._verticalPadding;var counter=this.counter;var values=counter.values;if(!values.length)
return;var bounds=counter._calculateBounds();var minValue=bounds.min;var maxValue=bounds.max;this.setRange(minValue,maxValue);if(!this.visible())
return;var yValues=this.graphYValues;var maxYRange=maxValue-minValue;var yFactor=maxYRange?height/(maxYRange):1;ctx.save();ctx.lineWidth=window.devicePixelRatio;if(ctx.lineWidth%2)
ctx.translate(0.5,0.5);ctx.beginPath();var value=values[counter._minimumIndex];var currentY=Math.round(originY+height-(value-minValue)*yFactor);ctx.moveTo(0,currentY);for(var i=counter._minimumIndex;i<=counter._maximumIndex;i++){var x=Math.round(counter.x[i]);ctx.lineTo(x,currentY);var currentValue=values[i];if(typeof currentValue!=='undefined')
value=currentValue;currentY=Math.round(originY+height-(value-minValue)*yFactor);ctx.lineTo(x,currentY);yValues[i]=currentY;}
yValues.length=i;ctx.lineTo(width,currentY);ctx.strokeStyle=this.graphColor;ctx.stroke();if(counter._limitValue){var limitLineY=Math.round(originY+height-(counter._limitValue-minValue)*yFactor);ctx.moveTo(0,limitLineY);ctx.lineTo(width,limitLineY);ctx.strokeStyle=this.limitColor;ctx.stroke();}
ctx.closePath();ctx.restore();}
visible(){return this._filter.checked();}};Timeline.CountersGraph.Calculator=class{setZeroTime(time){this._zeroTime=time;}
computePosition(time){return(time-this._minimumBoundary)/this.boundarySpan()*this._workingArea;}
setWindow(minimumBoundary,maximumBoundary){this._minimumBoundary=minimumBoundary;this._maximumBoundary=maximumBoundary;}
setDisplayWidth(clientWidth){this._workingArea=clientWidth;}
formatValue(value,precision){return Number.preciseMillisToString(value-this.zeroTime(),precision);}
maximumBoundary(){return this._maximumBoundary;}
minimumBoundary(){return this._minimumBoundary;}
zeroTime(){return this._zeroTime;}
boundarySpan(){return this._maximumBoundary-this._minimumBoundary;}};;Timeline.ExtensionTracingSession=class{constructor(provider,performanceModel){this._provider=provider;this._performanceModel=performanceModel;this._completionCallback;this._completionPromise=new Promise(fulfill=>{this._completionCallback=fulfill;});this._timeOffset=0;}
loadingStarted(){}
processingStarted(){}
loadingProgress(progress){}
loadingComplete(tracingModel,storage){if(!tracingModel)
return;this._performanceModel.addExtensionEvents(this._provider.longDisplayName(),tracingModel,this._timeOffset);this._completionCallback();}
complete(url,timeOffsetMicroseconds){if(!url){this._completionCallback();return;}
this._timeOffset=timeOffsetMicroseconds;Timeline.TimelineLoader.loadFromURL(url,this);}
start(){this._provider.start(this);}
stop(){this._provider.stop();return this._completionPromise;}};;Timeline.PerformanceModel=class extends Common.Object{constructor(){super();this._mainTarget=null;this._tracingModel=null;this._timelineModel=new TimelineModel.TimelineModel();this._frameModel=new TimelineModel.TimelineFrameModel(event=>Timeline.TimelineUIUtils.eventStyle(event).category.name);this._filmStripModel=null;this._irModel=new TimelineModel.TimelineIRModel();this._extensionTracingModels=[];this._recordStartTime=undefined;}
setMainTarget(target){this._mainTarget=target;}
setRecordStartTime(time){this._recordStartTime=time;}
setTracingModel(model){this._tracingModel=model;this._timelineModel.setEvents(model,!this._mainTarget);var groups=TimelineModel.TimelineModel.AsyncEventGroup;var asyncEventsByGroup=this._timelineModel.mainThreadAsyncEvents();this._irModel.populate(asyncEventsByGroup.get(groups.input),asyncEventsByGroup.get(groups.animation));this._frameModel.addTraceEvents(this._mainTarget,this._timelineModel.inspectedTargetEvents(),this._timelineModel.sessionId()||'');for(var entry of this._extensionTracingModels){entry.model.adjustTime(this._tracingModel.minimumRecordTime()+(entry.timeOffset/1000)-this._recordStartTime);}}
addExtensionEvents(title,model,timeOffset){this._extensionTracingModels.push({model:model,title:title,timeOffset:timeOffset});if(!this._tracingModel)
return;model.adjustTime(this._tracingModel.minimumRecordTime()+(timeOffset/1000)-this._recordStartTime);this.dispatchEventToListeners(Timeline.PerformanceModel.Events.ExtensionDataAdded);}
tracingModel(){if(!this._tracingModel)
throw'call setTracingModel before accessing PerformanceModel';return this._tracingModel;}
timelineModel(){return this._timelineModel;}
filmStripModel(){if(this._filmStripModel)
return this._filmStripModel;if(!this._tracingModel)
throw'call setTracingModel before accessing PerformanceModel';this._filmStripModel=new SDK.FilmStripModel(this._tracingModel);return this._filmStripModel;}
frames(){return this._frameModel.frames();}
frameModel(){return this._frameModel;}
interactionRecords(){return this._irModel.interactionRecords();}
extensionInfo(){return this._extensionTracingModels;}
dispose(){if(this._tracingModel)
this._tracingModel.reset();for(var extensionEntry of this._extensionTracingModels)
extensionEntry.model.reset();}};Timeline.PerformanceModel.Events={ExtensionDataAdded:Symbol('ExtensionDataAdded')};;Timeline.TimelineController=class{constructor(tracingManager,performanceModel,client){this._tracingManager=tracingManager;this._performanceModel=performanceModel;this._client=client;this._tracingModelBackingStorage=new Bindings.TempFileBackingStorage('tracing');this._tracingModel=new SDK.TracingModel(this._tracingModelBackingStorage);this._performanceModel.setMainTarget(tracingManager.target());this._extensionSessions=[];SDK.targetManager.observeModels(SDK.CPUProfilerModel,this);}
startRecording(options,providers){this._extensionTraceProviders=Extensions.extensionServer.traceProviders().slice();function disabledByDefault(category){return'disabled-by-default-'+category;}
const categoriesArray=['-*','devtools.timeline','v8.execute',disabledByDefault('devtools.timeline'),disabledByDefault('devtools.timeline.frame'),SDK.TracingModel.TopLevelEventCategory,TimelineModel.TimelineModel.Category.Console,TimelineModel.TimelineModel.Category.UserTiming];categoriesArray.push(TimelineModel.TimelineModel.Category.LatencyInfo);if(Runtime.experiments.isEnabled('timelineFlowEvents'))
categoriesArray.push('devtools.timeline.async');if(Runtime.experiments.isEnabled('timelineV8RuntimeCallStats')&&options.enableJSSampling)
categoriesArray.push(disabledByDefault('v8.runtime_stats_sampling'));if(Runtime.experiments.isEnabled('timelineTracingJSProfile')&&options.enableJSSampling){categoriesArray.push(disabledByDefault('v8.cpu_profiler'));if(Common.moduleSetting('highResolutionCpuProfiling').get())
categoriesArray.push(disabledByDefault('v8.cpu_profiler.hires'));}
categoriesArray.push(disabledByDefault('devtools.timeline.stack'));if(Runtime.experiments.isEnabled('timelineInvalidationTracking'))
categoriesArray.push(disabledByDefault('devtools.timeline.invalidationTracking'));if(options.capturePictures){categoriesArray.push(disabledByDefault('devtools.timeline.layers'),disabledByDefault('devtools.timeline.picture'),disabledByDefault('blink.graphics_context_annotations'));}
if(options.captureFilmStrip)
categoriesArray.push(disabledByDefault('devtools.screenshot'));this._extensionSessions=providers.map(provider=>new Timeline.ExtensionTracingSession(provider,this._performanceModel));this._extensionSessions.forEach(session=>session.start());var startPromise=this._startRecordingWithCategories(categoriesArray.join(','),options.enableJSSampling);this._performanceModel.setRecordStartTime(Date.now());return startPromise;}
stopRecording(){var tracingStoppedPromises=[];tracingStoppedPromises.push(new Promise(resolve=>this._tracingCompleteCallback=resolve));tracingStoppedPromises.push(this._stopProfilingOnAllModels());this._tracingManager.stop();tracingStoppedPromises.push(SDK.targetManager.resumeAllTargets());this._client.loadingStarted();var extensionCompletionPromises=this._extensionSessions.map(session=>session.stop());if(extensionCompletionPromises.length){var timerId;var timeoutPromise=new Promise(fulfill=>timerId=setTimeout(fulfill,5000));tracingStoppedPromises.push(Promise.race([Promise.all(extensionCompletionPromises).then(()=>clearTimeout(timerId)),timeoutPromise]));}
Promise.all(tracingStoppedPromises).then(()=>this._allSourcesFinished());}
modelAdded(cpuProfilerModel){if(this._profiling)
cpuProfilerModel.startRecording();}
modelRemoved(cpuProfilerModel){}
_startProfilingOnAllModels(){this._profiling=true;var models=SDK.targetManager.models(SDK.CPUProfilerModel);return Promise.all(models.map(model=>model.startRecording()));}
_addCpuProfile(targetId,cpuProfile){if(!cpuProfile){Common.console.warn(Common.UIString('CPU profile for a target is not available.'));return;}
if(!this._cpuProfiles)
this._cpuProfiles=new Map();this._cpuProfiles.set(targetId,cpuProfile);}
_stopProfilingOnAllModels(){var models=this._profiling?SDK.targetManager.models(SDK.CPUProfilerModel):[];this._profiling=false;var promises=[];for(var model of models){var targetId=model.target().id();var modelPromise=model.stopRecording().then(this._addCpuProfile.bind(this,targetId));promises.push(modelPromise);}
return Promise.all(promises);}
_startRecordingWithCategories(categories,enableJSSampling){SDK.targetManager.suspendAllTargets();var profilingStartedPromise=enableJSSampling&&!Runtime.experiments.isEnabled('timelineTracingJSProfile')?this._startProfilingOnAllModels():Promise.resolve();var samplingFrequencyHz=Common.moduleSetting('highResolutionCpuProfiling').get()?10000:1000;var options='sampling-frequency='+samplingFrequencyHz;return profilingStartedPromise.then(()=>this._tracingManager.start(this,categories,options));}
traceEventsCollected(events){this._tracingModel.addEvents(events);}
tracingComplete(){this._tracingCompleteCallback();this._tracingCompleteCallback=null;}
_allSourcesFinished(){this._client.processingStarted();setTimeout(()=>this._finalizeTrace(),0);}
_finalizeTrace(){this._injectCpuProfileEvents();this._tracingModel.tracingComplete();this._client.loadingComplete(this._tracingModel,this._tracingModelBackingStorage);}
_injectCpuProfileEvent(pid,tid,cpuProfile){if(!cpuProfile)
return;var cpuProfileEvent=({cat:SDK.TracingModel.DevToolsMetadataEventCategory,ph:SDK.TracingModel.Phase.Instant,ts:this._tracingModel.maximumRecordTime()*1000,pid:pid,tid:tid,name:TimelineModel.TimelineModel.RecordType.CpuProfile,args:{data:{cpuProfile:cpuProfile}}});this._tracingModel.addEvents([cpuProfileEvent]);}
_injectCpuProfileEvents(){if(!this._cpuProfiles)
return;var metadataEventTypes=TimelineModel.TimelineModel.DevToolsMetadataEvent;var metadataEvents=this._tracingModel.devToolsMetadataEvents();var mainMetaEvent=metadataEvents.filter(event=>event.name===metadataEventTypes.TracingStartedInPage).peekLast();if(!mainMetaEvent)
return;var pid=mainMetaEvent.thread.process().id();var mainCpuProfile=this._cpuProfiles.get(this._tracingManager.target().id());this._injectCpuProfileEvent(pid,mainMetaEvent.thread.id(),mainCpuProfile);var workerMetaEvents=metadataEvents.filter(event=>event.name===metadataEventTypes.TracingSessionIdForWorker);for(var metaEvent of workerMetaEvents){var workerId=metaEvent.args['data']['workerId'];var cpuProfile=this._cpuProfiles.get(workerId);this._injectCpuProfileEvent(metaEvent.thread.process().id(),metaEvent.args['data']['workerThreadId'],cpuProfile);}
this._cpuProfiles=null;}
tracingBufferUsage(usage){this._client.recordingProgress(usage);}
eventsRetrievalProgress(progress){this._client.loadingProgress(progress);}};Timeline.TimelineController.Client=function(){};Timeline.TimelineController.Client.prototype={recordingProgress(usage){},};Timeline.TimelineController.RecordingOptions;;Timeline.TimelineDetailsView=class extends UI.VBox{constructor(filters,delegate){super();this.element.classList.add('timeline-details');this._detailsLinkifier=new Components.Linkifier();this._tabbedPane=new UI.TabbedPane();this._tabbedPane.show(this.element);const tabIds=Timeline.TimelineDetailsView.Tab;this._defaultDetailsWidget=new UI.VBox();this._defaultDetailsWidget.element.classList.add('timeline-details-view');this._defaultDetailsContentElement=this._defaultDetailsWidget.element.createChild('div','timeline-details-view-body vbox');this._defaultDetailsContentElement.tabIndex=0;this._appendTab(tabIds.Details,Common.UIString('Summary'),this._defaultDetailsWidget);this.setPreferredTab(tabIds.Details);this._rangeDetailViews=new Map();if(!Runtime.experiments.isEnabled('timelineMultipleMainViews')){const bottomUpView=new Timeline.BottomUpTimelineTreeView(filters);this._appendTab(tabIds.BottomUp,Common.UIString('Bottom-Up'),bottomUpView);this._rangeDetailViews.set(tabIds.BottomUp,bottomUpView);const callTreeView=new Timeline.CallTreeTimelineTreeView(filters);this._appendTab(tabIds.CallTree,Common.UIString('Call Tree'),callTreeView);this._rangeDetailViews.set(tabIds.CallTree,callTreeView);const eventsView=new Timeline.EventsTimelineTreeView(filters,delegate);this._appendTab(tabIds.EventLog,Common.UIString('Event Log'),eventsView);this._rangeDetailViews.set(tabIds.EventLog,eventsView);}
this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._tabSelected,this);}
setModel(model){this._model=model;this._tabbedPane.closeTabs([Timeline.TimelineDetailsView.Tab.PaintProfiler,Timeline.TimelineDetailsView.Tab.LayerViewer],false);for(var view of this._rangeDetailViews.values())
view.setModel(model);this._lazyPaintProfilerView=null;this._lazyLayersView=null;}
_setContent(node){const allTabs=this._tabbedPane.otherTabs(Timeline.TimelineDetailsView.Tab.Details);for(var i=0;i<allTabs.length;++i){if(!this._rangeDetailViews.has(allTabs[i]))
this._tabbedPane.closeTab(allTabs[i]);}
this._defaultDetailsContentElement.removeChildren();this._defaultDetailsContentElement.appendChild(node);}
_updateContents(){const view=this._rangeDetailViews.get(this._tabbedPane.selectedTabId||'');if(view)
view.updateContents(this._selection);}
_appendTab(id,tabTitle,view,isCloseable){this._tabbedPane.appendTab(id,tabTitle,view,undefined,undefined,isCloseable);if(this._preferredTabId!==this._tabbedPane.selectedTabId)
this._tabbedPane.selectTab(id);}
headerElement(){return this._tabbedPane.headerElement();}
setPreferredTab(tabId){this._preferredTabId=tabId;}
setSelection(selection){this._detailsLinkifier.reset();this._selection=selection;switch(this._selection.type()){case Timeline.TimelineSelection.Type.TraceEvent:var event=(this._selection.object());Timeline.TimelineUIUtils.buildTraceEventDetails(event,this._model.timelineModel(),this._detailsLinkifier,true).then(fragment=>this._appendDetailsTabsForTraceEventAndShowDetails(event,fragment));break;case Timeline.TimelineSelection.Type.Frame:var frame=(this._selection.object());var screenshotTime=frame.idle?frame.startTime:frame.endTime;var filmStripFrame=this._model.filmStripModel().frameByTimestamp(screenshotTime);if(filmStripFrame&&filmStripFrame.timestamp-frame.endTime>10)
filmStripFrame=null;this._setContent(Timeline.TimelineUIUtils.generateDetailsContentForFrame(frame,filmStripFrame));if(frame.layerTree){var layersView=this._layersView();layersView.showLayerTree(frame.layerTree);if(!this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.LayerViewer))
this._appendTab(Timeline.TimelineDetailsView.Tab.LayerViewer,Common.UIString('Layers'),layersView);}
break;case Timeline.TimelineSelection.Type.NetworkRequest:var request=(this._selection.object());Timeline.TimelineUIUtils.buildNetworkRequestDetails(request,this._model.timelineModel(),this._detailsLinkifier).then(this._setContent.bind(this));break;case Timeline.TimelineSelection.Type.Range:this._updateSelectedRangeStats(this._selection.startTime(),this._selection.endTime());break;}
this._updateContents();}
_tabSelected(event){if(!event.data.isUserGesture)
return;this.setPreferredTab(event.data.tabId);this._updateContents();}
_layersView(){if(this._lazyLayersView)
return this._lazyLayersView;this._lazyLayersView=new Timeline.TimelineLayersView(this._model.timelineModel(),this._showSnapshotInPaintProfiler.bind(this));return this._lazyLayersView;}
_paintProfilerView(){if(this._lazyPaintProfilerView)
return this._lazyPaintProfilerView;this._lazyPaintProfilerView=new Timeline.TimelinePaintProfilerView(this._model.frameModel());return this._lazyPaintProfilerView;}
_showSnapshotInPaintProfiler(snapshot){var paintProfilerView=this._paintProfilerView();paintProfilerView.setSnapshot(snapshot);if(!this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.PaintProfiler)){this._appendTab(Timeline.TimelineDetailsView.Tab.PaintProfiler,Common.UIString('Paint Profiler'),paintProfilerView,true);}
this._tabbedPane.selectTab(Timeline.TimelineDetailsView.Tab.PaintProfiler,true);}
_appendDetailsTabsForTraceEventAndShowDetails(event,content){this._setContent(content);if(event.name===TimelineModel.TimelineModel.RecordType.Paint||event.name===TimelineModel.TimelineModel.RecordType.RasterTask)
this._showEventInPaintProfiler(event);}
_showEventInPaintProfiler(event){const paintProfilerModel=SDK.targetManager.models(SDK.PaintProfilerModel)[0];if(!paintProfilerModel)
return;const paintProfilerView=this._paintProfilerView();const hasProfileData=paintProfilerView.setEvent(paintProfilerModel,event);if(!hasProfileData)
return;if(this._tabbedPane.hasTab(Timeline.TimelineDetailsView.Tab.PaintProfiler))
return;this._appendTab(Timeline.TimelineDetailsView.Tab.PaintProfiler,Common.UIString('Paint Profiler'),paintProfilerView);}
_updateSelectedRangeStats(startTime,endTime){if(this._model)
this._setContent(Timeline.TimelineUIUtils.buildRangeStats(this._model.timelineModel(),startTime,endTime));}};Timeline.TimelineDetailsView.Tab={Details:'Details',EventLog:'EventLog',CallTree:'CallTree',BottomUp:'BottomUp',PaintProfiler:'PaintProfiler',LayerViewer:'LayerViewer'};;Timeline.TimelineLoader=class{constructor(client){this._client=client;this._backingStorage=new Bindings.TempFileBackingStorage('tracing');this._tracingModel=new SDK.TracingModel(this._backingStorage);this._canceledCallback=null;this._state=Timeline.TimelineLoader.State.Initial;this._buffer='';this._firstRawChunk=true;this._firstChunk=true;this._loadedBytes=0;this._totalSize;this._jsonTokenizer=new TextUtils.TextUtils.BalancedJSONTokenizer(this._writeBalancedJSON.bind(this),true);}
static loadFromFile(file,client){var loader=new Timeline.TimelineLoader(client);var fileReader=Timeline.TimelineLoader._createFileReader(file,loader);loader._canceledCallback=fileReader.cancel.bind(fileReader);loader._totalSize=file.size;fileReader.start(loader);return loader;}
static loadFromURL(url,client){var stream=new Timeline.TimelineLoader(client);Host.ResourceLoader.loadAsStream(url,null,stream);return stream;}
static _createFileReader(file,delegate){return new Bindings.ChunkedFileReader(file,Timeline.TimelineLoader.TransferChunkLengthBytes,delegate);}
cancel(){this._tracingModel=null;this._backingStorage.reset();this._client.loadingComplete(null,null);this._client=null;if(this._canceledCallback)
this._canceledCallback();}
write(chunk){if(!this._client)
return;this._loadedBytes+=chunk.length;if(this._firstRawChunk)
this._client.loadingStarted();else
this._client.loadingProgress(this._totalSize?this._loadedBytes/this._totalSize:undefined);this._firstRawChunk=false;if(this._state===Timeline.TimelineLoader.State.Initial){if(chunk.startsWith('{"nodes":[')){this._state=Timeline.TimelineLoader.State.LoadingCPUProfileFormat;}else if(chunk[0]==='{'){this._state=Timeline.TimelineLoader.State.LookingForEvents;}else if(chunk[0]==='['){this._state=Timeline.TimelineLoader.State.ReadingEvents;}else{this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: Unknown JSON format'));return;}}
if(this._state===Timeline.TimelineLoader.State.LoadingCPUProfileFormat){this._buffer+=chunk;return;}
if(this._state===Timeline.TimelineLoader.State.LookingForEvents){var objectName='"traceEvents":';var startPos=this._buffer.length-objectName.length;this._buffer+=chunk;var pos=this._buffer.indexOf(objectName,startPos);if(pos===-1)
return;chunk=this._buffer.slice(pos+objectName.length);this._state=Timeline.TimelineLoader.State.ReadingEvents;}
if(this._state!==Timeline.TimelineLoader.State.ReadingEvents)
return;if(this._jsonTokenizer.write(chunk))
return;this._state=Timeline.TimelineLoader.State.SkippingTail;if(this._firstChunk){this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline input, wrong JSON brackets balance'));return;}}
_writeBalancedJSON(data){var json=data+']';if(!this._firstChunk){var commaIndex=json.indexOf(',');if(commaIndex!==-1)
json=json.slice(commaIndex+1);json='['+json;}
var items;try{items=(JSON.parse(json));}catch(e){this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: %s',e.toString()));return;}
if(this._firstChunk){this._firstChunk=false;if(this._looksLikeAppVersion(items[0])){this._reportErrorAndCancelLoading(Common.UIString('Legacy Timeline format is not supported.'));return;}}
try{this._tracingModel.addEvents(items);}catch(e){this._reportErrorAndCancelLoading(Common.UIString('Malformed timeline data: %s',e.toString()));}}
_reportErrorAndCancelLoading(message){if(message)
Common.console.error(message);this.cancel();}
_looksLikeAppVersion(item){return typeof item==='string'&&item.indexOf('Chrome')!==-1;}
close(){if(!this._client)
return;this._client.processingStarted();setTimeout(()=>this._finalizeTrace(),0);}
_finalizeTrace(){if(this._state===Timeline.TimelineLoader.State.LoadingCPUProfileFormat){this._parseCPUProfileFormat(this._buffer);this._buffer='';}
this._tracingModel.tracingComplete();this._client.loadingComplete(this._tracingModel,this._backingStorage);}
onTransferStarted(){}
onChunkTransferred(reader){}
onTransferFinished(){}
onError(reader,event){switch(event.target.error.name){case'NotFoundError':this._reportErrorAndCancelLoading(Common.UIString('File "%s" not found.',reader.fileName()));break;case'NotReadableError':this._reportErrorAndCancelLoading(Common.UIString('File "%s" is not readable',reader.fileName()));break;case'AbortError':break;default:this._reportErrorAndCancelLoading(Common.UIString('An error occurred while reading the file "%s"',reader.fileName()));}}
_parseCPUProfileFormat(text){var traceEvents;try{var profile=JSON.parse(text);traceEvents=TimelineModel.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile(profile);}catch(e){this._reportErrorAndCancelLoading(Common.UIString('Malformed CPU profile format'));return;}
this._tracingModel.addEvents(traceEvents);}};Timeline.TimelineLoader.TransferChunkLengthBytes=5000000;Timeline.TimelineLoader.Client=function(){};Timeline.TimelineLoader.Client.prototype={loadingStarted(){},loadingProgress(progress){},processingStarted(){},loadingComplete(tracingModel,backingStorage){},};Timeline.TimelineLoader.State={Initial:Symbol('Initial'),LookingForEvents:Symbol('LookingForEvents'),ReadingEvents:Symbol('ReadingEvents'),SkippingTail:Symbol('SkippingTail'),LoadingCPUProfileFormat:Symbol('LoadingCPUProfileFormat')};Timeline.TracingTimelineSaver=class{onTransferStarted(){}
onTransferFinished(){}
onChunkTransferred(reader){}
onError(reader,event){var error=event.target.error;Common.console.error(Common.UIString('Failed to save timeline: %s (%s, %s)',error.message,error.name,error.code));}};;Timeline.TimelineEventOverview=class extends PerfUI.TimelineOverviewBase{constructor(id,title){super();this.element.id='timeline-overview-'+id;this.element.classList.add('overview-strip');this._model=null;if(title)
this.element.createChild('div','timeline-overview-strip-title').textContent=title;}
setModel(model){this._model=model;}
_renderBar(begin,end,position,height,color){var x=begin;var width=end-begin;var ctx=this.context();ctx.fillStyle=color;ctx.fillRect(x,position,width,height);}};Timeline.TimelineEventOverviewInput=class extends Timeline.TimelineEventOverview{constructor(){super('input',null);}
update(){super.update();if(!this._model)
return;var events=this._model.timelineModel().mainThreadEvents();var height=this.height();var descriptors=Timeline.TimelineUIUtils.eventDispatchDesciptors();var descriptorsByType=new Map();var maxPriority=-1;for(var descriptor of descriptors){for(var type of descriptor.eventTypes)
descriptorsByType.set(type,descriptor);maxPriority=Math.max(maxPriority,descriptor.priority);}
var minWidth=2*window.devicePixelRatio;var timeOffset=this._model.timelineModel().minimumRecordTime();var timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;var canvasWidth=this.width();var scale=canvasWidth/timeSpan;for(var priority=0;priority<=maxPriority;++priority){for(var i=0;i<events.length;++i){var event=events[i];if(event.name!==TimelineModel.TimelineModel.RecordType.EventDispatch)
continue;var descriptor=descriptorsByType.get(event.args['data']['type']);if(!descriptor||descriptor.priority!==priority)
continue;var start=Number.constrain(Math.floor((event.startTime-timeOffset)*scale),0,canvasWidth);var end=Number.constrain(Math.ceil((event.endTime-timeOffset)*scale),0,canvasWidth);var width=Math.max(end-start,minWidth);this._renderBar(start,start+width,0,height,descriptor.color);}}}};Timeline.TimelineEventOverviewNetwork=class extends Timeline.TimelineEventOverview{constructor(){super('network',Common.UIString('NET'));}
update(){super.update();if(!this._model)
return;var timelineModel=this._model.timelineModel();var bandHeight=this.height()/2;var timeOffset=timelineModel.minimumRecordTime();var timeSpan=timelineModel.maximumRecordTime()-timeOffset;var canvasWidth=this.width();var scale=canvasWidth/timeSpan;var highPath=new Path2D();var lowPath=new Path2D();var priorities=Protocol.Network.ResourcePriority;var highPrioritySet=new Set([priorities.VeryHigh,priorities.High,priorities.Medium]);for(var request of timelineModel.networkRequests()){var path=highPrioritySet.has(request.priority)?highPath:lowPath;var s=Math.max(Math.floor((request.startTime-timeOffset)*scale),0);var e=Math.min(Math.ceil((request.endTime-timeOffset)*scale+1),canvasWidth);path.rect(s,0,e-s,bandHeight-1);}
var ctx=this.context();ctx.save();ctx.fillStyle='hsl(214, 60%, 60%)';ctx.fill((highPath));ctx.translate(0,bandHeight);ctx.fillStyle='hsl(214, 80%, 80%)';ctx.fill((lowPath));ctx.restore();}};Timeline.TimelineEventOverviewCPUActivity=class extends Timeline.TimelineEventOverview{constructor(){super('cpu-activity',Common.UIString('CPU'));this._backgroundCanvas=this.element.createChild('canvas','fill background');}
resetCanvas(){super.resetCanvas();this._backgroundCanvas.width=this.element.clientWidth*window.devicePixelRatio;this._backgroundCanvas.height=this.element.clientHeight*window.devicePixelRatio;}
update(){super.update();if(!this._model)
return;var timelineModel=this._model.timelineModel();var quantSizePx=4*window.devicePixelRatio;var width=this.width();var height=this.height();var baseLine=height;var timeOffset=timelineModel.minimumRecordTime();var timeSpan=timelineModel.maximumRecordTime()-timeOffset;var scale=width/timeSpan;var quantTime=quantSizePx/scale;var categories=Timeline.TimelineUIUtils.categories();var categoryOrder=['idle','loading','painting','rendering','scripting','other'];var otherIndex=categoryOrder.indexOf('other');var idleIndex=0;console.assert(idleIndex===categoryOrder.indexOf('idle'));for(var i=idleIndex+1;i<categoryOrder.length;++i)
categories[categoryOrder[i]]._overviewIndex=i;var backgroundContext=this._backgroundCanvas.getContext('2d');for(var thread of timelineModel.virtualThreads())
drawThreadEvents(backgroundContext,thread.events);applyPattern(backgroundContext);drawThreadEvents(this.context(),timelineModel.mainThreadEvents());function drawThreadEvents(ctx,events){var quantizer=new Timeline.Quantizer(timeOffset,quantTime,drawSample);var x=0;var categoryIndexStack=[];var paths=[];var lastY=[];for(var i=0;i<categoryOrder.length;++i){paths[i]=new Path2D();paths[i].moveTo(0,height);lastY[i]=height;}
function drawSample(counters){var y=baseLine;for(var i=idleIndex+1;i<categoryOrder.length;++i){var h=(counters[i]||0)/quantTime*height;y-=h;paths[i].bezierCurveTo(x,lastY[i],x,y,x+quantSizePx/2,y);lastY[i]=y;}
x+=quantSizePx;}
function onEventStart(e){var index=categoryIndexStack.length?categoryIndexStack.peekLast():idleIndex;quantizer.appendInterval(e.startTime,index);categoryIndexStack.push(Timeline.TimelineUIUtils.eventStyle(e).category._overviewIndex||otherIndex);}
function onEventEnd(e){quantizer.appendInterval(e.endTime,categoryIndexStack.pop());}
TimelineModel.TimelineModel.forEachEvent(events,onEventStart,onEventEnd);quantizer.appendInterval(timeOffset+timeSpan+quantTime,idleIndex);for(var i=categoryOrder.length-1;i>0;--i){paths[i].lineTo(width,height);ctx.fillStyle=categories[categoryOrder[i]].color;ctx.fill(paths[i]);}}
function applyPattern(ctx){var step=4*window.devicePixelRatio;ctx.save();ctx.lineWidth=step/Math.sqrt(8);for(var x=0.5;x<width+height;x+=step){ctx.moveTo(x,0);ctx.lineTo(x-height,height);}
ctx.globalCompositeOperation='destination-out';ctx.stroke();ctx.restore();}}};Timeline.TimelineEventOverviewResponsiveness=class extends Timeline.TimelineEventOverview{constructor(){super('responsiveness',null);}
update(){super.update();if(!this._model)
return;var height=this.height();var timeOffset=this._model.timelineModel().minimumRecordTime();var timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;var scale=this.width()/timeSpan;var frames=this._model.frames();var ctx=(this.context());var fillPath=new Path2D();var markersPath=new Path2D();for(var i=0;i<frames.length;++i){var frame=frames[i];if(!frame.hasWarnings())
continue;paintWarningDecoration(frame.startTime,frame.duration);}
var events=this._model.timelineModel().mainThreadEvents();for(var i=0;i<events.length;++i){if(!TimelineModel.TimelineData.forEvent(events[i]).warning)
continue;paintWarningDecoration(events[i].startTime,events[i].duration);}
ctx.fillStyle='hsl(0, 80%, 90%)';ctx.strokeStyle='red';ctx.lineWidth=2*window.devicePixelRatio;ctx.fill(fillPath);ctx.stroke(markersPath);function paintWarningDecoration(time,duration){var x=Math.round(scale*(time-timeOffset));var w=Math.round(scale*duration);fillPath.rect(x,0,w,height);markersPath.moveTo(x+w,0);markersPath.lineTo(x+w,height);}}};Timeline.TimelineFilmStripOverview=class extends Timeline.TimelineEventOverview{constructor(){super('filmstrip',null);this.reset();}
update(){super.update();var frames=this._model?this._model.filmStripModel().frames():[];if(!frames.length)
return;var drawGeneration=Symbol('drawGeneration');this._drawGeneration=drawGeneration;this._imageByFrame(frames[0]).then(image=>{if(this._drawGeneration!==drawGeneration)
return;if(!image.naturalWidth||!image.naturalHeight)
return;var imageHeight=this.height()-2*Timeline.TimelineFilmStripOverview.Padding;var imageWidth=Math.ceil(imageHeight*image.naturalWidth/image.naturalHeight);var popoverScale=Math.min(200/image.naturalWidth,1);this._emptyImage=new Image(image.naturalWidth*popoverScale,image.naturalHeight*popoverScale);this._drawFrames(imageWidth,imageHeight);});}
_imageByFrame(frame){var imagePromise=this._frameToImagePromise.get(frame);if(!imagePromise){imagePromise=frame.imageDataPromise().then(createImage);this._frameToImagePromise.set(frame,imagePromise);}
return imagePromise;function createImage(data){var fulfill;var promise=new Promise(f=>fulfill=f);var image=(createElement('img'));if(data){image.src='data:image/jpg;base64,'+data;image.addEventListener('load',()=>fulfill(image));image.addEventListener('error',()=>fulfill(image));}else{fulfill(image);}
return promise;}}
_drawFrames(imageWidth,imageHeight){if(!imageWidth||!this._model)
return;var filmStripModel=this._model.filmStripModel();if(!filmStripModel.frames().length)
return;var padding=Timeline.TimelineFilmStripOverview.Padding;var width=this.width();var zeroTime=filmStripModel.zeroTime();var spanTime=filmStripModel.spanTime();var scale=spanTime/width;var context=this.context();var drawGeneration=this._drawGeneration;context.beginPath();for(var x=padding;x<width;x+=imageWidth+2*padding){var time=zeroTime+(x+imageWidth/2)*scale;var frame=filmStripModel.frameByTimestamp(time);if(!frame)
continue;context.rect(x-0.5,0.5,imageWidth+1,imageHeight+1);this._imageByFrame(frame).then(drawFrameImage.bind(this,x));}
context.strokeStyle='#ddd';context.stroke();function drawFrameImage(x,image){if(this._drawGeneration!==drawGeneration)
return;context.drawImage(image,x,1,imageWidth,imageHeight);}}
overviewInfoPromise(x){if(!this._model||!this._model.filmStripModel().frames().length)
return Promise.resolve((null));var time=this.calculator().positionToTime(x);var frame=this._model.filmStripModel().frameByTimestamp(time);if(frame===this._lastFrame)
return Promise.resolve(this._lastElement);var imagePromise=frame?this._imageByFrame(frame):Promise.resolve(this._emptyImage);return imagePromise.then(createFrameElement.bind(this));function createFrameElement(image){var element=createElementWithClass('div','frame');element.createChild('div','thumbnail').appendChild(image);this._lastFrame=frame;this._lastElement=element;return element;}}
reset(){this._lastFrame=undefined;this._lastElement=null;this._frameToImagePromise=new Map();this._imageWidth=0;}};Timeline.TimelineFilmStripOverview.Padding=2;Timeline.TimelineEventOverviewFrames=class extends Timeline.TimelineEventOverview{constructor(){super('framerate',Common.UIString('FPS'));}
update(){super.update();if(!this._model)
return;var frames=this._model.frames();if(!frames.length)
return;var height=this.height();var padding=1*window.devicePixelRatio;var baseFrameDurationMs=1e3/60;var visualHeight=height-2*padding;var timeOffset=this._model.timelineModel().minimumRecordTime();var timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;var scale=this.width()/timeSpan;var baseY=height-padding;var ctx=this.context();var bottomY=baseY+10*window.devicePixelRatio;var x=0;var y=bottomY;var lineWidth=window.devicePixelRatio;var offset=lineWidth&1?0.5:0;var tickDepth=1.5*window.devicePixelRatio;ctx.beginPath();ctx.moveTo(0,y);for(var i=0;i<frames.length;++i){var frame=frames[i];x=Math.round((frame.startTime-timeOffset)*scale)+offset;ctx.lineTo(x,y);ctx.lineTo(x,y+tickDepth);y=frame.idle?bottomY:Math.round(baseY-visualHeight*Math.min(baseFrameDurationMs/frame.duration,1))-offset;ctx.lineTo(x,y+tickDepth);ctx.lineTo(x,y);}
var lastFrame=frames.peekLast();x=Math.round((lastFrame.startTime+lastFrame.duration-timeOffset)*scale)+offset;ctx.lineTo(x,y);ctx.lineTo(x,bottomY);ctx.fillStyle='hsl(110, 50%, 88%)';ctx.strokeStyle='hsl(110, 50%, 60%)';ctx.lineWidth=lineWidth;ctx.fill();ctx.stroke();}};Timeline.TimelineEventOverviewMemory=class extends Timeline.TimelineEventOverview{constructor(){super('memory',Common.UIString('HEAP'));this._heapSizeLabel=this.element.createChild('div','memory-graph-label');}
resetHeapSizeLabels(){this._heapSizeLabel.textContent='';}
update(){super.update();var ratio=window.devicePixelRatio;var events=this._model?this._model.timelineModel().mainThreadEvents():[];if(!events.length){this.resetHeapSizeLabels();return;}
var lowerOffset=3*ratio;var maxUsedHeapSize=0;var minUsedHeapSize=100000000000;var minTime=this._model.timelineModel().minimumRecordTime();var maxTime=this._model.timelineModel().maximumRecordTime();function isUpdateCountersEvent(event){return event.name===TimelineModel.TimelineModel.RecordType.UpdateCounters;}
events=events.filter(isUpdateCountersEvent);function calculateMinMaxSizes(event){var counters=event.args.data;if(!counters||!counters.jsHeapSizeUsed)
return;maxUsedHeapSize=Math.max(maxUsedHeapSize,counters.jsHeapSizeUsed);minUsedHeapSize=Math.min(minUsedHeapSize,counters.jsHeapSizeUsed);}
events.forEach(calculateMinMaxSizes);minUsedHeapSize=Math.min(minUsedHeapSize,maxUsedHeapSize);var lineWidth=1;var width=this.width();var height=this.height()-lowerOffset;var xFactor=width/(maxTime-minTime);var yFactor=(height-lineWidth)/Math.max(maxUsedHeapSize-minUsedHeapSize,1);var histogram=new Array(width);function buildHistogram(event){var counters=event.args.data;if(!counters||!counters.jsHeapSizeUsed)
return;var x=Math.round((event.startTime-minTime)*xFactor);var y=Math.round((counters.jsHeapSizeUsed-minUsedHeapSize)*yFactor);histogram[x]=Math.max(histogram[x]||0,y);}
events.forEach(buildHistogram);var ctx=this.context();var heightBeyondView=height+lowerOffset+lineWidth;ctx.translate(0.5,0.5);ctx.beginPath();ctx.moveTo(-lineWidth,heightBeyondView);var y=0;var isFirstPoint=true;var lastX=0;for(var x=0;x<histogram.length;x++){if(typeof histogram[x]==='undefined')
continue;if(isFirstPoint){isFirstPoint=false;y=histogram[x];ctx.lineTo(-lineWidth,height-y);}
var nextY=histogram[x];if(Math.abs(nextY-y)>2&&Math.abs(x-lastX)>1)
ctx.lineTo(x,height-y);y=nextY;ctx.lineTo(x,height-y);lastX=x;}
ctx.lineTo(width+lineWidth,height-y);ctx.lineTo(width+lineWidth,heightBeyondView);ctx.closePath();ctx.fillStyle='hsla(220, 90%, 70%, 0.2)';ctx.fill();ctx.lineWidth=lineWidth;ctx.strokeStyle='hsl(220, 90%, 70%)';ctx.stroke();this._heapSizeLabel.textContent=Common.UIString('%s \u2013 %s',Number.bytesToString(minUsedHeapSize),Number.bytesToString(maxUsedHeapSize));}};Timeline.Quantizer=class{constructor(startTime,quantDuration,callback){this._lastTime=startTime;this._quantDuration=quantDuration;this._callback=callback;this._counters=[];this._remainder=quantDuration;}
appendInterval(time,group){var interval=time-this._lastTime;if(interval<=this._remainder){this._counters[group]=(this._counters[group]||0)+interval;this._remainder-=interval;this._lastTime=time;return;}
this._counters[group]=(this._counters[group]||0)+this._remainder;this._callback(this._counters);interval-=this._remainder;while(interval>=this._quantDuration){var counters=[];counters[group]=this._quantDuration;this._callback(counters);interval-=this._quantDuration;}
this._counters=[];this._counters[group]=interval;this._lastTime=time;this._remainder=this._quantDuration-interval;}};;Timeline.TimelineFilters={};Timeline.TimelineFilters.IsLong=class extends TimelineModel.TimelineModelFilter{constructor(){super();this._minimumRecordDuration=0;}
setMinimumRecordDuration(value){this._minimumRecordDuration=value;}
accept(event){var duration=event.endTime?event.endTime-event.startTime:0;return duration>=this._minimumRecordDuration;}};Timeline.TimelineFilters.Category=class extends TimelineModel.TimelineModelFilter{constructor(){super();}
accept(event){return!Timeline.TimelineUIUtils.eventStyle(event).category.hidden;}};Timeline.TimelineFilters.RegExp=class extends TimelineModel.TimelineModelFilter{constructor(regExp){super();this._regExp;this.setRegExp(regExp||null);}
setRegExp(regExp){this._regExp=regExp;}
regExp(){return this._regExp;}
accept(event){return!this._regExp||Timeline.TimelineUIUtils.testContentMatching(event,this._regExp);}};;Timeline.TimelineFlameChartDataProvider=class{constructor(filters){this.reset();this._font='11px '+Host.fontFamily();this._filters=filters;this._timelineData=null;this._currentLevel=0;this._performanceModel=null;this._model=null;this._consoleColorGenerator=new PerfUI.FlameChart.ColorGenerator({min:30,max:55},{min:70,max:100,count:6},50,0.7);this._extensionColorGenerator=new PerfUI.FlameChart.ColorGenerator({min:210,max:300},{min:70,max:100,count:6},70,0.7);var defaultGroupStyle={padding:4,height:17,collapsible:true,color:UI.themeSupport.patchColorText('#222',UI.ThemeSupport.ColorUsage.Foreground),backgroundColor:UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background),font:this._font,nestingLevel:0,shareHeaderLine:true};this._headerLevel1=(Object.assign({},defaultGroupStyle,{shareHeaderLine:false}));this._headerLevel2=(Object.assign({},defaultGroupStyle,{padding:2,nestingLevel:1,collapsible:false}));this._staticHeader=(Object.assign({},defaultGroupStyle,{collapsible:false}));this._interactionsHeaderLevel1=(Object.assign({useFirstLineForOverview:true},defaultGroupStyle));this._interactionsHeaderLevel2=(Object.assign({},defaultGroupStyle,{padding:2,nestingLevel:1}));this._flowEventIndexById=new Map();}
setModel(performanceModel){this.reset();this._performanceModel=performanceModel;this._model=performanceModel&&performanceModel.timelineModel();}
entryTitle(entryIndex){var entryType=this._entryType(entryIndex);if(entryType===Timeline.TimelineFlameChartEntryType.Event){var event=(this._entryData[entryIndex]);if(event.phase===SDK.TracingModel.Phase.AsyncStepInto||event.phase===SDK.TracingModel.Phase.AsyncStepPast)
return event.name+':'+event.args['step'];if(event._blackboxRoot)
return Common.UIString('Blackboxed');var name=Timeline.TimelineUIUtils.eventStyle(event).title;var detailsText=Timeline.TimelineUIUtils.buildDetailsTextForTraceEvent(event,this._model.targetByEvent(event));if(event.name===TimelineModel.TimelineModel.RecordType.JSFrame&&detailsText)
return detailsText;return detailsText?Common.UIString('%s (%s)',name,detailsText):name;}
if(entryType===Timeline.TimelineFlameChartEntryType.ExtensionEvent){var event=(this._entryData[entryIndex]);return event.name;}
var title=this._entryIndexToTitle[entryIndex];if(!title){title=Common.UIString('Unexpected entryIndex %d',entryIndex);console.error(title);}
return title;}
textColor(index){var event=this._entryData[index];return event&&event._blackboxRoot?'#888':Timeline.FlameChartStyle.textColor;}
entryFont(index){return this._font;}
reset(){this._currentLevel=0;this._timelineData=null;this._entryData=[];this._entryParent=[];this._entryTypeByLevel=[];this._entryIndexToTitle=[];this._markers=[];this._asyncColorByCategory=new Map();this._asyncColorByInteractionPhase=new Map();this._extensionInfo=[];}
maxStackDepth(){return this._currentLevel;}
timelineData(){if(this._timelineData)
return this._timelineData;this._timelineData=new PerfUI.FlameChart.TimelineData([],[],[],[]);if(!this._model)
return this._timelineData;this._flowEventIndexById.clear();this._minimumBoundary=this._model.minimumRecordTime();this._timeSpan=this._model.isEmpty()?1000:this._model.maximumRecordTime()-this._minimumBoundary;this._currentLevel=0;this._appendHeader(Common.UIString('Frames'),this._staticHeader);this._appendFrameBars(this._performanceModel.frames());this._appendHeader(Common.UIString('Interactions'),this._interactionsHeaderLevel1);this._appendInteractionRecords();var eventEntryType=Timeline.TimelineFlameChartEntryType.Event;var asyncEventGroups=TimelineModel.TimelineModel.AsyncEventGroup;var inputLatencies=this._model.mainThreadAsyncEvents().get(asyncEventGroups.input);if(inputLatencies&&inputLatencies.length){var title=Timeline.TimelineUIUtils.titleForAsyncEventGroup(asyncEventGroups.input);this._appendAsyncEventsGroup(title,inputLatencies,this._interactionsHeaderLevel2,eventEntryType);}
var animations=this._model.mainThreadAsyncEvents().get(asyncEventGroups.animation);if(animations&&animations.length){var title=Timeline.TimelineUIUtils.titleForAsyncEventGroup(asyncEventGroups.animation);this._appendAsyncEventsGroup(title,animations,this._interactionsHeaderLevel2,eventEntryType);}
var threads=this._model.virtualThreads();if(!Runtime.experiments.isEnabled('timelinePerFrameTrack')){this._appendThreadTimelineData(Common.UIString('Main'),this._model.mainThreadEvents(),this._model.mainThreadAsyncEvents(),true);}else{this._appendThreadTimelineData(Common.UIString('Page'),this._model.eventsForFrame(TimelineModel.TimelineModel.PageFrame.mainFrameId),this._model.mainThreadAsyncEvents(),true);for(var frame of this._model.rootFrames()){frame.children.forEach(this._appendFrameEvents.bind(this,0));}}
var compositorThreads=threads.filter(thread=>thread.name.startsWith('CompositorTileWorker'));var otherThreads=threads.filter(thread=>!thread.name.startsWith('CompositorTileWorker'));if(compositorThreads.length){this._appendHeader(Common.UIString('Raster'),this._headerLevel1);for(var i=0;i<compositorThreads.length;++i){this._appendSyncEvents(compositorThreads[i].events,Common.UIString('Rasterizer Thread %d',i),this._headerLevel2,eventEntryType);}}
this._appendGPUEvents();otherThreads.forEach(thread=>this._appendThreadTimelineData(thread.name||Common.UIString('Thread %d',thread.id),thread.events,thread.asyncEventsByGroup));for(let extensionIndex=0;extensionIndex<this._extensionInfo.length;extensionIndex++)
this._innerAppendExtensionEvents(extensionIndex);function compareStartTime(a,b){return a.startTime()-b.startTime();}
this._markers.sort(compareStartTime);this._timelineData.markers=this._markers;this._flowEventIndexById.clear();return this._timelineData;}
minimumBoundary(){return this._minimumBoundary;}
totalTime(){return this._timeSpan;}
_appendFrameEvents(level,frame){var events=this._model.eventsForFrame(frame.id);var clonedHeader=Object.assign({},this._headerLevel1);clonedHeader.nestingLevel=level;this._appendSyncEvents(events,Timeline.TimelineUIUtils.displayNameForFrame(frame),(clonedHeader),Timeline.TimelineFlameChartEntryType.Event);frame.children.forEach(this._appendFrameEvents.bind(this,level+1));}
_appendThreadTimelineData(threadTitle,syncEvents,asyncEvents,forceExpanded){var entryType=Timeline.TimelineFlameChartEntryType.Event;this._appendAsyncEvents(asyncEvents);this._appendSyncEvents(syncEvents,threadTitle,this._headerLevel1,entryType,forceExpanded);}
_appendSyncEvents(events,title,style,entryType,forceExpanded){var isExtension=entryType===Timeline.TimelineFlameChartEntryType.ExtensionEvent;var openEvents=[];var flowEventsEnabled=Runtime.experiments.isEnabled('timelineFlowEvents');var blackboxingEnabled=!isExtension&&Runtime.experiments.isEnabled('blackboxJSFramesOnTimeline');var maxStackDepth=0;for(var i=0;i<events.length;++i){var e=events[i];if(!isExtension&&TimelineModel.TimelineModel.isMarkerEvent(e)){this._markers.push(new Timeline.TimelineFlameChartMarker(e.startTime,e.startTime-this._model.minimumRecordTime(),Timeline.TimelineUIUtils.markerStyleForEvent(e)));}
if(!SDK.TracingModel.isFlowPhase(e.phase)){if(!e.endTime&&e.phase!==SDK.TracingModel.Phase.Instant)
continue;if(SDK.TracingModel.isAsyncPhase(e.phase))
continue;if(!isExtension&&!this._isVisible(e))
continue;}
while(openEvents.length&&openEvents.peekLast().endTime<=e.startTime)
openEvents.pop();e._blackboxRoot=false;if(blackboxingEnabled&&this._isBlackboxedEvent(e)){var parent=openEvents.peekLast();if(parent&&parent._blackboxRoot)
continue;e._blackboxRoot=true;}
if(title){this._appendHeader(title,style,forceExpanded);title='';}
var level=this._currentLevel+openEvents.length;if(flowEventsEnabled)
this._appendFlowEvent(e,level);var index=this._appendEvent(e,level);if(openEvents.length)
this._entryParent[index]=openEvents.peekLast();if(!isExtension&&TimelineModel.TimelineModel.isMarkerEvent(e))
this._timelineData.entryTotalTimes[this._entryData.length]=undefined;maxStackDepth=Math.max(maxStackDepth,openEvents.length+1);if(e.endTime)
openEvents.push(e);}
this._entryTypeByLevel.length=this._currentLevel+maxStackDepth;this._entryTypeByLevel.fill(entryType,this._currentLevel);this._currentLevel+=maxStackDepth;}
_isBlackboxedEvent(event){if(event.name!==TimelineModel.TimelineModel.RecordType.JSFrame)
return false;var url=event.args['data']['url'];return url&&this._isBlackboxedURL(url);}
_isBlackboxedURL(url){return Bindings.blackboxManager.isBlackboxedURL(url);}
_appendAsyncEvents(asyncEvents){var entryType=Timeline.TimelineFlameChartEntryType.Event;var groups=TimelineModel.TimelineModel.AsyncEventGroup;var groupArray=Object.keys(groups).map(key=>groups[key]);groupArray.remove(groups.animation);groupArray.remove(groups.input);for(var groupIndex=0;groupIndex<groupArray.length;++groupIndex){var group=groupArray[groupIndex];var events=asyncEvents.get(group);if(!events)
continue;var title=Timeline.TimelineUIUtils.titleForAsyncEventGroup(group);this._appendAsyncEventsGroup(title,events,this._headerLevel1,entryType);}}
_appendAsyncEventsGroup(header,events,style,entryType){var lastUsedTimeByLevel=[];var groupHeaderAppended=false;for(var i=0;i<events.length;++i){var asyncEvent=events[i];if(!this._isVisible(asyncEvent))
continue;if(!groupHeaderAppended){this._appendHeader(header,style);groupHeaderAppended=true;}
var startTime=asyncEvent.startTime;var level;for(level=0;level<lastUsedTimeByLevel.length&&lastUsedTimeByLevel[level]>startTime;++level){}
this._appendAsyncEvent(asyncEvent,this._currentLevel+level);lastUsedTimeByLevel[level]=asyncEvent.endTime;}
this._entryTypeByLevel.length=this._currentLevel+lastUsedTimeByLevel.length;this._entryTypeByLevel.fill(entryType,this._currentLevel);this._currentLevel+=lastUsedTimeByLevel.length;}
_appendGPUEvents(){var eventType=Timeline.TimelineFlameChartEntryType.Event;var gpuEvents=this._model.gpuEvents();if(this._appendSyncEvents(gpuEvents,Common.UIString('GPU'),this._headerLevel1,eventType,false))
++this._currentLevel;}
_appendInteractionRecords(){this._performanceModel.interactionRecords().forEach(this._appendSegment,this);this._entryTypeByLevel[this._currentLevel++]=Timeline.TimelineFlameChartEntryType.InteractionRecord;}
_appendFrameBars(frames){var style=Timeline.TimelineUIUtils.markerStyleForFrame();this._entryTypeByLevel[this._currentLevel]=Timeline.TimelineFlameChartEntryType.Frame;for(var i=0;i<frames.length;++i){this._markers.push(new Timeline.TimelineFlameChartMarker(frames[i].startTime,frames[i].startTime-this._model.minimumRecordTime(),style));this._appendFrame(frames[i]);}
++this._currentLevel;}
_entryType(entryIndex){return this._entryTypeByLevel[this._timelineData.entryLevels[entryIndex]];}
prepareHighlightedEntryInfo(entryIndex){var time='';var title;var warning;var type=this._entryType(entryIndex);if(type===Timeline.TimelineFlameChartEntryType.Event){var event=(this._entryData[entryIndex]);var totalTime=event.duration;var selfTime=event.selfTime;var eps=1e-6;if(typeof totalTime==='number'){time=Math.abs(totalTime-selfTime)>eps&&selfTime>eps?Common.UIString('%s (self %s)',Number.millisToString(totalTime,true),Number.millisToString(selfTime,true)):Number.millisToString(totalTime,true);}
title=this.entryTitle(entryIndex);warning=Timeline.TimelineUIUtils.eventWarning(event);}else if(type===Timeline.TimelineFlameChartEntryType.Frame){var frame=(this._entryData[entryIndex]);time=Common.UIString('%s ~ %.0f\xa0fps',Number.preciseMillisToString(frame.duration,1),(1000/frame.duration));title=frame.idle?Common.UIString('Idle Frame'):Common.UIString('Frame');if(frame.hasWarnings()){warning=createElement('span');warning.textContent=Common.UIString('Long frame');}}else{return null;}
var element=createElement('div');var root=UI.createShadowRootWithCoreStyles(element,'timeline/timelineFlamechartPopover.css');var contents=root.createChild('div','timeline-flamechart-popover');contents.createChild('span','timeline-info-time').textContent=time;contents.createChild('span','timeline-info-title').textContent=title;if(warning){warning.classList.add('timeline-info-warning');contents.appendChild(warning);}
return element;}
entryColor(entryIndex){function patchColorAndCache(cache,key,lookupColor){var color=cache.get(key);if(color)
return color;var parsedColor=Common.Color.parse(lookupColor(key));color=parsedColor.setAlpha(0.7).asString(Common.Color.Format.RGBA)||'';cache.set(key,color);return color;}
var type=this._entryType(entryIndex);if(type===Timeline.TimelineFlameChartEntryType.Event){var event=(this._entryData[entryIndex]);if(!SDK.TracingModel.isAsyncPhase(event.phase))
return Timeline.TimelineUIUtils.eventColor(event);if(event.hasCategory(TimelineModel.TimelineModel.Category.Console)||event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming))
return this._consoleColorGenerator.colorForID(event.name);if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){var phase=TimelineModel.TimelineIRModel.phaseForEvent(event)||TimelineModel.TimelineIRModel.Phases.Uncategorized;return patchColorAndCache(this._asyncColorByInteractionPhase,phase,Timeline.TimelineUIUtils.interactionPhaseColor);}
var category=Timeline.TimelineUIUtils.eventStyle(event).category;return patchColorAndCache(this._asyncColorByCategory,category,()=>category.color);}
if(type===Timeline.TimelineFlameChartEntryType.Frame)
return'white';if(type===Timeline.TimelineFlameChartEntryType.InteractionRecord)
return'transparent';if(type===Timeline.TimelineFlameChartEntryType.ExtensionEvent){var event=(this._entryData[entryIndex]);return this._extensionColorGenerator.colorForID(event.name);}
return'';}
decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixels){var data=this._entryData[entryIndex];var type=this._entryType(entryIndex);if(type===Timeline.TimelineFlameChartEntryType.Frame){var vPadding=1;var hPadding=1;var frame=(data);barX+=hPadding;barWidth-=2*hPadding;barY+=vPadding;barHeight-=2*vPadding+1;context.fillStyle=frame.idle?'white':(frame.hasWarnings()?'#fad1d1':'#d7f0d1');context.fillRect(barX,barY,barWidth,barHeight);var frameDurationText=Number.preciseMillisToString(frame.duration,1);var textWidth=context.measureText(frameDurationText).width;if(barWidth>=textWidth){context.fillStyle=this.textColor(entryIndex);context.fillText(frameDurationText,barX+(barWidth-textWidth)/2,barY+barHeight-3);}
return true;}
if(type===Timeline.TimelineFlameChartEntryType.InteractionRecord){var color=Timeline.TimelineUIUtils.interactionPhaseColor((data));context.fillStyle=color;context.fillRect(barX,barY,barWidth-1,2);context.fillRect(barX,barY-3,2,3);context.fillRect(barX+barWidth-3,barY-3,2,3);return false;}
if(type===Timeline.TimelineFlameChartEntryType.Event){var event=(data);if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){var timeWaitingForMainThread=TimelineModel.TimelineData.forEvent(event).timeWaitingForMainThread;if(timeWaitingForMainThread){context.fillStyle='hsla(0, 70%, 60%, 1)';var width=Math.floor(unclippedBarX-barX+timeWaitingForMainThread*timeToPixels);context.fillRect(barX,barY+barHeight-3,width,2);}}
if(TimelineModel.TimelineData.forEvent(event).warning)
paintWarningDecoration(barX,barWidth-1.5);}
function paintWarningDecoration(x,width){var triangleSize=8;context.save();context.beginPath();context.rect(x,barY,width,barHeight);context.clip();context.beginPath();context.fillStyle='red';context.moveTo(x+width-triangleSize,barY);context.lineTo(x+width,barY);context.lineTo(x+width,barY+triangleSize);context.fill();context.restore();}
return false;}
forceDecoration(entryIndex){var type=this._entryType(entryIndex);if(type===Timeline.TimelineFlameChartEntryType.Frame)
return true;if(type===Timeline.TimelineFlameChartEntryType.Event){var event=(this._entryData[entryIndex]);return!!TimelineModel.TimelineData.forEvent(event).warning;}
return false;}
appendExtensionEvents(entry){this._extensionInfo.push(entry);if(this._timelineData)
this._innerAppendExtensionEvents(this._extensionInfo.length-1);}
_innerAppendExtensionEvents(index){var entry=this._extensionInfo[index];var entryType=Timeline.TimelineFlameChartEntryType.ExtensionEvent;var allThreads=[].concat(...entry.model.sortedProcesses().map(process=>process.sortedThreads()));if(!allThreads.length)
return;this._appendHeader(entry.title,this._headerLevel1);for(let thread of allThreads){this._appendAsyncEventsGroup(thread.name(),thread.asyncEvents(),this._headerLevel2,entryType);this._appendSyncEvents(thread.events(),thread.name(),this._headerLevel2,entryType,false);}}
_appendHeader(title,style,expanded){this._timelineData.groups.push({startLevel:this._currentLevel,name:title,expanded:expanded,style:style});}
_appendEvent(event,level){var index=this._entryData.length;this._entryData.push(event);this._timelineData.entryLevels[index]=level;this._timelineData.entryTotalTimes[index]=event.duration||Timeline.TimelineFlameChartDataProvider.InstantEventVisibleDurationMs;this._timelineData.entryStartTimes[index]=event.startTime;event[Timeline.TimelineFlameChartDataProvider._indexSymbol]=index;return index;}
_appendAsyncEvent(asyncEvent,level){if(SDK.TracingModel.isNestableAsyncPhase(asyncEvent.phase)){this._appendEvent(asyncEvent,level);return;}
var steps=asyncEvent.steps;var eventOffset=steps.length>1&&steps[1].phase===SDK.TracingModel.Phase.AsyncStepPast?1:0;for(var i=0;i<steps.length-1;++i){var index=this._entryData.length;this._entryData.push(steps[i+eventOffset]);var startTime=steps[i].startTime;this._timelineData.entryLevels[index]=level;this._timelineData.entryTotalTimes[index]=steps[i+1].startTime-startTime;this._timelineData.entryStartTimes[index]=startTime;}}
_appendFlowEvent(event,level){var timelineData=this._timelineData;function pushStartFlow(event){var flowIndex=timelineData.flowStartTimes.length;timelineData.flowStartTimes.push(event.startTime);timelineData.flowStartLevels.push(level);return flowIndex;}
function pushEndFlow(event,flowIndex){timelineData.flowEndTimes[flowIndex]=event.startTime;timelineData.flowEndLevels[flowIndex]=level;}
switch(event.phase){case SDK.TracingModel.Phase.FlowBegin:this._flowEventIndexById.set(event.id,pushStartFlow(event));break;case SDK.TracingModel.Phase.FlowStep:pushEndFlow(event,this._flowEventIndexById.get(event.id));this._flowEventIndexById.set(event.id,pushStartFlow(event));break;case SDK.TracingModel.Phase.FlowEnd:pushEndFlow(event,this._flowEventIndexById.get(event.id));this._flowEventIndexById.delete(event.id);break;}}
_appendFrame(frame){var index=this._entryData.length;this._entryData.push(frame);this._entryIndexToTitle[index]=Number.millisToString(frame.duration,true);this._timelineData.entryLevels[index]=this._currentLevel;this._timelineData.entryTotalTimes[index]=frame.duration;this._timelineData.entryStartTimes[index]=frame.startTime;}
_appendSegment(segment){var index=this._entryData.length;this._entryData.push((segment.data));this._entryIndexToTitle[index]=(segment.data);this._timelineData.entryLevels[index]=this._currentLevel;this._timelineData.entryTotalTimes[index]=segment.end-segment.begin;this._timelineData.entryStartTimes[index]=segment.begin;}
createSelection(entryIndex){var type=this._entryType(entryIndex);var timelineSelection=null;if(type===Timeline.TimelineFlameChartEntryType.Event){timelineSelection=Timeline.TimelineSelection.fromTraceEvent((this._entryData[entryIndex]));}else if(type===Timeline.TimelineFlameChartEntryType.Frame){timelineSelection=Timeline.TimelineSelection.fromFrame((this._entryData[entryIndex]));}
if(timelineSelection)
this._lastSelection=new Timeline.TimelineFlameChartView.Selection(timelineSelection,entryIndex);return timelineSelection;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
canJumpToEntry(entryIndex){return false;}
entryIndexForSelection(selection){if(!selection||selection.type()===Timeline.TimelineSelection.Type.Range)
return-1;if(this._lastSelection&&this._lastSelection.timelineSelection.object()===selection.object())
return this._lastSelection.entryIndex;var index=this._entryData.indexOf((selection.object()));if(index!==-1)
this._lastSelection=new Timeline.TimelineFlameChartView.Selection(selection,index);return index;}
selectionForEvent(event){var entryIndex=this._entryData.indexOf(event);return this.createSelection(entryIndex);}
_isVisible(event){return this._filters.every(function(filter){return filter.accept(event);});}
buildFlowForInitiator(entryIndex){if(this._lastInitiatorEntry===entryIndex)
return false;this._lastInitiatorEntry=entryIndex;var event=this.eventByIndex(entryIndex);var td=this._timelineData;td.flowStartTimes=[];td.flowStartLevels=[];td.flowEndTimes=[];td.flowEndLevels=[];while(event){var initiator;for(;event;event=this._eventParent(event)){initiator=TimelineModel.TimelineData.forEvent(event).initiator();if(initiator)
break;}
if(!initiator)
break;var eventIndex=event[Timeline.TimelineFlameChartDataProvider._indexSymbol];var initiatorIndex=initiator[Timeline.TimelineFlameChartDataProvider._indexSymbol];td.flowStartTimes.push(initiator.endTime||initiator.startTime);td.flowStartLevels.push(td.entryLevels[initiatorIndex]);td.flowEndTimes.push(event.startTime);td.flowEndLevels.push(td.entryLevels[eventIndex]);event=initiator;}
return true;}
_eventParent(event){return this._entryParent[event[Timeline.TimelineFlameChartDataProvider._indexSymbol]]||null;}
eventByIndex(entryIndex){return this._entryType(entryIndex)===Timeline.TimelineFlameChartEntryType.Event?(this._entryData[entryIndex]):null;}};Timeline.TimelineFlameChartDataProvider.InstantEventVisibleDurationMs=0.001;Timeline.TimelineFlameChartDataProvider._indexSymbol=Symbol('index');;Timeline.TimelineFlameChartNetworkDataProvider=class{constructor(){this._font='11px '+Host.fontFamily();this.setModel(null);this._style={padding:4,height:17,collapsible:true,color:UI.themeSupport.patchColorText('#222',UI.ThemeSupport.ColorUsage.Foreground),font:this._font,backgroundColor:UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background),nestingLevel:0,useFirstLineForOverview:false,useDecoratorsForOverview:true,shareHeaderLine:false};this._group={startLevel:0,name:Common.UIString('Network'),expanded:false,style:this._style};}
setModel(performanceModel){this._model=performanceModel&&performanceModel.timelineModel();this._maxLevel=0;this._timelineData=null;this._requests=[];}
isEmpty(){this.timelineData();return!this._requests.length;}
maxStackDepth(){return this._maxLevel;}
timelineData(){if(this._timelineData)
return this._timelineData;this._requests=[];this._timelineData=new PerfUI.FlameChart.TimelineData([],[],[],[]);if(this._model)
this._appendTimelineData(this._model.mainThreadEvents());return this._timelineData;}
minimumBoundary(){return this._minimumBoundary;}
totalTime(){return this._timeSpan;}
setWindowTimes(startTime,endTime){this._startTime=startTime;this._endTime=endTime;this._updateTimelineData();}
createSelection(index){if(index===-1)
return null;var request=this._requests[index];this._lastSelection=new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request),index);return this._lastSelection.timelineSelection;}
entryIndexForSelection(selection){if(!selection)
return-1;if(this._lastSelection&&this._lastSelection.timelineSelection.object()===selection.object())
return this._lastSelection.entryIndex;if(selection.type()!==Timeline.TimelineSelection.Type.NetworkRequest)
return-1;var request=(selection.object());var index=this._requests.indexOf(request);if(index!==-1){this._lastSelection=new Timeline.TimelineFlameChartView.Selection(Timeline.TimelineSelection.fromNetworkRequest(request),index);}
return index;}
entryColor(index){var request=(this._requests[index]);var category=Timeline.TimelineUIUtils.networkRequestCategory(request);return Timeline.TimelineUIUtils.networkCategoryColor(category);}
textColor(index){return Timeline.FlameChartStyle.textColor;}
entryTitle(index){var request=(this._requests[index]);var parsedURL=new Common.ParsedURL(request.url||'');return parsedURL.isValid?`${parsedURL.displayName} (${parsedURL.host})`:request.url||null;}
entryFont(index){return this._font;}
decorateEntry(index,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixelRatio){var request=(this._requests[index]);if(!request.timing)
return false;function timeToPixel(time){return Math.floor(unclippedBarX+(time-startTime)*timeToPixelRatio);}
var minBarWidthPx=2;var startTime=request.startTime;var endTime=request.endTime;var requestTime=request.timing.requestTime*1000;var sendStart=Math.max(timeToPixel(requestTime+request.timing.sendStart),unclippedBarX);var headersEnd=Math.max(timeToPixel(requestTime+request.timing.receiveHeadersEnd),sendStart);var finish=Math.max(timeToPixel(request.finishTime||endTime),headersEnd+minBarWidthPx);var end=Math.max(timeToPixel(endTime),finish);context.fillStyle='hsla(0, 100%, 100%, 0.8)';context.fillRect(sendStart+0.5,barY+0.5,headersEnd-sendStart-0.5,barHeight-2);context.fillStyle=UI.themeSupport.patchColorText('white',UI.ThemeSupport.ColorUsage.Background);context.fillRect(barX,barY-0.5,sendStart-barX,barHeight);context.fillRect(finish,barY-0.5,barX+barWidth-finish,barHeight);function drawTick(begin,end,y){var tickHeightPx=6;context.moveTo(begin,y-tickHeightPx/2);context.lineTo(begin,y+tickHeightPx/2);context.moveTo(begin,y);context.lineTo(end,y);}
context.lineWidth=1;context.strokeStyle='#ccc';var lineY=Math.floor(barY+barHeight/2)+0.5;var leftTick=Math.floor(unclippedBarX)+0.5;var rightTick=end-0.5;drawTick(leftTick,sendStart,lineY);drawTick(rightTick,finish,lineY);context.stroke();if(typeof request.priority==='string'){var color=this._colorForPriority(request.priority);if(color){context.fillStyle=color;context.fillRect(sendStart+0.5,barY+0.5,3.5,3.5);}}
var textStart=Math.max(sendStart,0);var textWidth=finish-textStart;var minTextWidthPx=20;if(textWidth>=minTextWidthPx){text=this.entryTitle(index)||'';if(request.fromServiceWorker)
text='⚙ '+text;if(text){var textPadding=4;var textBaseline=5;var textBaseHeight=barHeight-textBaseline;var trimmedText=UI.trimTextEnd(context,text,textWidth-2*textPadding);context.fillStyle='#333';context.fillText(trimmedText,textStart+textPadding,barY+textBaseHeight);}}
return true;}
forceDecoration(index){return true;}
prepareHighlightedEntryInfo(index){var maxURLChars=80;var request=(this._requests[index]);if(!request.url)
return null;var element=createElement('div');var root=UI.createShadowRootWithCoreStyles(element,'timeline/timelineFlamechartPopover.css');var contents=root.createChild('div','timeline-flamechart-popover');var duration=request.endTime-request.startTime;if(request.startTime&&isFinite(duration))
contents.createChild('span','timeline-info-network-time').textContent=Number.millisToString(duration);if(typeof request.priority==='string'){var div=contents.createChild('span');div.textContent=NetworkConditions.uiLabelForPriority((request.priority));div.style.color=this._colorForPriority(request.priority)||'black';}
contents.createChild('span').textContent=request.url.trimMiddle(maxURLChars);return element;}
_colorForPriority(priority){if(!this._priorityToValue){var priorities=Protocol.Network.ResourcePriority;this._priorityToValue=new Map([[priorities.VeryLow,1],[priorities.Low,2],[priorities.Medium,3],[priorities.High,4],[priorities.VeryHigh,5]]);}
var value=this._priorityToValue.get(priority);return value?`hsla(214, 80%, 50%, ${value / 5})`:null;}
_appendTimelineData(events){this._minimumBoundary=this._model.minimumRecordTime();this._maximumBoundary=this._model.maximumRecordTime();this._timeSpan=this._model.isEmpty()?1000:this._maximumBoundary-this._minimumBoundary;this._model.networkRequests().forEach(this._appendEntry.bind(this));this._updateTimelineData();}
_updateTimelineData(){if(!this._timelineData)
return;var lastTimeByLevel=[];var maxLevel=0;for(var i=0;i<this._requests.length;++i){var r=this._requests[i];var visible=r.startTime<this._endTime&&r.endTime>this._startTime;if(!visible){this._timelineData.entryLevels[i]=-1;continue;}
while(lastTimeByLevel.length&&lastTimeByLevel.peekLast()<=r.startTime)
lastTimeByLevel.pop();this._timelineData.entryLevels[i]=lastTimeByLevel.length;lastTimeByLevel.push(r.endTime);maxLevel=Math.max(maxLevel,lastTimeByLevel.length);}
for(var i=0;i<this._requests.length;++i){if(this._timelineData.entryLevels[i]===-1)
this._timelineData.entryLevels[i]=maxLevel;}
this._timelineData=new PerfUI.FlameChart.TimelineData(this._timelineData.entryLevels,this._timelineData.entryTotalTimes,this._timelineData.entryStartTimes,[this._group]);this._maxLevel=maxLevel;}
_appendEntry(request){this._requests.push(request);this._timelineData.entryStartTimes.push(request.startTime);this._timelineData.entryTotalTimes.push(request.endTime-request.startTime);this._timelineData.entryLevels.push(this._requests.length-1);}
preferredHeight(){return this._style.height*(this._group.expanded?Number.constrain(this._maxLevel+1,4,8.5):1);}
isExpanded(){return this._group.expanded;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
canJumpToEntry(entryIndex){return false;}};;Timeline.TimelineFlameChartView=class extends UI.VBox{constructor(delegate,filters){super();this.element.classList.add('timeline-flamechart');this._delegate=delegate;this._model=null;this._searchResults;this._filters=filters;this._showMemoryGraphSetting=Common.settings.createSetting('timelineShowMemory',false);this._networkSplitWidget=new UI.SplitWidget(false,false,'timelineFlamechartMainView',150);var mainViewGroupExpansionSetting=Common.settings.createSetting('timelineFlamechartMainViewGroupExpansion',{});this._mainDataProvider=new Timeline.TimelineFlameChartDataProvider(filters);this._mainFlameChart=new PerfUI.FlameChart(this._mainDataProvider,this,mainViewGroupExpansionSetting);this._mainFlameChart.alwaysShowVerticalScroll();this._mainFlameChart.enableRuler(false);this._networkFlameChartGroupExpansionSetting=Common.settings.createSetting('timelineFlamechartNetworkViewGroupExpansion',{});this._networkDataProvider=new Timeline.TimelineFlameChartNetworkDataProvider();this._networkFlameChart=new PerfUI.FlameChart(this._networkDataProvider,this,this._networkFlameChartGroupExpansionSetting);this._networkFlameChart.alwaysShowVerticalScroll();this._networkPane=new UI.VBox();this._networkPane.setMinimumSize(23,23);this._networkFlameChart.show(this._networkPane.element);this._splitResizer=this._networkPane.element.createChild('div','timeline-flamechart-resizer');this._networkSplitWidget.hideDefaultResizer(true);this._networkSplitWidget.installResizer(this._splitResizer);this._networkSplitWidget.setMainWidget(this._mainFlameChart);this._networkSplitWidget.setSidebarWidget(this._networkPane);this._chartSplitWidget=new UI.SplitWidget(false,true,'timelineCountersSplitViewState');this._countersView=new Timeline.CountersGraph(this._delegate);this._chartSplitWidget.setMainWidget(this._networkSplitWidget);this._chartSplitWidget.setSidebarWidget(this._countersView);this._chartSplitWidget.hideDefaultResizer();this._chartSplitWidget.installResizer((this._countersView.resizerElement()));this._updateCountersGraphToggle();this._detailsSplitWidget=new UI.SplitWidget(false,true,'timelinePanelDetailsSplitViewState');this._detailsSplitWidget.element.classList.add('timeline-details-split');this._detailsView=new Timeline.TimelineDetailsView(filters,delegate);this._detailsSplitWidget.installResizer(this._detailsView.headerElement());this._detailsSplitWidget.setMainWidget(this._chartSplitWidget);this._detailsSplitWidget.setSidebarWidget(this._detailsView);this._detailsSplitWidget.show(this.element);this._onMainEntrySelected=this._onEntrySelected.bind(this,this._mainDataProvider);this._onNetworkEntrySelected=this._onEntrySelected.bind(this,this._networkDataProvider);this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onMainEntrySelected,this);this._networkFlameChart.addEventListener(PerfUI.FlameChart.Events.EntrySelected,this._onNetworkEntrySelected,this);this._mainFlameChart.addEventListener(PerfUI.FlameChart.Events.EntryHighlighted,this._onEntryHighlighted,this);this._nextExtensionIndex=0;this._boundRefresh=this._refresh.bind(this);}
resizerElement(){return null;}
requestWindowTimes(windowStartTime,windowEndTime){this._delegate.requestWindowTimes(windowStartTime,windowEndTime);}
updateRangeSelection(startTime,endTime){this._delegate.select(Timeline.TimelineSelection.fromRange(startTime,endTime));}
setModel(model){var extensionDataAdded=Timeline.PerformanceModel.Events.ExtensionDataAdded;if(this._model)
this._model.removeEventListener(extensionDataAdded,this._appendExtensionData,this);this._model=model;if(this._model)
this._model.addEventListener(extensionDataAdded,this._appendExtensionData,this);this._mainDataProvider.setModel(this._model);this._networkDataProvider.setModel(this._model);this._countersView.setModel(this._model);this._detailsView.setModel(this._model);this._nextExtensionIndex=0;this._appendExtensionData();this._updateSearchHighlight(false,true);this._refresh();}
_refresh(){if(this._networkDataProvider.isEmpty()){this._mainFlameChart.enableRuler(true);this._networkSplitWidget.hideSidebar();}else{this._mainFlameChart.enableRuler(false);this._networkSplitWidget.showBoth();this.resizeToPreferredHeights();}
this._mainFlameChart.reset();this._networkFlameChart.reset();}
_appendExtensionData(){if(!this._model)
return;var extensions=this._model.extensionInfo();while(this._nextExtensionIndex<extensions.length)
this._mainDataProvider.appendExtensionEvents(extensions[this._nextExtensionIndex++]);this._mainFlameChart.scheduleUpdate();}
_onEntryHighlighted(commonEvent){SDK.OverlayModel.hideDOMNodeHighlight();var entryIndex=(commonEvent.data);var event=this._mainDataProvider.eventByIndex(entryIndex);if(!event)
return;var target=this._model&&this._model.timelineModel().targetByEvent(event);if(!target)
return;var timelineData=TimelineModel.TimelineData.forEvent(event);var backendNodeId=timelineData.backendNodeId;if(!backendNodeId)
return;new SDK.DeferredDOMNode(target,backendNodeId).highlight();}
highlightEvent(event){var entryIndex=event?this._mainDataProvider.entryIndexForSelection(Timeline.TimelineSelection.fromTraceEvent(event)):-1;if(entryIndex>=0)
this._mainFlameChart.highlightEntry(entryIndex);else
this._mainFlameChart.hideHighlight();}
willHide(){this._networkFlameChartGroupExpansionSetting.removeChangeListener(this.resizeToPreferredHeights,this);this._showMemoryGraphSetting.removeChangeListener(this._updateCountersGraphToggle,this);Bindings.blackboxManager.removeChangeListener(this._boundRefresh);}
wasShown(){this._networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights,this);this._showMemoryGraphSetting.addChangeListener(this._updateCountersGraphToggle,this);Bindings.blackboxManager.addChangeListener(this._boundRefresh);if(this._needsResizeToPreferredHeights)
this.resizeToPreferredHeights();this._mainFlameChart.scheduleUpdate();this._networkFlameChart.scheduleUpdate();}
_updateCountersGraphToggle(){if(this._showMemoryGraphSetting.get())
this._chartSplitWidget.showBoth();else
this._chartSplitWidget.hideSidebar();}
view(){return this;}
setWindowTimes(startTime,endTime){this._mainFlameChart.setWindowTimes(startTime,endTime);this._networkFlameChart.setWindowTimes(startTime,endTime);this._networkDataProvider.setWindowTimes(startTime,endTime);this._countersView.setWindowTimes(startTime,endTime);this._windowStartTime=startTime;this._windowEndTime=endTime;}
_highlightSearchResult(event,regex,select){if(!event){this._delegate.select(null);return;}
var timelineSelection=this._mainDataProvider.selectionForEvent(event);if(timelineSelection)
this._delegate.select(timelineSelection);}
setSelection(selection){var index=this._mainDataProvider.entryIndexForSelection(selection);this._mainFlameChart.setSelectedEntry(index);index=this._networkDataProvider.entryIndexForSelection(selection);this._networkFlameChart.setSelectedEntry(index);if(selection&&this._detailsView)
this._detailsView.setSelection(selection);}
_onEntrySelected(dataProvider,event){var entryIndex=(event.data);if(Runtime.experiments.isEnabled('timelineEventInitiators')&&dataProvider===this._mainDataProvider){if(this._mainDataProvider.buildFlowForInitiator(entryIndex))
this._mainFlameChart.scheduleUpdate();}
this._delegate.select(dataProvider.createSelection(entryIndex));}
resizeToPreferredHeights(){if(!this.isShowing()){this._needsResizeToPreferredHeights=true;return;}
this._needsResizeToPreferredHeights=false;this._networkPane.element.classList.toggle('timeline-network-resizer-disabled',!this._networkDataProvider.isExpanded());this._networkSplitWidget.setSidebarSize(this._networkDataProvider.preferredHeight()+this._splitResizer.clientHeight+PerfUI.FlameChart.HeaderHeight+
2);}
setSearchableView(searchableView){this._searchableView=searchableView;}
jumpToNextSearchResult(){if(!this._searchResults||!this._searchResults.length)
return;var index=this._selectedSearchResult?this._searchResults.indexOf(this._selectedSearchResult):-1;this._jumpToSearchResult(index+1);}
jumpToPreviousSearchResult(){if(!this._searchResults||!this._searchResults.length)
return;var index=this._selectedSearchResult?this._searchResults.indexOf(this._selectedSearchResult):0;this._jumpToSearchResult(index-1);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}
_jumpToSearchResult(index){this._selectSearchResult(mod(index,this._searchResults.length));this._highlightSearchResult(this._selectedSearchResult,this._searchRegex,true);}
_selectSearchResult(index){this._selectedSearchResult=this._searchResults[index];this._searchableView.updateCurrentMatchIndex(index);}
_clearHighlight(){this._highlightSearchResult(null);}
_updateSearchHighlight(revealRecord,shouldJump,jumpBackwards){if(!this._searchRegex){this._clearHighlight();return;}
if(!this._searchResults)
this._updateSearchResults(shouldJump,jumpBackwards);this._highlightSearchResult(this._selectedSearchResult,this._searchRegex,revealRecord);}
_updateSearchResults(shouldJump,jumpBackwards){if(!this._searchRegex)
return;var events=this._model?this._model.timelineModel().mainThreadEvents():[];var filters=[...this._filters,new Timeline.TimelineFilters.RegExp(this._searchRegex)];var matches=[];var startIndex=events.lowerBound(this._windowStartTime,(time,event)=>time-event.startTime);for(var index=startIndex;index<events.length;++index){var event=events[index];if(event.startTime>this._windowEndTime)
break;if(TimelineModel.TimelineModel.isVisible(filters,event))
matches.push(event);}
var matchesCount=matches.length;if(matchesCount){this._searchResults=matches;this._searchableView.updateSearchMatchesCount(matchesCount);var selectedIndex=matches.indexOf(this._selectedSearchResult);if(shouldJump&&selectedIndex===-1)
selectedIndex=jumpBackwards?this._searchResults.length-1:0;this._selectSearchResult(selectedIndex);}else{this._searchableView.updateSearchMatchesCount(0);delete this._selectedSearchResult;}}
searchCanceled(){this._clearHighlight();delete this._searchResults;delete this._selectedSearchResult;delete this._searchRegex;}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchRegex=searchConfig.toSearchRegex();delete this._searchResults;this._updateSearchHighlight(true,shouldJump,jumpBackwards);}};Timeline.TimelineFlameChartView.Selection=class{constructor(selection,entryIndex){this.timelineSelection=selection;this.entryIndex=entryIndex;}};Timeline.FlameChartStyle={textColor:'#333'};Timeline.TimelineFlameChartEntryType={Frame:Symbol('Frame'),Event:Symbol('Event'),InteractionRecord:Symbol('InteractionRecord'),ExtensionEvent:Symbol('ExtensionEvent')};Timeline.TimelineFlameChartMarker=class{constructor(startTime,startOffset,style){this._startTime=startTime;this._startOffset=startOffset;this._style=style;}
startTime(){return this._startTime;}
color(){return this._style.color;}
title(){var startTime=Number.millisToString(this._startOffset);return Common.UIString('%s at %s',this._style.title,startTime);}
draw(context,x,height,pixelsPerMillisecond){var lowPriorityVisibilityThresholdInPixelsPerMs=4;if(this._style.lowPriority&&pixelsPerMillisecond<lowPriorityVisibilityThresholdInPixelsPerMs)
return;context.save();if(!this._style.lowPriority){context.strokeStyle=this._style.color;context.lineWidth=2;context.beginPath();context.moveTo(x,0);context.lineTo(x,height);context.stroke();}
if(this._style.tall){context.strokeStyle=this._style.color;context.lineWidth=this._style.lineWidth;context.translate(this._style.lineWidth<1||(this._style.lineWidth&1)?0.5:0,0.5);context.beginPath();context.moveTo(x,height);context.setLineDash(this._style.dashStyle);context.lineTo(x,context.canvas.height);context.stroke();}
context.restore();}};;Timeline.TimelineTreeModeView=class extends UI.VBox{constructor(delegate,innerTreeView){super();this._treeView=innerTreeView;this._treeView.show(this.element);}
resizerElement(){return null;}
highlightEvent(event){}
setModel(model){this._treeView.setModel(model);}
setSelection(){}
setWindowTimes(startTime,endTime){this._treeView.setRange(startTime,endTime);}
view(){return this;}};;Timeline.TimelineTreeView=class extends UI.VBox{constructor(){super();this._model=null;this._tree=null;this.element.classList.add('timeline-tree-view');}
static eventNameForSorting(event){if(event.name===TimelineModel.TimelineModel.RecordType.JSFrame){var data=event.args['data'];return data['functionName']+'@'+(data['scriptId']||data['url']||'');}
return event.name+':@'+TimelineModel.TimelineProfileTree.eventURL(event);}
setSearchableView(searchableView){this._searchableView=searchableView;}
setModel(model){this._model=model;this._populateThreadSelector();this.refreshTree();}
model(){return this._model;}
init(filters){this._linkifier=new Components.Linkifier();this._textFilter=new Timeline.TimelineFilters.RegExp();this._filters=[...filters,this._textFilter];const columns=([]);this.populateColumns(columns);this._splitWidget=new UI.SplitWidget(true,true,'timelineTreeViewDetailsSplitWidget');var mainView=new UI.VBox();var toolbar=new UI.Toolbar('',mainView.element);this.populateToolbar(toolbar);this._dataGrid=new DataGrid.SortableDataGrid(columns);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SortingChanged,this._sortingChanged,this);this._dataGrid.element.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.setRowContextMenuCallback(this._onContextMenu.bind(this));this._dataGrid.asWidget().show(mainView.element);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._updateDetailsForSelection,this);this._detailsView=new UI.VBox();this._detailsView.element.classList.add('timeline-details-view','timeline-details-view-body');this._splitWidget.setMainWidget(mainView);this._splitWidget.setSidebarWidget(this._detailsView);this._splitWidget.hideSidebar();this._splitWidget.show(this.element);this._splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged,this._updateDetailsForSelection,this);this._lastSelectedNode;}
lastSelectedNode(){return this._lastSelectedNode;}
updateContents(selection){this.setRange(selection.startTime(),selection.endTime());}
setRange(startTime,endTime){this._startTime=startTime;this._endTime=endTime;this.refreshTree();}
_exposePercentages(){return false;}
populateToolbar(toolbar){this._threadSelector=new UI.ToolbarComboBox(targetChanged.bind(this));this._threadSelector.setMaxWidth(230);this._currentThreadSetting=Common.settings.createSetting('timelineTreeCurrentThread',0);toolbar.appendToolbarItem(this._threadSelector);this._textFilterUI=new UI.ToolbarInput(Common.UIString('Filter'),0,0,true);this._textFilterUI.addEventListener(UI.ToolbarInput.Event.TextChanged,textFilterChanged,this);toolbar.appendToolbarItem(this._textFilterUI);function textFilterChanged(){var searchQuery=this._textFilterUI.value();this._textFilter.setRegExp(searchQuery?createPlainTextSearchRegex(searchQuery,'i'):null);this.refreshTree();}
function targetChanged(){this._currentThreadSetting.set(this._threadSelector.selectedIndex());this.refreshTree();}}
_modelEvents(){if(!this._model||this._threadSelector.size()===0)
return[];return this._threadEvents[Number(this._threadSelector.selectedOption().value)];}
_populateThreadSelector(){this._threadSelector.removeOptions();this._threadEvents=[];if(!this._model){this._threadSelector.setVisible(false);this._currentThreadSetting.set(0);return;}
var option=this._threadSelector.createOption(Common.UIString('Main'),'','0');this._threadEvents.push(this._model.timelineModel().mainThreadEvents());this._threadSelector.addOption(option);for(var thread of this._model.timelineModel().virtualThreads()){if(!thread.name)
continue;if(!thread.events.some(e=>e.name===TimelineModel.TimelineModel.RecordType.JSFrame))
continue;option=this._threadSelector.createOption(thread.name,'',String(this._threadEvents.length));this._threadSelector.addOption(option);this._threadEvents.push(thread.events);}
this._threadSelector.setSelectedIndex(this._currentThreadSetting.get());this._threadSelector.setVisible(this._threadEvents.length>1);}
_onHover(node){}
_appendContextMenuItems(contextMenu,node){}
_linkifyLocation(event){var target=this._model.timelineModel().targetByEvent(event);if(!target)
return null;var frame=TimelineModel.TimelineProfileTree.eventStackFrame(event);if(!frame)
return null;return this._linkifier.maybeLinkifyConsoleCallFrame(target,frame);}
selectProfileNode(treeNode,suppressSelectedEvent){var pathToRoot=[];for(var node=treeNode;node;node=node.parent)
pathToRoot.push(node);for(var i=pathToRoot.length-1;i>0;--i){var gridNode=this.dataGridNodeForTreeNode(pathToRoot[i]);if(gridNode&&gridNode.dataGrid)
gridNode.expand();}
var gridNode=this.dataGridNodeForTreeNode(treeNode);if(gridNode.dataGrid){gridNode.reveal();gridNode.select(suppressSelectedEvent);}}
refreshTree(){this._linkifier.reset();if(this._searchableView)
this._searchableView.cancelSearch();this._dataGrid.rootNode().removeChildren();if(!this._model){this._updateDetailsForSelection();return;}
this._root=this._buildTree();var children=this._root.children();var maxSelfTime=0;var maxTotalTime=0;var totalUsedTime=this._root.totalTime-this._root.selfTime;for(var child of children.values()){maxSelfTime=Math.max(maxSelfTime,child.selfTime);maxTotalTime=Math.max(maxTotalTime,child.totalTime);}
for(var child of children.values()){var gridNode=new Timeline.TimelineTreeView.TreeGridNode(child,totalUsedTime,maxSelfTime,maxTotalTime,this);this._dataGrid.insertChild(gridNode);}
this._sortingChanged();this._updateDetailsForSelection();}
_buildTree(){throw new Error('Not Implemented');}
buildTopDownTree(doNotAggregate,groupIdCallback){return new TimelineModel.TimelineProfileTree.TopDownRootNode(this._modelEvents(),this._filters,this._startTime,this._endTime,doNotAggregate,groupIdCallback);}
populateColumns(columns){columns.push({id:'self',title:Common.UIString('Self Time'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'total',title:Common.UIString('Total Time'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'activity',title:Common.UIString('Activity'),disclosure:true,sortable:true});}
_sortingChanged(){var columnId=this._dataGrid.sortColumnId();if(!columnId)
return;var sortFunction;switch(columnId){case'startTime':sortFunction=compareStartTime;break;case'self':sortFunction=compareNumericField.bind(null,'selfTime');break;case'total':sortFunction=compareNumericField.bind(null,'totalTime');break;case'activity':sortFunction=compareName;break;default:console.assert(false,'Unknown sort field: '+columnId);return;}
this._dataGrid.sortNodes(sortFunction,!this._dataGrid.isSortOrderAscending());function compareNumericField(field,a,b){var nodeA=(a);var nodeB=(b);return nodeA._profileNode[field]-nodeB._profileNode[field];}
function compareStartTime(a,b){var nodeA=(a);var nodeB=(b);return nodeA._profileNode.event.startTime-nodeB._profileNode.event.startTime;}
function compareName(a,b){var nodeA=(a);var nodeB=(b);var nameA=Timeline.TimelineTreeView.eventNameForSorting(nodeA._profileNode.event);var nameB=Timeline.TimelineTreeView.eventNameForSorting(nodeB._profileNode.event);return nameA.localeCompare(nameB);}}
_updateDetailsForSelection(){var selectedNode=this._dataGrid.selectedNode?(this._dataGrid.selectedNode)._profileNode:null;if(selectedNode===this._lastSelectedNode)
return;this._lastSelectedNode=selectedNode;if(this._splitWidget.showMode()===UI.SplitWidget.ShowMode.OnlyMain)
return;this._detailsView.detachChildWidgets();this._detailsView.element.removeChildren();if(!selectedNode||!this._showDetailsForNode(selectedNode)){var banner=this._detailsView.element.createChild('div','full-widget-dimmed-banner');banner.createTextChild(Common.UIString('Select item for details.'));}}
_showDetailsForNode(node){return false;}
_onMouseMove(event){var gridNode=event.target&&(event.target instanceof Node)?(this._dataGrid.dataGridNodeFromNode((event.target))):null;var profileNode=gridNode&&gridNode._profileNode;if(profileNode===this._lastHoveredProfileNode)
return;this._lastHoveredProfileNode=profileNode;this._onHover(profileNode);}
_onContextMenu(contextMenu,gridNode){var profileNode=gridNode._profileNode;if(!profileNode)
return;this._appendContextMenuItems(contextMenu,profileNode);}
dataGridNodeForTreeNode(treeNode){return treeNode[Timeline.TimelineTreeView.TreeGridNode._gridNodeSymbol]||null;}
searchCanceled(){this._searchResults=[];this._currentResult=0;}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchResults=[];this._currentResult=0;if(!this._root)
return;var searchRegex=searchConfig.toSearchRegex();this._searchResults=this._root.searchTree(event=>Timeline.TimelineUIUtils.testContentMatching(event,searchRegex));this._searchableView.updateSearchMatchesCount(this._searchResults.length);}
jumpToNextSearchResult(){if(!this._searchResults.length)
return;this.selectProfileNode(this._searchResults[this._currentResult],false);this._currentResult=mod(this._currentResult+1,this._searchResults.length);}
jumpToPreviousSearchResult(){if(!this._searchResults.length)
return;this.selectProfileNode(this._searchResults[this._currentResult],false);this._currentResult=mod(this._currentResult-1,this._searchResults.length);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}};Timeline.TimelineTreeView.GridNode=class extends DataGrid.SortableDataGridNode{constructor(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView){super(null,false);this._populated=false;this._profileNode=profileNode;this._treeView=treeView;this._grandTotalTime=grandTotalTime;this._maxSelfTime=maxSelfTime;this._maxTotalTime=maxTotalTime;}
createCell(columnId){if(columnId==='activity')
return this._createNameCell(columnId);return this._createValueCell(columnId)||super.createCell(columnId);}
_createNameCell(columnId){const cell=this.createTD(columnId);const container=cell.createChild('div','name-container');const icon=container.createChild('div','activity-icon');const name=container.createChild('div','activity-name');const event=this._profileNode.event;if(this._profileNode.isGroupNode()){const treeView=(this._treeView);const info=treeView._displayInfoForGroupNode(this._profileNode);name.textContent=info.name;icon.style.backgroundColor=info.color;}else if(event){const data=event.args['data'];const deoptReason=data&&data['deoptReason'];if(deoptReason)
container.createChild('div','activity-warning').title=Common.UIString('Not optimized: %s',deoptReason);name.textContent=Timeline.TimelineUIUtils.eventTitle(event);const link=this._treeView._linkifyLocation(event);if(link)
container.createChild('div','activity-link').appendChild(link);icon.style.backgroundColor=Timeline.TimelineUIUtils.eventColor(event);}
return cell;}
_createValueCell(columnId){if(columnId!=='self'&&columnId!=='total'&&columnId!=='startTime')
return null;var showPercents=false;var value;var maxTime;switch(columnId){case'startTime':value=this._profileNode.event.startTime-this._treeView._model.timelineModel().minimumRecordTime();break;case'self':value=this._profileNode.selfTime;maxTime=this._maxSelfTime;showPercents=true;break;case'total':value=this._profileNode.totalTime;maxTime=this._maxTotalTime;showPercents=true;break;default:return null;}
var cell=this.createTD(columnId);cell.className='numeric-column';var textDiv=cell.createChild('div');textDiv.createChild('span').textContent=Common.UIString('%.1f\xa0ms',value);if(showPercents&&this._treeView._exposePercentages()){textDiv.createChild('span','percent-column').textContent=Common.UIString('%.1f\xa0%%',value/this._grandTotalTime*100);}
if(maxTime){textDiv.classList.add('background-percent-bar');cell.createChild('div','background-bar-container').createChild('div','background-bar').style.width=(value*100/maxTime).toFixed(1)+'%';}
return cell;}};Timeline.TimelineTreeView.TreeGridNode=class extends Timeline.TimelineTreeView.GridNode{constructor(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView){super(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView);this.setHasChildren(this._profileNode.hasChildren());profileNode[Timeline.TimelineTreeView.TreeGridNode._gridNodeSymbol]=this;}
populate(){if(this._populated)
return;this._populated=true;if(!this._profileNode.children)
return;for(var node of this._profileNode.children().values()){var gridNode=new Timeline.TimelineTreeView.TreeGridNode(node,this._grandTotalTime,this._maxSelfTime,this._maxTotalTime,this._treeView);this.insertChildOrdered(gridNode);}}};Timeline.TimelineTreeView.TreeGridNode._gridNodeSymbol=Symbol('treeGridNode');Timeline.AggregatedTimelineTreeView=class extends Timeline.TimelineTreeView{constructor(filters){super();this._groupBySetting=Common.settings.createSetting('timelineTreeGroupBy',Timeline.AggregatedTimelineTreeView.GroupBy.None);this._groupByCombobox=new UI.ToolbarComboBox(this._onGroupByChanged.bind(this));this.init(filters);this._stackView=new Timeline.TimelineStackView(this);this._stackView.addEventListener(Timeline.TimelineStackView.Events.SelectionChanged,this._onStackViewSelectionChanged,this);}
wasShown(){var groupById=this._groupBySetting.get();var option=this._groupByCombobox.options().find(option=>option.value===groupById);if(option)
this._groupByCombobox.select(option);}
updateContents(selection){this._updateExtensionResolver();super.updateContents(selection);var rootNode=this._dataGrid.rootNode();if(rootNode.children.length)
rootNode.children[0].revealAndSelect();}
_updateExtensionResolver(){this._executionContextNamesByOrigin=new Map();for(var runtimeModel of SDK.targetManager.models(SDK.RuntimeModel)){for(var context of runtimeModel.executionContexts())
this._executionContextNamesByOrigin.set(context.origin,context.name);}}
_displayInfoForGroupNode(node){var categories=Timeline.TimelineUIUtils.categories();var color=node.id?Timeline.TimelineUIUtils.eventColor((node.event)):categories['other'].color;switch(this._groupBySetting.get()){case Timeline.AggregatedTimelineTreeView.GroupBy.Category:var category=categories[node.id]||categories['other'];return{name:category.title,color:category.color};case Timeline.AggregatedTimelineTreeView.GroupBy.Domain:case Timeline.AggregatedTimelineTreeView.GroupBy.Subdomain:var name=node.id;if(Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(name))
name=Common.UIString('[Chrome extensions overhead]');else if(Timeline.AggregatedTimelineTreeView._isV8NativeURL(name))
name=Common.UIString('[V8 Runtime]');else if(name.startsWith('chrome-extension'))
name=this._executionContextNamesByOrigin.get(name)||name;return{name:name||Common.UIString('unattributed'),color:color};case Timeline.AggregatedTimelineTreeView.GroupBy.EventName:var name=node.event.name===TimelineModel.TimelineModel.RecordType.JSFrame?Common.UIString('JavaScript'):Timeline.TimelineUIUtils.eventTitle(node.event);return{name:name,color:node.event.name===TimelineModel.TimelineModel.RecordType.JSFrame?Timeline.TimelineUIUtils.eventStyle(node.event).category.color:color};case Timeline.AggregatedTimelineTreeView.GroupBy.URL:break;case Timeline.AggregatedTimelineTreeView.GroupBy.Frame:var frame=this._model.timelineModel().pageFrameById(node.id);var frameName=frame?Timeline.TimelineUIUtils.displayNameForFrame(frame,80):Common.UIString('Page');return{name:frameName,color:color};default:console.assert(false,'Unexpected aggregation type');}
return{name:node.id||Common.UIString('unattributed'),color:color};}
populateToolbar(toolbar){super.populateToolbar(toolbar);function addGroupingOption(name,id){var option=this._groupByCombobox.createOption(name,'',id);this._groupByCombobox.addOption(option);if(id===this._groupBySetting.get())
this._groupByCombobox.select(option);}
const groupBy=Timeline.AggregatedTimelineTreeView.GroupBy;addGroupingOption.call(this,Common.UIString('No Grouping'),groupBy.None);addGroupingOption.call(this,Common.UIString('Group by Activity'),groupBy.EventName);addGroupingOption.call(this,Common.UIString('Group by Category'),groupBy.Category);addGroupingOption.call(this,Common.UIString('Group by Domain'),groupBy.Domain);addGroupingOption.call(this,Common.UIString('Group by Subdomain'),groupBy.Subdomain);addGroupingOption.call(this,Common.UIString('Group by URL'),groupBy.URL);addGroupingOption.call(this,Common.UIString('Group by Frame'),groupBy.Frame);toolbar.appendToolbarItem(this._groupByCombobox);toolbar.appendSpacer();toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton(Common.UIString('heaviest stack')));}
_buildHeaviestStack(treeNode){console.assert(!!treeNode.parent,'Attempt to build stack for tree root');var result=[];for(var node=treeNode;node&&node.parent;node=node.parent)
result.push(node);result=result.reverse();for(node=treeNode;node&&node.children()&&node.children().size;){var children=Array.from(node.children().values());node=children.reduce((a,b)=>a.totalTime>b.totalTime?a:b);result.push(node);}
return result;}
_exposePercentages(){return true;}
_onGroupByChanged(){this._groupBySetting.set(this._groupByCombobox.selectedOption().value);this.refreshTree();}
_onStackViewSelectionChanged(){var treeNode=this._stackView.selectedTreeNode();if(treeNode)
this.selectProfileNode(treeNode,true);}
_showDetailsForNode(node){var stack=this._buildHeaviestStack(node);this._stackView.setStack(stack,node);this._stackView.show(this._detailsView.element);return true;}
_groupingFunction(groupBy){function groupByURL(event){return TimelineModel.TimelineProfileTree.eventURL(event)||'';}
function groupByDomain(groupSubdomains,event){var url=TimelineModel.TimelineProfileTree.eventURL(event)||'';if(Timeline.AggregatedTimelineTreeView._isExtensionInternalURL(url))
return Timeline.AggregatedTimelineTreeView._extensionInternalPrefix;if(Timeline.AggregatedTimelineTreeView._isV8NativeURL(url))
return Timeline.AggregatedTimelineTreeView._v8NativePrefix;var parsedURL=url.asParsedURL();if(!parsedURL)
return'';if(parsedURL.scheme==='chrome-extension')
return parsedURL.scheme+'://'+parsedURL.host;if(!groupSubdomains)
return parsedURL.host;if(/^[.0-9]+$/.test(parsedURL.host))
return parsedURL.host;var domainMatch=/([^.]*\.)?[^.]*$/.exec(parsedURL.host);return domainMatch&&domainMatch[0]||'';}
switch(groupBy){case Timeline.AggregatedTimelineTreeView.GroupBy.None:return null;case Timeline.AggregatedTimelineTreeView.GroupBy.EventName:return event=>Timeline.TimelineUIUtils.eventStyle(event).title;case Timeline.AggregatedTimelineTreeView.GroupBy.Category:return event=>Timeline.TimelineUIUtils.eventStyle(event).category.name;case Timeline.AggregatedTimelineTreeView.GroupBy.Subdomain:return groupByDomain.bind(null,false);case Timeline.AggregatedTimelineTreeView.GroupBy.Domain:return groupByDomain.bind(null,true);case Timeline.AggregatedTimelineTreeView.GroupBy.URL:return groupByURL;case Timeline.AggregatedTimelineTreeView.GroupBy.Frame:return event=>TimelineModel.TimelineData.forEvent(event).frameId;default:console.assert(false,`Unexpected aggregation setting: ${groupBy}`);return null;}}
_appendContextMenuItems(contextMenu,node){if(this._groupBySetting.get()!==Timeline.AggregatedTimelineTreeView.GroupBy.Frame)
return;if(!node.isGroupNode())
return;var frame=this._model.timelineModel().pageFrameById(node.id);if(!frame||!frame.ownerNode)
return;contextMenu.appendApplicableItems(frame.ownerNode);}
static _isExtensionInternalURL(url){return url.startsWith(Timeline.AggregatedTimelineTreeView._extensionInternalPrefix);}
static _isV8NativeURL(url){return url.startsWith(Timeline.AggregatedTimelineTreeView._v8NativePrefix);}};Timeline.AggregatedTimelineTreeView._extensionInternalPrefix='extensions::';Timeline.AggregatedTimelineTreeView._v8NativePrefix='native ';Timeline.AggregatedTimelineTreeView.GroupBy={None:'None',EventName:'EventName',Category:'Category',Domain:'Domain',Subdomain:'Subdomain',URL:'URL',Frame:'Frame'};Timeline.CallTreeTimelineTreeView=class extends Timeline.AggregatedTimelineTreeView{constructor(filters){super(filters);this._dataGrid.markColumnAsSortedBy('total',DataGrid.DataGrid.Order.Descending);}
_buildTree(){var grouping=this._groupBySetting.get();return this.buildTopDownTree(false,this._groupingFunction(grouping));}};Timeline.BottomUpTimelineTreeView=class extends Timeline.AggregatedTimelineTreeView{constructor(filters){super(filters);this._dataGrid.markColumnAsSortedBy('self',DataGrid.DataGrid.Order.Descending);}
_buildTree(){return new TimelineModel.TimelineProfileTree.BottomUpRootNode(this._modelEvents(),this._filters,this._startTime,this._endTime,this._groupingFunction(this._groupBySetting.get()));}};Timeline.TimelineStackView=class extends UI.VBox{constructor(treeView){super();var header=this.element.createChild('div','timeline-stack-view-header');header.textContent=Common.UIString('Heaviest stack');this._treeView=treeView;var columns=([{id:'total',title:Common.UIString('Total Time'),fixedWidth:true,width:'110px'},{id:'activity',title:Common.UIString('Activity')}]);this._dataGrid=new DataGrid.ViewportDataGrid(columns);this._dataGrid.setResizeMethod(DataGrid.DataGrid.ResizeMethod.Last);this._dataGrid.addEventListener(DataGrid.DataGrid.Events.SelectedNode,this._onSelectionChanged,this);this._dataGrid.asWidget().show(this.element);}
setStack(stack,selectedNode){var rootNode=this._dataGrid.rootNode();rootNode.removeChildren();var nodeToReveal=null;var totalTime=Math.max.apply(Math,stack.map(node=>node.totalTime));for(var node of stack){var gridNode=new Timeline.TimelineTreeView.GridNode(node,totalTime,totalTime,totalTime,this._treeView);rootNode.appendChild(gridNode);if(node===selectedNode)
nodeToReveal=gridNode;}
nodeToReveal.revealAndSelect();}
selectedTreeNode(){var selectedNode=this._dataGrid.selectedNode;return selectedNode&&(selectedNode)._profileNode;}
_onSelectionChanged(){this.dispatchEventToListeners(Timeline.TimelineStackView.Events.SelectionChanged);}};Timeline.TimelineStackView.Events={SelectionChanged:Symbol('SelectionChanged')};;Timeline.EventsTimelineTreeView=class extends Timeline.TimelineTreeView{constructor(filters,delegate){super();this._filtersControl=new Timeline.EventsTimelineTreeView.Filters();this._filtersControl.addEventListener(Timeline.EventsTimelineTreeView.Filters.Events.FilterChanged,this._onFilterChanged,this);this.init(filters);this._delegate=delegate;this._filters.push.apply(this._filters,this._filtersControl.filters());this._dataGrid.markColumnAsSortedBy('startTime',DataGrid.DataGrid.Order.Ascending);this._splitWidget.showBoth();}
updateContents(selection){super.updateContents(selection);if(selection.type()===Timeline.TimelineSelection.Type.TraceEvent){var event=(selection.object());this._selectEvent(event,true);}}
_buildTree(){this._currentTree=this.buildTopDownTree(true,null);return this._currentTree;}
_onFilterChanged(){var selectedEvent=this.lastSelectedNode()&&this.lastSelectedNode().event;this.refreshTree();if(selectedEvent)
this._selectEvent(selectedEvent,false);}
_findNodeWithEvent(event){var iterators=[this._currentTree.children().values()];while(iterators.length){var iterator=iterators.peekLast().next();if(iterator.done){iterators.pop();continue;}
var child=(iterator.value);if(child.event===event)
return child;iterators.push(child.children().values());}
return null;}
_selectEvent(event,expand){var node=this._findNodeWithEvent(event);if(!node)
return;this.selectProfileNode(node,false);if(expand)
this.dataGridNodeForTreeNode(node).expand();}
populateColumns(columns){columns.push({id:'startTime',title:Common.UIString('Start Time'),width:'80px',fixedWidth:true,sortable:true});super.populateColumns(columns);columns.filter(c=>c.fixedWidth).forEach(c=>c.width='80px');}
populateToolbar(toolbar){super.populateToolbar(toolbar);this._filtersControl.populateToolbar(toolbar);}
_showDetailsForNode(node){var traceEvent=node.event;if(!traceEvent)
return false;Timeline.TimelineUIUtils.buildTraceEventDetails(traceEvent,this.model().timelineModel(),this._linkifier,false).then(fragment=>this._detailsView.element.appendChild(fragment));return true;}
_onHover(node){this._delegate.highlightEvent(node&&node.event);}};Timeline.EventsTimelineTreeView.Filters=class extends Common.Object{constructor(){super();this._categoryFilter=new Timeline.TimelineFilters.Category();this._durationFilter=new Timeline.TimelineFilters.IsLong();this._filters=[this._categoryFilter,this._durationFilter];}
filters(){return this._filters;}
populateToolbar(toolbar){var durationFilterUI=new UI.ToolbarComboBox(durationFilterChanged.bind(this));for(var durationMs of Timeline.EventsTimelineTreeView.Filters._durationFilterPresetsMs){durationFilterUI.addOption(durationFilterUI.createOption(durationMs?Common.UIString('\u2265 %d\xa0ms',durationMs):Common.UIString('All'),durationMs?Common.UIString('Hide records shorter than %d\xa0ms',durationMs):Common.UIString('Show all records'),String(durationMs)));}
toolbar.appendToolbarItem(durationFilterUI);var categoryFiltersUI={};var categories=Timeline.TimelineUIUtils.categories();for(var categoryName in categories){var category=categories[categoryName];if(!category.visible)
continue;var checkbox=new UI.ToolbarCheckbox(category.title,undefined,categoriesFilterChanged.bind(this,categoryName));checkbox.setChecked(true);checkbox.inputElement.style.backgroundColor=category.color;categoryFiltersUI[category.name]=checkbox;toolbar.appendToolbarItem(checkbox);}
function durationFilterChanged(){var duration=durationFilterUI.selectedOption().value;var minimumRecordDuration=parseInt(duration,10);this._durationFilter.setMinimumRecordDuration(minimumRecordDuration);this._notifyFiltersChanged();}
function categoriesFilterChanged(name){var categories=Timeline.TimelineUIUtils.categories();categories[name].hidden=!categoryFiltersUI[name].checked();this._notifyFiltersChanged();}}
_notifyFiltersChanged(){this.dispatchEventToListeners(Timeline.EventsTimelineTreeView.Filters.Events.FilterChanged);}};Timeline.EventsTimelineTreeView.Filters._durationFilterPresetsMs=[0,1,15];Timeline.EventsTimelineTreeView.Filters.Events={FilterChanged:Symbol('FilterChanged')};;Timeline.TimelineUIUtils=class{static _initEventStyles(){if(Timeline.TimelineUIUtils._eventStylesMap)
return Timeline.TimelineUIUtils._eventStylesMap;var recordTypes=TimelineModel.TimelineModel.RecordType;var categories=Timeline.TimelineUIUtils.categories();var eventStyles={};eventStyles[recordTypes.Task]=new Timeline.TimelineRecordStyle(Common.UIString('Task'),categories['other']);eventStyles[recordTypes.Program]=new Timeline.TimelineRecordStyle(Common.UIString('Other'),categories['other']);eventStyles[recordTypes.Animation]=new Timeline.TimelineRecordStyle(Common.UIString('Animation'),categories['rendering']);eventStyles[recordTypes.EventDispatch]=new Timeline.TimelineRecordStyle(Common.UIString('Event'),categories['scripting']);eventStyles[recordTypes.RequestMainThreadFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Request Main Thread Frame'),categories['rendering'],true);eventStyles[recordTypes.BeginFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Frame Start'),categories['rendering'],true);eventStyles[recordTypes.BeginMainThreadFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Frame Start (main thread)'),categories['rendering'],true);eventStyles[recordTypes.DrawFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Draw Frame'),categories['rendering'],true);eventStyles[recordTypes.HitTest]=new Timeline.TimelineRecordStyle(Common.UIString('Hit Test'),categories['rendering']);eventStyles[recordTypes.ScheduleStyleRecalculation]=new Timeline.TimelineRecordStyle(Common.UIString('Schedule Style Recalculation'),categories['rendering'],true);eventStyles[recordTypes.RecalculateStyles]=new Timeline.TimelineRecordStyle(Common.UIString('Recalculate Style'),categories['rendering']);eventStyles[recordTypes.UpdateLayoutTree]=new Timeline.TimelineRecordStyle(Common.UIString('Recalculate Style'),categories['rendering']);eventStyles[recordTypes.InvalidateLayout]=new Timeline.TimelineRecordStyle(Common.UIString('Invalidate Layout'),categories['rendering'],true);eventStyles[recordTypes.Layout]=new Timeline.TimelineRecordStyle(Common.UIString('Layout'),categories['rendering']);eventStyles[recordTypes.PaintSetup]=new Timeline.TimelineRecordStyle(Common.UIString('Paint Setup'),categories['painting']);eventStyles[recordTypes.PaintImage]=new Timeline.TimelineRecordStyle(Common.UIString('Paint Image'),categories['painting'],true);eventStyles[recordTypes.UpdateLayer]=new Timeline.TimelineRecordStyle(Common.UIString('Update Layer'),categories['painting'],true);eventStyles[recordTypes.UpdateLayerTree]=new Timeline.TimelineRecordStyle(Common.UIString('Update Layer Tree'),categories['rendering']);eventStyles[recordTypes.Paint]=new Timeline.TimelineRecordStyle(Common.UIString('Paint'),categories['painting']);eventStyles[recordTypes.RasterTask]=new Timeline.TimelineRecordStyle(Common.UIString('Rasterize Paint'),categories['painting']);eventStyles[recordTypes.ScrollLayer]=new Timeline.TimelineRecordStyle(Common.UIString('Scroll'),categories['rendering']);eventStyles[recordTypes.CompositeLayers]=new Timeline.TimelineRecordStyle(Common.UIString('Composite Layers'),categories['painting']);eventStyles[recordTypes.ParseHTML]=new Timeline.TimelineRecordStyle(Common.UIString('Parse HTML'),categories['loading']);eventStyles[recordTypes.ParseAuthorStyleSheet]=new Timeline.TimelineRecordStyle(Common.UIString('Parse Stylesheet'),categories['loading']);eventStyles[recordTypes.TimerInstall]=new Timeline.TimelineRecordStyle(Common.UIString('Install Timer'),categories['scripting']);eventStyles[recordTypes.TimerRemove]=new Timeline.TimelineRecordStyle(Common.UIString('Remove Timer'),categories['scripting']);eventStyles[recordTypes.TimerFire]=new Timeline.TimelineRecordStyle(Common.UIString('Timer Fired'),categories['scripting']);eventStyles[recordTypes.XHRReadyStateChange]=new Timeline.TimelineRecordStyle(Common.UIString('XHR Ready State Change'),categories['scripting']);eventStyles[recordTypes.XHRLoad]=new Timeline.TimelineRecordStyle(Common.UIString('XHR Load'),categories['scripting']);eventStyles[recordTypes.CompileScript]=new Timeline.TimelineRecordStyle(Common.UIString('Compile Script'),categories['scripting']);eventStyles[recordTypes.EvaluateScript]=new Timeline.TimelineRecordStyle(Common.UIString('Evaluate Script'),categories['scripting']);eventStyles[recordTypes.ParseScriptOnBackground]=new Timeline.TimelineRecordStyle(Common.UIString('Parse Script'),categories['scripting']);eventStyles[recordTypes.MarkLoad]=new Timeline.TimelineRecordStyle(Common.UIString('Load event'),categories['scripting'],true);eventStyles[recordTypes.MarkDOMContent]=new Timeline.TimelineRecordStyle(Common.UIString('DOMContentLoaded event'),categories['scripting'],true);eventStyles[recordTypes.MarkFirstPaint]=new Timeline.TimelineRecordStyle(Common.UIString('First paint'),categories['painting'],true);eventStyles[recordTypes.MarkFMP]=new Timeline.TimelineRecordStyle(Common.UIString('FMP'),categories['rendering'],true);eventStyles[recordTypes.MarkFMPCandidate]=new Timeline.TimelineRecordStyle(Common.UIString('FMP candidate'),categories['rendering'],true);eventStyles[recordTypes.TimeStamp]=new Timeline.TimelineRecordStyle(Common.UIString('Timestamp'),categories['scripting']);eventStyles[recordTypes.ConsoleTime]=new Timeline.TimelineRecordStyle(Common.UIString('Console Time'),categories['scripting']);eventStyles[recordTypes.UserTiming]=new Timeline.TimelineRecordStyle(Common.UIString('User Timing'),categories['scripting']);eventStyles[recordTypes.ResourceSendRequest]=new Timeline.TimelineRecordStyle(Common.UIString('Send Request'),categories['loading']);eventStyles[recordTypes.ResourceReceiveResponse]=new Timeline.TimelineRecordStyle(Common.UIString('Receive Response'),categories['loading']);eventStyles[recordTypes.ResourceFinish]=new Timeline.TimelineRecordStyle(Common.UIString('Finish Loading'),categories['loading']);eventStyles[recordTypes.ResourceReceivedData]=new Timeline.TimelineRecordStyle(Common.UIString('Receive Data'),categories['loading']);eventStyles[recordTypes.RunMicrotasks]=new Timeline.TimelineRecordStyle(Common.UIString('Run Microtasks'),categories['scripting']);eventStyles[recordTypes.FunctionCall]=new Timeline.TimelineRecordStyle(Common.UIString('Function Call'),categories['scripting']);eventStyles[recordTypes.GCEvent]=new Timeline.TimelineRecordStyle(Common.UIString('GC Event'),categories['scripting']);eventStyles[recordTypes.MajorGC]=new Timeline.TimelineRecordStyle(Common.UIString('Major GC'),categories['scripting']);eventStyles[recordTypes.MinorGC]=new Timeline.TimelineRecordStyle(Common.UIString('Minor GC'),categories['scripting']);eventStyles[recordTypes.JSFrame]=new Timeline.TimelineRecordStyle(Common.UIString('JS Frame'),categories['scripting']);eventStyles[recordTypes.RequestAnimationFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Request Animation Frame'),categories['scripting']);eventStyles[recordTypes.CancelAnimationFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Cancel Animation Frame'),categories['scripting']);eventStyles[recordTypes.FireAnimationFrame]=new Timeline.TimelineRecordStyle(Common.UIString('Animation Frame Fired'),categories['scripting']);eventStyles[recordTypes.RequestIdleCallback]=new Timeline.TimelineRecordStyle(Common.UIString('Request Idle Callback'),categories['scripting']);eventStyles[recordTypes.CancelIdleCallback]=new Timeline.TimelineRecordStyle(Common.UIString('Cancel Idle Callback'),categories['scripting']);eventStyles[recordTypes.FireIdleCallback]=new Timeline.TimelineRecordStyle(Common.UIString('Fire Idle Callback'),categories['scripting']);eventStyles[recordTypes.WebSocketCreate]=new Timeline.TimelineRecordStyle(Common.UIString('Create WebSocket'),categories['scripting']);eventStyles[recordTypes.WebSocketSendHandshakeRequest]=new Timeline.TimelineRecordStyle(Common.UIString('Send WebSocket Handshake'),categories['scripting']);eventStyles[recordTypes.WebSocketReceiveHandshakeResponse]=new Timeline.TimelineRecordStyle(Common.UIString('Receive WebSocket Handshake'),categories['scripting']);eventStyles[recordTypes.WebSocketDestroy]=new Timeline.TimelineRecordStyle(Common.UIString('Destroy WebSocket'),categories['scripting']);eventStyles[recordTypes.EmbedderCallback]=new Timeline.TimelineRecordStyle(Common.UIString('Embedder Callback'),categories['scripting']);eventStyles[recordTypes.DecodeImage]=new Timeline.TimelineRecordStyle(Common.UIString('Image Decode'),categories['painting']);eventStyles[recordTypes.ResizeImage]=new Timeline.TimelineRecordStyle(Common.UIString('Image Resize'),categories['painting']);eventStyles[recordTypes.GPUTask]=new Timeline.TimelineRecordStyle(Common.UIString('GPU'),categories['gpu']);eventStyles[recordTypes.LatencyInfo]=new Timeline.TimelineRecordStyle(Common.UIString('Input Latency'),categories['scripting']);eventStyles[recordTypes.GCIdleLazySweep]=new Timeline.TimelineRecordStyle(Common.UIString('DOM GC'),categories['scripting']);eventStyles[recordTypes.GCCompleteSweep]=new Timeline.TimelineRecordStyle(Common.UIString('DOM GC'),categories['scripting']);eventStyles[recordTypes.GCCollectGarbage]=new Timeline.TimelineRecordStyle(Common.UIString('DOM GC'),categories['scripting']);eventStyles[recordTypes.AsyncTask]=new Timeline.TimelineRecordStyle(Common.UIString('Async Task'),categories['async']);Timeline.TimelineUIUtils._eventStylesMap=eventStyles;return eventStyles;}
static inputEventDisplayName(inputEventType){if(!Timeline.TimelineUIUtils._inputEventToDisplayName){var inputEvent=TimelineModel.TimelineIRModel.InputEvents;Timeline.TimelineUIUtils._inputEventToDisplayName=new Map([[inputEvent.Char,Common.UIString('Key Character')],[inputEvent.KeyDown,Common.UIString('Key Down')],[inputEvent.KeyDownRaw,Common.UIString('Key Down')],[inputEvent.KeyUp,Common.UIString('Key Up')],[inputEvent.Click,Common.UIString('Click')],[inputEvent.ContextMenu,Common.UIString('Context Menu')],[inputEvent.MouseDown,Common.UIString('Mouse Down')],[inputEvent.MouseMove,Common.UIString('Mouse Move')],[inputEvent.MouseUp,Common.UIString('Mouse Up')],[inputEvent.MouseWheel,Common.UIString('Mouse Wheel')],[inputEvent.ScrollBegin,Common.UIString('Scroll Begin')],[inputEvent.ScrollEnd,Common.UIString('Scroll End')],[inputEvent.ScrollUpdate,Common.UIString('Scroll Update')],[inputEvent.FlingStart,Common.UIString('Fling Start')],[inputEvent.FlingCancel,Common.UIString('Fling Halt')],[inputEvent.Tap,Common.UIString('Tap')],[inputEvent.TapCancel,Common.UIString('Tap Halt')],[inputEvent.ShowPress,Common.UIString('Tap Begin')],[inputEvent.TapDown,Common.UIString('Tap Down')],[inputEvent.TouchCancel,Common.UIString('Touch Cancel')],[inputEvent.TouchEnd,Common.UIString('Touch End')],[inputEvent.TouchMove,Common.UIString('Touch Move')],[inputEvent.TouchStart,Common.UIString('Touch Start')],[inputEvent.PinchBegin,Common.UIString('Pinch Begin')],[inputEvent.PinchEnd,Common.UIString('Pinch End')],[inputEvent.PinchUpdate,Common.UIString('Pinch Update')]]);}
return Timeline.TimelineUIUtils._inputEventToDisplayName.get(inputEventType)||null;}
static frameDisplayName(frame){if(!TimelineModel.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame))
return UI.beautifyFunctionName(frame.functionName);const nativeGroup=TimelineModel.TimelineJSProfileProcessor.nativeGroup(frame.functionName);const groups=TimelineModel.TimelineJSProfileProcessor.NativeGroups;switch(nativeGroup){case groups.Compile:return Common.UIString('Compile');case groups.Parse:return Common.UIString('Parse');}
return frame.functionName;}
static testContentMatching(traceEvent,regExp){var title=Timeline.TimelineUIUtils.eventStyle(traceEvent).title;var tokens=[title];var url=TimelineModel.TimelineData.forEvent(traceEvent).url;if(url)
tokens.push(url);appendObjectProperties(traceEvent.args,2);return regExp.test(tokens.join('|'));function appendObjectProperties(object,depth){if(!depth)
return;for(var key in object){var value=object[key];var type=typeof value;if(type==='string')
tokens.push(value);else if(type==='number')
tokens.push(String(value));else if(type==='object')
appendObjectProperties(value,depth-1);}}}
static eventStyle(event){var eventStyles=Timeline.TimelineUIUtils._initEventStyles();if(event.hasCategory(TimelineModel.TimelineModel.Category.Console)||event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming))
return{title:event.name,category:Timeline.TimelineUIUtils.categories()['scripting']};if(event.hasCategory(TimelineModel.TimelineModel.Category.LatencyInfo)){var prefix='InputLatency::';var inputEventType=event.name.startsWith(prefix)?event.name.substr(prefix.length):event.name;var displayName=Timeline.TimelineUIUtils.inputEventDisplayName((inputEventType));return{title:displayName||inputEventType,category:Timeline.TimelineUIUtils.categories()['scripting']};}
var result=eventStyles[event.name];if(!result){result=new Timeline.TimelineRecordStyle(event.name,Timeline.TimelineUIUtils.categories()['other'],true);eventStyles[event.name]=result;}
return result;}
static eventColor(event){if(event.name===TimelineModel.TimelineModel.RecordType.JSFrame){var frame=event.args['data'];if(Timeline.TimelineUIUtils.isUserFrame(frame))
return Timeline.TimelineUIUtils.colorForURL(frame.url);}
return Timeline.TimelineUIUtils.eventStyle(event).category.color;}
static eventTitle(event){const recordType=TimelineModel.TimelineModel.RecordType;const eventData=event.args['data'];if(event.name===recordType.JSFrame)
return Timeline.TimelineUIUtils.frameDisplayName(eventData);const title=Timeline.TimelineUIUtils.eventStyle(event).title;if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
return title;if(event.name===recordType.TimeStamp)
return Common.UIString('%s: %s',title,eventData['message']);if(event.name===recordType.Animation&&eventData&&eventData['name'])
return Common.UIString('%s: %s',title,eventData['name']);return title;}
static _interactionPhaseStyles(){var map=Timeline.TimelineUIUtils._interactionPhaseStylesMap;if(!map){map=new Map([[TimelineModel.TimelineIRModel.Phases.Idle,{color:'white',label:'Idle'}],[TimelineModel.TimelineIRModel.Phases.Response,{color:'hsl(43, 83%, 64%)',label:Common.UIString('Response')}],[TimelineModel.TimelineIRModel.Phases.Scroll,{color:'hsl(256, 67%, 70%)',label:Common.UIString('Scroll')}],[TimelineModel.TimelineIRModel.Phases.Fling,{color:'hsl(256, 67%, 70%)',label:Common.UIString('Fling')}],[TimelineModel.TimelineIRModel.Phases.Drag,{color:'hsl(256, 67%, 70%)',label:Common.UIString('Drag')}],[TimelineModel.TimelineIRModel.Phases.Animation,{color:'hsl(256, 67%, 70%)',label:Common.UIString('Animation')}],[TimelineModel.TimelineIRModel.Phases.Uncategorized,{color:'hsl(0, 0%, 87%)',label:Common.UIString('Uncategorized')}]]);Timeline.TimelineUIUtils._interactionPhaseStylesMap=map;}
return map;}
static interactionPhaseColor(phase){return Timeline.TimelineUIUtils._interactionPhaseStyles().get(phase).color;}
static interactionPhaseLabel(phase){return Timeline.TimelineUIUtils._interactionPhaseStyles().get(phase).label;}
static isUserFrame(frame){return frame.scriptId!=='0'&&!(frame.url&&frame.url.startsWith('native '));}
static networkRequestCategory(request){var categories=Timeline.TimelineUIUtils.NetworkCategory;switch(request.mimeType){case'text/html':return categories.HTML;case'application/javascript':case'application/x-javascript':case'text/javascript':return categories.Script;case'text/css':return categories.Style;case'audio/ogg':case'image/gif':case'image/jpeg':case'image/png':case'image/svg+xml':case'image/webp':case'image/x-icon':case'font/opentype':case'font/woff2':case'application/font-woff':return categories.Media;default:return categories.Other;}}
static networkCategoryColor(category){var categories=Timeline.TimelineUIUtils.NetworkCategory;switch(category){case categories.HTML:return'hsl(214, 67%, 66%)';case categories.Script:return'hsl(43, 83%, 64%)';case categories.Style:return'hsl(256, 67%, 70%)';case categories.Media:return'hsl(109, 33%, 55%)';default:return'hsl(0, 0%, 70%)';}}
static buildDetailsTextForTraceEvent(event,target){var recordType=TimelineModel.TimelineModel.RecordType;var detailsText;var eventData=event.args['data'];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:var delta=event.args['usedHeapSizeBefore']-event.args['usedHeapSizeAfter'];detailsText=Common.UIString('%s collected',Number.bytesToString(delta));break;case recordType.FunctionCall:if(eventData)
detailsText=linkifyLocationAsText(eventData['scriptId'],eventData['lineNumber'],0);break;case recordType.JSFrame:detailsText=Timeline.TimelineUIUtils.frameDisplayName(eventData);break;case recordType.EventDispatch:detailsText=eventData?eventData['type']:null;break;case recordType.Paint:var width=Timeline.TimelineUIUtils.quadWidth(eventData.clip);var height=Timeline.TimelineUIUtils.quadHeight(eventData.clip);if(width&&height)
detailsText=Common.UIString('%d\xa0\u00d7\xa0%d',width,height);break;case recordType.ParseHTML:var endLine=event.args['endData']&&event.args['endData']['endLine'];var url=Bindings.displayNameForURL(event.args['beginData']['url']);detailsText=Common.UIString('%s [%s\u2026%s]',url,event.args['beginData']['startLine']+1,endLine>=0?endLine+1:'');break;case recordType.CompileScript:case recordType.EvaluateScript:var url=eventData&&eventData['url'];if(url)
detailsText=Bindings.displayNameForURL(url)+':'+(eventData['lineNumber']+1);break;case recordType.ParseScriptOnBackground:case recordType.XHRReadyStateChange:case recordType.XHRLoad:var url=eventData['url'];if(url)
detailsText=Bindings.displayNameForURL(url);break;case recordType.TimeStamp:detailsText=eventData['message'];break;case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:var url=TimelineModel.TimelineData.forEvent(event).url;if(url)
detailsText=Bindings.displayNameForURL(url);break;case recordType.EmbedderCallback:detailsText=eventData['callbackName'];break;case recordType.Animation:detailsText=eventData&&eventData['name'];break;case recordType.GCIdleLazySweep:detailsText=Common.UIString('idle sweep');break;case recordType.GCCompleteSweep:detailsText=Common.UIString('complete sweep');break;case recordType.GCCollectGarbage:detailsText=Common.UIString('collect');break;case recordType.AsyncTask:detailsText=eventData?eventData['name']:null;break;default:if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
detailsText=null;else
detailsText=linkifyTopCallFrameAsText();break;}
return detailsText;function linkifyLocationAsText(scriptId,lineNumber,columnNumber){var debuggerModel=target?target.model(SDK.DebuggerModel):null;if(!target||target.isDisposed()||!scriptId||!debuggerModel)
return null;var rawLocation=debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber);if(!rawLocation)
return null;var uiLocation=Bindings.debuggerWorkspaceBinding.rawLocationToUILocation(rawLocation);return uiLocation.linkText();}
function linkifyTopCallFrameAsText(){var frame=TimelineModel.TimelineData.forEvent(event).topFrame();if(!frame)
return null;var text=linkifyLocationAsText(frame.scriptId,frame.lineNumber,frame.columnNumber);if(!text){text=frame.url;if(typeof frame.lineNumber==='number')
text+=':'+(frame.lineNumber+1);}
return text;}}
static buildDetailsNodeForTraceEvent(event,target,linkifier){var recordType=TimelineModel.TimelineModel.RecordType;var details=null;var detailsText;var eventData=event.args['data'];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:case recordType.EventDispatch:case recordType.Paint:case recordType.Animation:case recordType.EmbedderCallback:case recordType.ParseHTML:case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:case recordType.GCIdleLazySweep:case recordType.GCCompleteSweep:case recordType.GCCollectGarbage:detailsText=Timeline.TimelineUIUtils.buildDetailsTextForTraceEvent(event,target);break;case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:case recordType.XHRReadyStateChange:case recordType.XHRLoad:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:var url=TimelineModel.TimelineData.forEvent(event).url;if(url)
details=Components.Linkifier.linkifyURL(url);break;case recordType.FunctionCall:case recordType.JSFrame:details=createElement('span');details.createTextChild(Timeline.TimelineUIUtils.frameDisplayName(eventData));const location=linkifyLocation(eventData['scriptId'],eventData['url'],eventData['lineNumber'],eventData['columnNumber']);if(location){details.createTextChild(' @ ');details.appendChild(location);}
break;case recordType.CompileScript:case recordType.EvaluateScript:var url=eventData['url'];if(url)
details=linkifyLocation('',url,eventData['lineNumber'],0);break;case recordType.ParseScriptOnBackground:var url=eventData['url'];if(url)
details=linkifyLocation('',url,0,0);break;default:if(event.hasCategory(TimelineModel.TimelineModel.Category.Console))
detailsText=null;else
details=linkifyTopCallFrame();break;}
if(!details&&detailsText)
details=createTextNode(detailsText);return details;function linkifyLocation(scriptId,url,lineNumber,columnNumber){return linkifier.linkifyScriptLocation(target,scriptId,url,lineNumber,columnNumber,'timeline-details');}
function linkifyTopCallFrame(){var frame=TimelineModel.TimelineData.forEvent(event).topFrame();return frame?linkifier.maybeLinkifyConsoleCallFrame(target,frame,'timeline-details'):null;}}
static async buildTraceEventDetails(event,model,linkifier,detailed){var maybeTarget=model.targetByEvent(event);if(!maybeTarget){return Timeline.TimelineUIUtils._buildTraceEventDetailsSynchronously(event,model,linkifier,detailed,null);}
var target=(maybeTarget);if(typeof event[Timeline.TimelineUIUtils._previewElementSymbol]==='undefined'){var previewElement=null;var url=TimelineModel.TimelineData.forEvent(event).url;if(url)
previewElement=await Components.DOMPresentationUtils.buildImagePreviewContents(target,url,false);else if(TimelineModel.TimelineData.forEvent(event).picture)
previewElement=await Timeline.TimelineUIUtils.buildPicturePreviewContent(event,target);event[Timeline.TimelineUIUtils._previewElementSymbol]=previewElement;}
var nodeIdsToResolve=new Set();var timelineData=TimelineModel.TimelineData.forEvent(event);if(timelineData.backendNodeId)
nodeIdsToResolve.add(timelineData.backendNodeId);var invalidationTrackingEvents=TimelineModel.InvalidationTracker.invalidationEventsFor(event);if(invalidationTrackingEvents)
Timeline.TimelineUIUtils._collectInvalidationNodeIds(nodeIdsToResolve,invalidationTrackingEvents);var relatedNodes=null;if(nodeIdsToResolve.size){var domModel=target.model(SDK.DOMModel);if(domModel){relatedNodes=await new Promise(fulfill=>domModel.pushNodesByBackendIdsToFrontend(nodeIdsToResolve,fulfill));}}
return Timeline.TimelineUIUtils._buildTraceEventDetailsSynchronously(event,model,linkifier,detailed,relatedNodes);}
static _buildTraceEventDetailsSynchronously(event,model,linkifier,detailed,relatedNodesMap){var recordTypes=TimelineModel.TimelineModel.RecordType;var relatedNodeLabel;var contentHelper=new Timeline.TimelineDetailsContentHelper(model.targetByEvent(event),linkifier);contentHelper.addSection(Timeline.TimelineUIUtils.eventTitle(event),Timeline.TimelineUIUtils.eventStyle(event).category.color);var eventData=event.args['data'];var timelineData=TimelineModel.TimelineData.forEvent(event);var initiator=timelineData.initiator();if(timelineData.warning)
contentHelper.appendWarningRow(event);if(event.name===recordTypes.JSFrame&&eventData['deoptReason'])
contentHelper.appendWarningRow(event,TimelineModel.TimelineModel.WarningType.V8Deopt);if(detailed){contentHelper.appendTextRow(Common.UIString('Self Time'),Number.millisToString(event.selfTime,true));contentHelper.appendTextRow(Common.UIString('Total Time'),Number.millisToString(event.duration||0,true));}
switch(event.name){case recordTypes.GCEvent:case recordTypes.MajorGC:case recordTypes.MinorGC:var delta=event.args['usedHeapSizeBefore']-event.args['usedHeapSizeAfter'];contentHelper.appendTextRow(Common.UIString('Collected'),Number.bytesToString(delta));break;case recordTypes.JSFrame:case recordTypes.FunctionCall:var detailsNode=Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode)
contentHelper.appendElementRow(Common.UIString('Function'),detailsNode);break;case recordTypes.TimerFire:case recordTypes.TimerInstall:case recordTypes.TimerRemove:contentHelper.appendTextRow(Common.UIString('Timer ID'),eventData['timerId']);if(event.name===recordTypes.TimerInstall){contentHelper.appendTextRow(Common.UIString('Timeout'),Number.millisToString(eventData['timeout']));contentHelper.appendTextRow(Common.UIString('Repeats'),!eventData['singleShot']);}
break;case recordTypes.FireAnimationFrame:contentHelper.appendTextRow(Common.UIString('Callback ID'),eventData['id']);break;case recordTypes.ResourceSendRequest:case recordTypes.ResourceReceiveResponse:case recordTypes.ResourceReceivedData:case recordTypes.ResourceFinish:var url=timelineData.url;if(url)
contentHelper.appendElementRow(Common.UIString('Resource'),Components.Linkifier.linkifyURL(url));if(eventData['requestMethod'])
contentHelper.appendTextRow(Common.UIString('Request Method'),eventData['requestMethod']);if(typeof eventData['statusCode']==='number')
contentHelper.appendTextRow(Common.UIString('Status Code'),eventData['statusCode']);if(eventData['mimeType'])
contentHelper.appendTextRow(Common.UIString('MIME Type'),eventData['mimeType']);if('priority'in eventData){var priority=NetworkConditions.uiLabelForPriority(eventData['priority']);contentHelper.appendTextRow(Common.UIString('Priority'),priority);}
if(eventData['encodedDataLength']){contentHelper.appendTextRow(Common.UIString('Encoded Data'),Common.UIString('%d Bytes',eventData['encodedDataLength']));}
if(eventData['decodedBodyLength']){contentHelper.appendTextRow(Common.UIString('Decoded Body'),Common.UIString('%d Bytes',eventData['decodedBodyLength']));}
break;case recordTypes.CompileScript:case recordTypes.EvaluateScript:var url=eventData&&eventData['url'];if(url){contentHelper.appendLocationRow(Common.UIString('Script'),url,eventData['lineNumber'],eventData['columnNumber']);}
break;case recordTypes.Paint:var clip=eventData['clip'];contentHelper.appendTextRow(Common.UIString('Location'),Common.UIString('(%d, %d)',clip[0],clip[1]));var clipWidth=Timeline.TimelineUIUtils.quadWidth(clip);var clipHeight=Timeline.TimelineUIUtils.quadHeight(clip);contentHelper.appendTextRow(Common.UIString('Dimensions'),Common.UIString('%d × %d',clipWidth,clipHeight));case recordTypes.PaintSetup:case recordTypes.Rasterize:case recordTypes.ScrollLayer:relatedNodeLabel=Common.UIString('Layer Root');break;case recordTypes.PaintImage:case recordTypes.DecodeLazyPixelRef:case recordTypes.DecodeImage:case recordTypes.ResizeImage:case recordTypes.DrawLazyPixelRef:relatedNodeLabel=Common.UIString('Owner Element');if(timelineData.url){contentHelper.appendElementRow(Common.UIString('Image URL'),Components.Linkifier.linkifyURL(timelineData.url));}
break;case recordTypes.ParseAuthorStyleSheet:var url=eventData['styleSheetUrl'];if(url)
contentHelper.appendElementRow(Common.UIString('Stylesheet URL'),Components.Linkifier.linkifyURL(url));break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:contentHelper.appendTextRow(Common.UIString('Elements Affected'),event.args['elementCount']);break;case recordTypes.Layout:var beginData=event.args['beginData'];contentHelper.appendTextRow(Common.UIString('Nodes That Need Layout'),Common.UIString('%s of %s',beginData['dirtyObjects'],beginData['totalObjects']));relatedNodeLabel=Common.UIString('Layout root');break;case recordTypes.ConsoleTime:contentHelper.appendTextRow(Common.UIString('Message'),event.name);break;case recordTypes.WebSocketCreate:case recordTypes.WebSocketSendHandshakeRequest:case recordTypes.WebSocketReceiveHandshakeResponse:case recordTypes.WebSocketDestroy:var initiatorData=initiator?initiator.args['data']:eventData;if(typeof initiatorData['webSocketURL']!=='undefined')
contentHelper.appendTextRow(Common.UIString('URL'),initiatorData['webSocketURL']);if(typeof initiatorData['webSocketProtocol']!=='undefined')
contentHelper.appendTextRow(Common.UIString('WebSocket Protocol'),initiatorData['webSocketProtocol']);if(typeof eventData['message']!=='undefined')
contentHelper.appendTextRow(Common.UIString('Message'),eventData['message']);break;case recordTypes.EmbedderCallback:contentHelper.appendTextRow(Common.UIString('Callback Function'),eventData['callbackName']);break;case recordTypes.Animation:if(event.phase===SDK.TracingModel.Phase.NestableAsyncInstant)
contentHelper.appendTextRow(Common.UIString('State'),eventData['state']);break;case recordTypes.ParseHTML:var beginData=event.args['beginData'];var url=beginData['url'];var startLine=beginData['startLine']-1;var endLine=event.args['endData']?event.args['endData']['endLine']-1:undefined;if(url)
contentHelper.appendLocationRange(Common.UIString('Range'),url,startLine,endLine);break;case recordTypes.FireIdleCallback:contentHelper.appendTextRow(Common.UIString('Allotted Time'),Number.millisToString(eventData['allottedMilliseconds']));contentHelper.appendTextRow(Common.UIString('Invoked by Timeout'),eventData['timedOut']);case recordTypes.RequestIdleCallback:case recordTypes.CancelIdleCallback:contentHelper.appendTextRow(Common.UIString('Callback ID'),eventData['id']);break;case recordTypes.EventDispatch:contentHelper.appendTextRow(Common.UIString('Type'),eventData['type']);break;default:var detailsNode=Timeline.TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode)
contentHelper.appendElementRow(Common.UIString('Details'),detailsNode);break;}
if(timelineData.timeWaitingForMainThread){contentHelper.appendTextRow(Common.UIString('Time Waiting for Main Thread'),Number.millisToString(timelineData.timeWaitingForMainThread,true));}
var relatedNode=relatedNodesMap&&relatedNodesMap.get(timelineData.backendNodeId);if(relatedNode){contentHelper.appendElementRow(relatedNodeLabel||Common.UIString('Related Node'),Components.DOMPresentationUtils.linkifyNodeReference(relatedNode));}
if(event[Timeline.TimelineUIUtils._previewElementSymbol]){contentHelper.addSection(Common.UIString('Preview'));contentHelper.appendElementRow('',event[Timeline.TimelineUIUtils._previewElementSymbol]);}
if(initiator||timelineData.stackTraceForSelfOrInitiator()||TimelineModel.InvalidationTracker.invalidationEventsFor(event))
Timeline.TimelineUIUtils._generateCauses(event,model.targetByEvent(event),relatedNodesMap,contentHelper);var stats={};var showPieChart=detailed&&Timeline.TimelineUIUtils._aggregatedStatsForTraceEvent(stats,model,event);if(showPieChart){contentHelper.addSection(Common.UIString('Aggregated Time'));var pieChart=Timeline.TimelineUIUtils.generatePieChart(stats,Timeline.TimelineUIUtils.eventStyle(event).category,event.selfTime);contentHelper.appendElementRow('',pieChart);}
return contentHelper.fragment;}
static buildRangeStats(model,startTime,endTime){var aggregatedStats=Timeline.TimelineUIUtils.statsForTimeRange(model,startTime,endTime);var startOffset=startTime-model.minimumRecordTime();var endOffset=endTime-model.minimumRecordTime();var contentHelper=new Timeline.TimelineDetailsContentHelper(null,null);contentHelper.addSection(Common.UIString('Range:  %s \u2013 %s',Number.millisToString(startOffset),Number.millisToString(endOffset)));var pieChart=Timeline.TimelineUIUtils.generatePieChart(aggregatedStats);contentHelper.appendElementRow('',pieChart);return contentHelper.fragment;}
static statsForTimeRange(model,startTime,endTime){Timeline.TimelineUIUtils._buildRangeStatsCacheIfNeeded(model);var tasks=model.mainThreadTasks();if(!tasks.length)
return{};var statsBeforeIndex=Math.min(tasks.lowerBound(startTime,(time,task)=>time-task.endTime),tasks.length-1);var statsAfterIndex=Math.min(tasks.lowerBound(endTime,(time,task)=>time-task.endTime),tasks.length-1);var events=model.mainThreadEvents();var statsAfter=subtractStats(tasks[statsAfterIndex][Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol],Timeline.TimelineUIUtils._slowStatsForTimeRange(events,endTime,tasks[statsAfterIndex].endTime));var statsBefore=subtractStats(tasks[statsBeforeIndex][Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol],Timeline.TimelineUIUtils._slowStatsForTimeRange(events,startTime,tasks[statsBeforeIndex].endTime));var aggregatedStats=subtractStats(statsAfter,statsBefore);function subtractStats(a,b){var result=Object.assign({},a);for(var key in b)
result[key]-=b[key];return result;}
var aggregatedTotal=Object.values(aggregatedStats).reduce((a,b)=>a+b,0);aggregatedStats['idle']=Math.max(0,endTime-startTime-aggregatedTotal);return aggregatedStats;}
static _slowStatsForTimeRange(events,startTime,endTime){var stats={};var ownTimes=[];TimelineModel.TimelineModel.forEachEvent(events,onStartEvent,onEndEvent,undefined,startTime,endTime,Timeline.TimelineUIUtils._filterForStats());function onStartEvent(e){var duration=Math.min(e.endTime,endTime)-Math.max(e.startTime,startTime);if(ownTimes.length)
ownTimes[ownTimes.length-1]-=duration;ownTimes.push(duration);}
function onEndEvent(e){var category=Timeline.TimelineUIUtils.eventStyle(e).category.name;stats[category]=(stats[category]||0)+ownTimes.pop();}
return stats;}
static _filterForStats(){var visibleEventsFilter=Timeline.TimelineUIUtils.visibleEventsFilter();return event=>visibleEventsFilter.accept(event)||SDK.TracingModel.isTopLevelEvent(event);}
static _buildRangeStatsCacheIfNeeded(model){var tasks=model.mainThreadTasks();var filter=Timeline.TimelineUIUtils._filterForStats();var firstTask=tasks.find(filter);if(!firstTask||firstTask[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol])
return;var aggregatedStats={};var ownTimes=[];TimelineModel.TimelineModel.forEachEvent(model.mainThreadEvents(),onStartEvent,onEndEvent,undefined,undefined,undefined,filter);function onStartEvent(e){if(ownTimes.length)
ownTimes[ownTimes.length-1]-=e.duration;ownTimes.push(e.duration);}
function onEndEvent(e){var category=Timeline.TimelineUIUtils.eventStyle(e).category.name;aggregatedStats[category]=(aggregatedStats[category]||0)+ownTimes.pop();if(!ownTimes.length)
e[Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol]=Object.assign({},aggregatedStats);}}
static buildNetworkRequestDetails(request,model,linkifier){const target=model.targetByEvent(request.children[0]);const contentHelper=new Timeline.TimelineDetailsContentHelper(target,linkifier);const category=Timeline.TimelineUIUtils.networkRequestCategory(request);const color=Timeline.TimelineUIUtils.networkCategoryColor(category);contentHelper.addSection(Common.UIString('Network request'),color);const duration=request.endTime-(request.startTime||-Infinity);if(request.url)
contentHelper.appendElementRow(Common.UIString('URL'),Components.Linkifier.linkifyURL(request.url));if(isFinite(duration))
contentHelper.appendTextRow(Common.UIString('Duration'),Number.millisToString(duration,true));if(request.requestMethod)
contentHelper.appendTextRow(Common.UIString('Request Method'),request.requestMethod);if(typeof request.priority==='string'){const priority=NetworkConditions.uiLabelForPriority((request.priority));contentHelper.appendTextRow(Common.UIString('Priority'),priority);}
if(request.mimeType)
contentHelper.appendTextRow(Common.UIString('Mime Type'),request.mimeType);var lengthText='';if(request.fromCache)
lengthText+=Common.UIString(' (from cache)');if(request.fromServiceWorker)
lengthText+=Common.UIString(' (from service worker)');if(request.encodedDataLength||!lengthText)
lengthText=`${Number.bytesToString(request.encodedDataLength)}${lengthText}`;contentHelper.appendTextRow(Common.UIString('Encoded Data'),lengthText);if(request.decodedBodyLength)
contentHelper.appendTextRow(Common.UIString('Decoded Body'),Number.bytesToString(request.decodedBodyLength));const title=Common.UIString('Initiator');const sendRequest=request.children[0];const topFrame=TimelineModel.TimelineData.forEvent(sendRequest).topFrame();if(topFrame){const link=linkifier.maybeLinkifyConsoleCallFrame(target,topFrame);if(link)
contentHelper.appendElementRow(title,link);}else{const initiator=TimelineModel.TimelineData.forEvent(sendRequest).initiator();if(initiator){const initiatorURL=TimelineModel.TimelineData.forEvent(initiator).url;if(initiatorURL){const link=linkifier.maybeLinkifyScriptLocation(target,null,initiatorURL,0);if(link)
contentHelper.appendElementRow(title,link);}}}
function action(fulfill){Components.DOMPresentationUtils.buildImagePreviewContents((target),request.url,false).then(saveImage);function saveImage(element){request.previewElement=element;fulfill(request.previewElement);}}
var previewPromise;if(request.previewElement)
previewPromise=Promise.resolve(request.previewElement);else
previewPromise=request.url&&target?new Promise(action):Promise.resolve(null);function appendPreview(element){if(element)
contentHelper.appendElementRow(Common.UIString('Preview'),request.previewElement);return contentHelper.fragment;}
return previewPromise.then(appendPreview);}
static _stackTraceFromCallFrames(callFrames){return({callFrames:callFrames});}
static _generateCauses(event,target,relatedNodesMap,contentHelper){var recordTypes=TimelineModel.TimelineModel.RecordType;var callSiteStackLabel;var stackLabel;switch(event.name){case recordTypes.TimerFire:callSiteStackLabel=Common.UIString('Timer Installed');break;case recordTypes.FireAnimationFrame:callSiteStackLabel=Common.UIString('Animation Frame Requested');break;case recordTypes.FireIdleCallback:callSiteStackLabel=Common.UIString('Idle Callback Requested');break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:stackLabel=Common.UIString('Recalculation Forced');break;case recordTypes.Layout:callSiteStackLabel=Common.UIString('First Layout Invalidation');stackLabel=Common.UIString('Layout Forced');break;}
var timelineData=TimelineModel.TimelineData.forEvent(event);if(timelineData.stackTrace&&timelineData.stackTrace.length){contentHelper.addSection(Common.UIString('Call Stacks'));contentHelper.appendStackTrace(stackLabel||Common.UIString('Stack Trace'),Timeline.TimelineUIUtils._stackTraceFromCallFrames(timelineData.stackTrace));}
var initiator=TimelineModel.TimelineData.forEvent(event).initiator();if(TimelineModel.InvalidationTracker.invalidationEventsFor(event)&&target){contentHelper.addSection(Common.UIString('Invalidations'));Timeline.TimelineUIUtils._generateInvalidations(event,target,relatedNodesMap,contentHelper);}else if(initiator){var delay=event.startTime-initiator.startTime;contentHelper.appendTextRow(Common.UIString('Pending for'),Number.preciseMillisToString(delay,1));var link=createElementWithClass('span','devtools-link');link.textContent=Common.UIString('reveal');link.addEventListener('click',()=>{Timeline.TimelinePanel.instance().select(Timeline.TimelineSelection.fromTraceEvent((initiator)));});contentHelper.appendElementRow(Common.UIString('Initiator'),link);var initiatorStackTrace=TimelineModel.TimelineData.forEvent(initiator).stackTrace;if(initiatorStackTrace){contentHelper.appendStackTrace(callSiteStackLabel||Common.UIString('First Invalidated'),Timeline.TimelineUIUtils._stackTraceFromCallFrames(initiatorStackTrace));}}}
static _generateInvalidations(event,target,relatedNodesMap,contentHelper){var invalidationTrackingEvents=TimelineModel.InvalidationTracker.invalidationEventsFor(event);var invalidations={};invalidationTrackingEvents.forEach(function(invalidation){if(!invalidations[invalidation.type])
invalidations[invalidation.type]=[invalidation];else
invalidations[invalidation.type].push(invalidation);});Object.keys(invalidations).forEach(function(type){Timeline.TimelineUIUtils._generateInvalidationsForType(type,target,invalidations[type],relatedNodesMap,contentHelper);});}
static _generateInvalidationsForType(type,target,invalidations,relatedNodesMap,contentHelper){var title;switch(type){case TimelineModel.TimelineModel.RecordType.StyleRecalcInvalidationTracking:title=Common.UIString('Style Invalidations');break;case TimelineModel.TimelineModel.RecordType.LayoutInvalidationTracking:title=Common.UIString('Layout Invalidations');break;default:title=Common.UIString('Other Invalidations');break;}
var invalidationsTreeOutline=new UI.TreeOutlineInShadow();invalidationsTreeOutline.registerRequiredCSS('timeline/invalidationsTree.css');invalidationsTreeOutline.element.classList.add('invalidations-tree');var invalidationGroups=groupInvalidationsByCause(invalidations);invalidationGroups.forEach(function(group){var groupElement=new Timeline.TimelineUIUtils.InvalidationsGroupElement(target,relatedNodesMap,contentHelper,group);invalidationsTreeOutline.appendChild(groupElement);});contentHelper.appendElementRow(title,invalidationsTreeOutline.element,false,true);function groupInvalidationsByCause(invalidations){var causeToInvalidationMap=new Map();for(var index=0;index<invalidations.length;index++){var invalidation=invalidations[index];var causeKey='';if(invalidation.cause.reason)
causeKey+=invalidation.cause.reason+'.';if(invalidation.cause.stackTrace){invalidation.cause.stackTrace.forEach(function(stackFrame){causeKey+=stackFrame['functionName']+'.';causeKey+=stackFrame['scriptId']+'.';causeKey+=stackFrame['url']+'.';causeKey+=stackFrame['lineNumber']+'.';causeKey+=stackFrame['columnNumber']+'.';});}
if(causeToInvalidationMap.has(causeKey))
causeToInvalidationMap.get(causeKey).push(invalidation);else
causeToInvalidationMap.set(causeKey,[invalidation]);}
return causeToInvalidationMap.valuesArray();}}
static _collectInvalidationNodeIds(nodeIds,invalidations){nodeIds.addAll(invalidations.map(invalidation=>invalidation.nodeId).filter(id=>id));}
static _aggregatedStatsForTraceEvent(total,model,event){var events=model.inspectedTargetEvents();function eventComparator(startTime,e){return startTime-e.startTime;}
var index=events.binaryIndexOf(event.startTime,eventComparator);if(index<0)
return false;var hasChildren=false;var endTime=event.endTime;if(endTime){for(var i=index;i<events.length;i++){var nextEvent=events[i];if(nextEvent.startTime>=endTime)
break;if(!nextEvent.selfTime)
continue;if(nextEvent.thread!==event.thread)
continue;if(i>index)
hasChildren=true;var categoryName=Timeline.TimelineUIUtils.eventStyle(nextEvent).category.name;total[categoryName]=(total[categoryName]||0)+nextEvent.selfTime;}}
if(SDK.TracingModel.isAsyncPhase(event.phase)){if(event.endTime){var aggregatedTotal=0;for(var categoryName in total)
aggregatedTotal+=total[categoryName];total['idle']=Math.max(0,event.endTime-event.startTime-aggregatedTotal);}
return false;}
return hasChildren;}
static async buildPicturePreviewContent(event,target){var snapshotWithRect=await new TimelineModel.LayerPaintEvent(event,target).snapshotPromise();if(!snapshotWithRect)
return null;var imageURLPromise=snapshotWithRect.snapshot.replay(null,null,1);snapshotWithRect.snapshot.release();var imageURL=await imageURLPromise;if(!imageURL)
return null;var container=createElement('div');UI.appendStyle(container,'components/imagePreview.css');container.classList.add('image-preview-container','vbox','link');var img=container.createChild('img');img.src=imageURL;var paintProfilerButton=container.createChild('a');paintProfilerButton.textContent=Common.UIString('Paint Profiler');container.addEventListener('click',showPaintProfiler,false);return container;function showPaintProfiler(){Timeline.TimelinePanel.instance().select(Timeline.TimelineSelection.fromTraceEvent(event),Timeline.TimelineDetailsView.Tab.PaintProfiler);}}
static createEventDivider(event,zeroTime){var eventDivider=createElementWithClass('div','resources-event-divider');var startTime=Number.millisToString(event.startTime-zeroTime);eventDivider.title=Common.UIString('%s at %s',Timeline.TimelineUIUtils.eventTitle(event),startTime);var style=Timeline.TimelineUIUtils.markerStyleForEvent(event);if(style.tall)
eventDivider.style.backgroundColor=style.color;return eventDivider;}
static _visibleTypes(){var eventStyles=Timeline.TimelineUIUtils._initEventStyles();var result=[];for(var name in eventStyles){if(!eventStyles[name].hidden)
result.push(name);}
return result;}
static visibleEventsFilter(){return new TimelineModel.TimelineVisibleEventsFilter(Timeline.TimelineUIUtils._visibleTypes());}
static paintEventsFilter(){var recordTypes=TimelineModel.TimelineModel.RecordType;return new TimelineModel.TimelineInvisibleEventsFilter([recordTypes.MarkFMP,recordTypes.MarkFMPCandidate]);}
static categories(){if(Timeline.TimelineUIUtils._categories)
return Timeline.TimelineUIUtils._categories;Timeline.TimelineUIUtils._categories={loading:new Timeline.TimelineCategory('loading',Common.UIString('Loading'),true,'hsl(214, 67%, 74%)','hsl(214, 67%, 66%)'),scripting:new Timeline.TimelineCategory('scripting',Common.UIString('Scripting'),true,'hsl(43, 83%, 72%)','hsl(43, 83%, 64%) '),rendering:new Timeline.TimelineCategory('rendering',Common.UIString('Rendering'),true,'hsl(256, 67%, 76%)','hsl(256, 67%, 70%)'),painting:new Timeline.TimelineCategory('painting',Common.UIString('Painting'),true,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),gpu:new Timeline.TimelineCategory('gpu',Common.UIString('GPU'),false,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),async:new Timeline.TimelineCategory('async',Common.UIString('Async'),false,'hsl(0, 100%, 50%)','hsl(0, 100%, 40%)'),other:new Timeline.TimelineCategory('other',Common.UIString('Other'),false,'hsl(0, 0%, 87%)','hsl(0, 0%, 79%)'),idle:new Timeline.TimelineCategory('idle',Common.UIString('Idle'),false,'hsl(0, 0%, 98%)','hsl(0, 0%, 98%)')};return Timeline.TimelineUIUtils._categories;}
static titleForAsyncEventGroup(group){if(!Timeline.TimelineUIUtils._titleForAsyncEventGroupMap){var groups=TimelineModel.TimelineModel.AsyncEventGroup;Timeline.TimelineUIUtils._titleForAsyncEventGroupMap=new Map([[groups.animation,Common.UIString('Animation')],[groups.console,Common.UIString('Console')],[groups.userTiming,Common.UIString('User Timing')],[groups.input,Common.UIString('Input')]]);}
return Timeline.TimelineUIUtils._titleForAsyncEventGroupMap.get(group)||'';}
static generatePieChart(aggregatedStats,selfCategory,selfTime){var total=0;for(var categoryName in aggregatedStats)
total+=aggregatedStats[categoryName];var element=createElementWithClass('div','timeline-details-view-pie-chart-wrapper hbox');var pieChart=new PerfUI.PieChart(110,value=>Number.preciseMillisToString(value),true);pieChart.element.classList.add('timeline-details-view-pie-chart');pieChart.setTotal(total);var pieChartContainer=element.createChild('div','vbox');pieChartContainer.appendChild(pieChart.element);var footerElement=element.createChild('div','timeline-aggregated-info-legend');function appendLegendRow(name,title,value,color){if(!value)
return;pieChart.addSlice(value,color);var rowElement=footerElement.createChild('div');rowElement.createChild('span','timeline-aggregated-legend-value').textContent=Number.preciseMillisToString(value,1);rowElement.createChild('span','timeline-aggregated-legend-swatch').style.backgroundColor=color;rowElement.createChild('span','timeline-aggregated-legend-title').textContent=title;}
if(selfCategory){if(selfTime){appendLegendRow(selfCategory.name,Common.UIString('%s (self)',selfCategory.title),selfTime,selfCategory.color);}
var categoryTime=aggregatedStats[selfCategory.name];var value=categoryTime-selfTime;if(value>0){appendLegendRow(selfCategory.name,Common.UIString('%s (children)',selfCategory.title),value,selfCategory.childColor);}}
for(var categoryName in Timeline.TimelineUIUtils.categories()){var category=Timeline.TimelineUIUtils.categories()[categoryName];if(category===selfCategory)
continue;appendLegendRow(category.name,category.title,aggregatedStats[category.name],category.childColor);}
return element;}
static generateDetailsContentForFrame(frame,filmStripFrame){var contentHelper=new Timeline.TimelineDetailsContentHelper(null,null);contentHelper.addSection(Common.UIString('Frame'));var duration=Timeline.TimelineUIUtils.frameDuration(frame);contentHelper.appendElementRow(Common.UIString('Duration'),duration,frame.hasWarnings());if(filmStripFrame){var filmStripPreview=createElementWithClass('img','timeline-filmstrip-preview');filmStripFrame.imageDataPromise().then(onGotImageData.bind(null,filmStripPreview));contentHelper.appendElementRow('',filmStripPreview);filmStripPreview.addEventListener('click',frameClicked.bind(null,filmStripFrame),false);}
var durationInMillis=frame.endTime-frame.startTime;contentHelper.appendTextRow(Common.UIString('FPS'),Math.floor(1000/durationInMillis));contentHelper.appendTextRow(Common.UIString('CPU time'),Number.millisToString(frame.cpuTime,true));if(frame.layerTree){contentHelper.appendElementRow(Common.UIString('Layer tree'),Components.Linkifier.linkifyRevealable(frame.layerTree,Common.UIString('show')));}
function onGotImageData(image,data){if(data)
image.src='data:image/jpg;base64,'+data;}
function frameClicked(filmStripFrame){new PerfUI.FilmStripView.Dialog(filmStripFrame,0);}
return contentHelper.fragment;}
static frameDuration(frame){var durationText=Common.UIString('%s (at %s)',Number.millisToString(frame.endTime-frame.startTime,true),Number.millisToString(frame.startTimeOffset,true));var element=createElement('span');element.createTextChild(durationText);if(!frame.hasWarnings())
return element;element.createTextChild(Common.UIString('. Long frame times are an indication of '));element.appendChild(UI.createExternalLink('https://developers.google.com/web/fundamentals/performance/rendering/',Common.UIString('jank')));element.createTextChild('.');return element;}
static createFillStyle(context,width,height,color0,color1,color2){var gradient=context.createLinearGradient(0,0,width,height);gradient.addColorStop(0,color0);gradient.addColorStop(0.25,color1);gradient.addColorStop(0.75,color1);gradient.addColorStop(1,color2);return gradient;}
static quadWidth(quad){return Math.round(Math.sqrt(Math.pow(quad[0]-quad[2],2)+Math.pow(quad[1]-quad[3],2)));}
static quadHeight(quad){return Math.round(Math.sqrt(Math.pow(quad[0]-quad[6],2)+Math.pow(quad[1]-quad[7],2)));}
static eventDispatchDesciptors(){if(Timeline.TimelineUIUtils._eventDispatchDesciptors)
return Timeline.TimelineUIUtils._eventDispatchDesciptors;var lightOrange='hsl(40,100%,80%)';var orange='hsl(40,100%,50%)';var green='hsl(90,100%,40%)';var purple='hsl(256,100%,75%)';Timeline.TimelineUIUtils._eventDispatchDesciptors=[new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(1,lightOrange,['mousemove','mouseenter','mouseleave','mouseout','mouseover']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(1,lightOrange,['pointerover','pointerout','pointerenter','pointerleave','pointermove']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(2,green,['wheel']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,['click','mousedown','mouseup']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,['touchstart','touchend','touchmove','touchcancel']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,orange,['pointerdown','pointerup','pointercancel','gotpointercapture','lostpointercapture']),new Timeline.TimelineUIUtils.EventDispatchTypeDescriptor(3,purple,['keydown','keyup','keypress'])];return Timeline.TimelineUIUtils._eventDispatchDesciptors;}
static markerStyleForEvent(event){const tallMarkerDashStyle=[10,5];const title=Timeline.TimelineUIUtils.eventTitle(event);if(event.hasCategory(TimelineModel.TimelineModel.Category.Console)||event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)){return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:event.hasCategory(TimelineModel.TimelineModel.Category.UserTiming)?'purple':'orange',tall:false,lowPriority:false,};}
var recordTypes=TimelineModel.TimelineModel.RecordType;var tall=false;var color='green';switch(event.name){case recordTypes.MarkDOMContent:color='blue';tall=true;break;case recordTypes.MarkLoad:color='red';tall=true;break;case recordTypes.MarkFirstPaint:color='green';tall=true;break;case recordTypes.MarkFMP:color='orange';tall=true;break;case recordTypes.MarkFMPCandidate:color='orange';tall=true;break;case recordTypes.TimeStamp:color='orange';break;}
return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:color,tall:tall,lowPriority:false,};}
static markerStyleForFrame(){return{title:Common.UIString('Frame'),color:'rgba(100, 100, 100, 0.4)',lineWidth:3,dashStyle:[3],tall:true,lowPriority:true};}
static colorForURL(url){if(!Timeline.TimelineUIUtils.colorForURL._colorGenerator){Timeline.TimelineUIUtils.colorForURL._colorGenerator=new PerfUI.FlameChart.ColorGenerator({min:30,max:330},{min:50,max:80,count:3},85);}
return Timeline.TimelineUIUtils.colorForURL._colorGenerator.colorForID(url);}
static eventWarning(event,warningType){var timelineData=TimelineModel.TimelineData.forEvent(event);var warning=warningType||timelineData.warning;if(!warning)
return null;var warnings=TimelineModel.TimelineModel.WarningType;var span=createElement('span');var eventData=event.args['data'];switch(warning){case warnings.ForcedStyle:case warnings.ForcedLayout:span.appendChild(UI.createDocumentationLink('../../fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts',Common.UIString('Forced reflow')));span.createTextChild(Common.UIString(' is a likely performance bottleneck.'));break;case warnings.IdleDeadlineExceeded:span.textContent=Common.UIString('Idle callback execution extended beyond deadline by '+
Number.millisToString(event.duration-eventData['allottedMilliseconds'],true));break;case warnings.LongHandler:span.textContent=Common.UIString('Handler took %s',Number.millisToString(event.duration,true));break;case warnings.LongRecurringHandler:span.textContent=Common.UIString('Recurring handler took %s',Number.millisToString(event.duration,true));break;case warnings.V8Deopt:span.appendChild(UI.createExternalLink('https://github.com/GoogleChrome/devtools-docs/issues/53',Common.UIString('Not optimized')));span.createTextChild(Common.UIString(': %s',eventData['deoptReason']));break;default:console.assert(false,'Unhandled TimelineModel.WarningType');}
return span;}
static displayNameForFrame(frame,trimAt){var url=frame.url;if(!trimAt)
trimAt=30;return url.startsWith('about:')?`"${frame.name.trimMiddle(trimAt)}"`:frame.url.trimEnd(trimAt);}};Timeline.TimelineRecordStyle=class{constructor(title,category,hidden){this.title=title;this.category=category;this.hidden=!!hidden;}};Timeline.TimelineUIUtils.NetworkCategory={HTML:Symbol('HTML'),Script:Symbol('Script'),Style:Symbol('Style'),Media:Symbol('Media'),Other:Symbol('Other')};Timeline.TimelineUIUtils._aggregatedStatsKey=Symbol('aggregatedStats');Timeline.TimelineUIUtils.InvalidationsGroupElement=class extends UI.TreeElement{constructor(target,relatedNodesMap,contentHelper,invalidations){super('',true);this.listItemElement.classList.add('header');this.selectable=false;this.toggleOnClick=true;this._relatedNodesMap=relatedNodesMap;this._contentHelper=contentHelper;this._invalidations=invalidations;this.title=this._createTitle(target);}
_createTitle(target){var first=this._invalidations[0];var reason=first.cause.reason;var topFrame=first.cause.stackTrace&&first.cause.stackTrace[0];var title=createElement('span');if(reason)
title.createTextChild(Common.UIString('%s for ',reason));else
title.createTextChild(Common.UIString('Unknown cause for '));this._appendTruncatedNodeList(title,this._invalidations);if(topFrame&&this._contentHelper.linkifier()){title.createTextChild(Common.UIString('. '));var stack=title.createChild('span','monospace');stack.createChild('span').textContent=Timeline.TimelineUIUtils.frameDisplayName(topFrame);var link=this._contentHelper.linkifier().maybeLinkifyConsoleCallFrame(target,topFrame);if(link){stack.createChild('span').textContent=' @ ';stack.createChild('span').appendChild(link);}}
return title;}
onpopulate(){var content=createElementWithClass('div','content');var first=this._invalidations[0];if(first.cause.stackTrace){var stack=content.createChild('div');stack.createTextChild(Common.UIString('Stack trace:'));this._contentHelper.createChildStackTraceElement(stack,Timeline.TimelineUIUtils._stackTraceFromCallFrames(first.cause.stackTrace));}
content.createTextChild(this._invalidations.length>1?Common.UIString('Nodes:'):Common.UIString('Node:'));var nodeList=content.createChild('div','node-list');var firstNode=true;for(var i=0;i<this._invalidations.length;i++){var invalidation=this._invalidations[i];var invalidationNode=this._createInvalidationNode(invalidation,true);if(invalidationNode){if(!firstNode)
nodeList.createTextChild(Common.UIString(', '));firstNode=false;nodeList.appendChild(invalidationNode);var extraData=invalidation.extraData?', '+invalidation.extraData:'';if(invalidation.changedId){nodeList.createTextChild(Common.UIString('(changed id to "%s"%s)',invalidation.changedId,extraData));}else if(invalidation.changedClass){nodeList.createTextChild(Common.UIString('(changed class to "%s"%s)',invalidation.changedClass,extraData));}else if(invalidation.changedAttribute){nodeList.createTextChild(Common.UIString('(changed attribute to "%s"%s)',invalidation.changedAttribute,extraData));}else if(invalidation.changedPseudo){nodeList.createTextChild(Common.UIString('(changed pesudo to "%s"%s)',invalidation.changedPseudo,extraData));}else if(invalidation.selectorPart){nodeList.createTextChild(Common.UIString('(changed "%s"%s)',invalidation.selectorPart,extraData));}}}
var contentTreeElement=new UI.TreeElement(content,false);contentTreeElement.selectable=false;this.appendChild(contentTreeElement);}
_appendTruncatedNodeList(parentElement,invalidations){var invalidationNodes=[];var invalidationNodeIdMap={};for(var i=0;i<invalidations.length;i++){var invalidation=invalidations[i];var invalidationNode=this._createInvalidationNode(invalidation,false);invalidationNode.addEventListener('click',e=>e.consume(),false);if(invalidationNode&&!invalidationNodeIdMap[invalidation.nodeId]){invalidationNodes.push(invalidationNode);invalidationNodeIdMap[invalidation.nodeId]=true;}}
if(invalidationNodes.length===1){parentElement.appendChild(invalidationNodes[0]);}else if(invalidationNodes.length===2){parentElement.appendChild(invalidationNodes[0]);parentElement.createTextChild(Common.UIString(' and '));parentElement.appendChild(invalidationNodes[1]);}else if(invalidationNodes.length>=3){parentElement.appendChild(invalidationNodes[0]);parentElement.createTextChild(Common.UIString(', '));parentElement.appendChild(invalidationNodes[1]);parentElement.createTextChild(Common.UIString(', and %s others',invalidationNodes.length-2));}}
_createInvalidationNode(invalidation,showUnknownNodes){var node=(invalidation.nodeId&&this._relatedNodesMap)?this._relatedNodesMap.get(invalidation.nodeId):null;if(node)
return Components.DOMPresentationUtils.linkifyNodeReference(node);if(invalidation.nodeName){var nodeSpan=createElement('span');nodeSpan.textContent=Common.UIString('[ %s ]',invalidation.nodeName);return nodeSpan;}
if(showUnknownNodes){var nodeSpan=createElement('span');return nodeSpan.createTextChild(Common.UIString('[ unknown node ]'));}}};Timeline.TimelineUIUtils._previewElementSymbol=Symbol('previewElement');Timeline.TimelineUIUtils.EventDispatchTypeDescriptor=class{constructor(priority,color,eventTypes){this.priority=priority;this.color=color;this.eventTypes=eventTypes;}};Timeline.TimelineCategory=class extends Common.Object{constructor(name,title,visible,childColor,color){super();this.name=name;this.title=title;this.visible=visible;this.childColor=childColor;this.color=color;this.hidden=false;}
get hidden(){return this._hidden;}
set hidden(hidden){this._hidden=hidden;this.dispatchEventToListeners(Timeline.TimelineCategory.Events.VisibilityChanged,this);}};Timeline.TimelineCategory.Events={VisibilityChanged:Symbol('VisibilityChanged')};Timeline.TimelineMarkerStyle;Timeline.TimelinePopupContentHelper=class{constructor(title){this._contentTable=createElement('table');var titleCell=this._createCell(Common.UIString('%s - Details',title),'timeline-details-title');titleCell.colSpan=2;var titleRow=createElement('tr');titleRow.appendChild(titleCell);this._contentTable.appendChild(titleRow);}
contentTable(){return this._contentTable;}
_createCell(content,styleName){var text=createElement('label');text.createTextChild(String(content));var cell=createElement('td');cell.className='timeline-details';if(styleName)
cell.className+=' '+styleName;cell.textContent=content;return cell;}
appendTextRow(title,content){var row=createElement('tr');row.appendChild(this._createCell(title,'timeline-details-row-title'));row.appendChild(this._createCell(content,'timeline-details-row-data'));this._contentTable.appendChild(row);}
appendElementRow(title,content){var row=createElement('tr');var titleCell=this._createCell(title,'timeline-details-row-title');row.appendChild(titleCell);var cell=createElement('td');cell.className='details';if(content instanceof Node)
cell.appendChild(content);else
cell.createTextChild(content||'');row.appendChild(cell);this._contentTable.appendChild(row);}};Timeline.TimelineDetailsContentHelper=class{constructor(target,linkifier){this.fragment=createDocumentFragment();this._linkifier=linkifier;this._target=target;this.element=createElementWithClass('div','timeline-details-view-block');this._tableElement=this.element.createChild('div','vbox timeline-details-chip-body');this.fragment.appendChild(this.element);}
addSection(title,swatchColor){if(!this._tableElement.hasChildNodes()){this.element.removeChildren();}else{this.element=createElementWithClass('div','timeline-details-view-block');this.fragment.appendChild(this.element);}
if(title){var titleElement=this.element.createChild('div','timeline-details-chip-title');if(swatchColor)
titleElement.createChild('div').style.backgroundColor=swatchColor;titleElement.createTextChild(title);}
this._tableElement=this.element.createChild('div','vbox timeline-details-chip-body');this.fragment.appendChild(this.element);}
linkifier(){return this._linkifier;}
appendTextRow(title,value){var rowElement=this._tableElement.createChild('div','timeline-details-view-row');rowElement.createChild('div','timeline-details-view-row-title').textContent=title;rowElement.createChild('div','timeline-details-view-row-value').textContent=value;}
appendElementRow(title,content,isWarning,isStacked){var rowElement=this._tableElement.createChild('div','timeline-details-view-row');if(isWarning)
rowElement.classList.add('timeline-details-warning');if(isStacked)
rowElement.classList.add('timeline-details-stack-values');var titleElement=rowElement.createChild('div','timeline-details-view-row-title');titleElement.textContent=title;var valueElement=rowElement.createChild('div','timeline-details-view-row-value');if(content instanceof Node)
valueElement.appendChild(content);else
valueElement.createTextChild(content||'');}
appendLocationRow(title,url,startLine,startColumn){if(!this._linkifier||!this._target)
return;var link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine,startColumn);if(!link)
return;this.appendElementRow(title,link);}
appendLocationRange(title,url,startLine,endLine){if(!this._linkifier||!this._target)
return;var locationContent=createElement('span');var link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine);if(!link)
return;locationContent.appendChild(link);locationContent.createTextChild(String.sprintf(' [%s\u2026%s]',startLine+1,endLine+1||''));this.appendElementRow(title,locationContent);}
appendStackTrace(title,stackTrace){if(!this._linkifier||!this._target)
return;var rowElement=this._tableElement.createChild('div','timeline-details-view-row');rowElement.createChild('div','timeline-details-view-row-title').textContent=title;this.createChildStackTraceElement(rowElement,stackTrace);}
createChildStackTraceElement(parentElement,stackTrace){if(!this._linkifier||!this._target)
return;parentElement.classList.add('timeline-details-stack-values');var stackTraceElement=parentElement.createChild('div','timeline-details-view-row-value timeline-details-view-row-stack-trace');var callFrameElem=Components.DOMPresentationUtils.buildStackTracePreviewContents(this._target,this._linkifier,stackTrace);stackTraceElement.appendChild(callFrameElem);}
appendWarningRow(event,warningType){var warning=Timeline.TimelineUIUtils.eventWarning(event,warningType);if(warning)
this.appendElementRow(Common.UIString('Warning'),warning,true);}};Timeline.TimelineUIUtils._categoryBreakdownCacheSymbol=Symbol('categoryBreakdownCache');;Timeline.TimelineLayersView=class extends UI.SplitWidget{constructor(model,showPaintProfilerCallback){super(true,false,'timelineLayersView');this._model=model;this._showPaintProfilerCallback=showPaintProfilerCallback;this.element.classList.add('timeline-layers-view');this._rightSplitWidget=new UI.SplitWidget(true,true,'timelineLayersViewDetails');this._rightSplitWidget.element.classList.add('timeline-layers-view-properties');this.setMainWidget(this._rightSplitWidget);var vbox=new UI.VBox();this.setSidebarWidget(vbox);this._layerViewHost=new LayerViewer.LayerViewHost();var layerTreeOutline=new LayerViewer.LayerTreeOutline(this._layerViewHost);vbox.element.appendChild(layerTreeOutline.element);this._layers3DView=new LayerViewer.Layers3DView(this._layerViewHost);this._layers3DView.addEventListener(LayerViewer.Layers3DView.Events.PaintProfilerRequested,this._onPaintProfilerRequested,this);this._rightSplitWidget.setMainWidget(this._layers3DView);var layerDetailsView=new LayerViewer.LayerDetailsView(this._layerViewHost);this._rightSplitWidget.setSidebarWidget(layerDetailsView);layerDetailsView.addEventListener(LayerViewer.LayerDetailsView.Events.PaintProfilerRequested,this._onPaintProfilerRequested,this);}
showLayerTree(frameLayerTree){this._frameLayerTree=frameLayerTree;if(this.isShowing())
this._update();else
this._updateWhenVisible=true;}
wasShown(){if(this._updateWhenVisible){this._updateWhenVisible=false;this._update();}}
_onPaintProfilerRequested(event){var selection=(event.data);this._layers3DView.snapshotForSelection(selection).then(snapshotWithRect=>{if(snapshotWithRect)
this._showPaintProfilerCallback(snapshotWithRect.snapshot);});}
_update(){this._frameLayerTree.layerTreePromise().then(layerTree=>this._layerViewHost.setLayerTree(layerTree));}};;Timeline.TimelinePaintProfilerView=class extends UI.SplitWidget{constructor(frameModel){super(false,false);this.element.classList.add('timeline-paint-profiler-view');this.setSidebarSize(60);this.setResizable(false);this._frameModel=frameModel;this._logAndImageSplitWidget=new UI.SplitWidget(true,false);this._logAndImageSplitWidget.element.classList.add('timeline-paint-profiler-log-split');this.setMainWidget(this._logAndImageSplitWidget);this._imageView=new Timeline.TimelinePaintImageView();this._logAndImageSplitWidget.setMainWidget(this._imageView);this._paintProfilerView=new LayerViewer.PaintProfilerView(this._imageView.showImage.bind(this._imageView));this._paintProfilerView.addEventListener(LayerViewer.PaintProfilerView.Events.WindowChanged,this._onWindowChanged,this);this.setSidebarWidget(this._paintProfilerView);this._logTreeView=new LayerViewer.PaintProfilerCommandLogView();this._logAndImageSplitWidget.setSidebarWidget(this._logTreeView);this._needsUpdateWhenVisible=false;this._pendingSnapshot=null;this._event=null;this._paintProfilerModel=null;this._lastLoadedSnapshot=null;}
wasShown(){if(this._needsUpdateWhenVisible){this._needsUpdateWhenVisible=false;this._update();}}
setSnapshot(snapshot){this._releaseSnapshot();this._pendingSnapshot=snapshot;this._event=null;this._updateWhenVisible();}
setEvent(paintProfilerModel,event){this._releaseSnapshot();this._paintProfilerModel=paintProfilerModel;this._pendingSnapshot=null;this._event=event;this._updateWhenVisible();if(this._event.name===TimelineModel.TimelineModel.RecordType.Paint)
return!!TimelineModel.TimelineData.forEvent(event).picture;if(this._event.name===TimelineModel.TimelineModel.RecordType.RasterTask)
return this._frameModel.hasRasterTile(this._event);return false;}
_updateWhenVisible(){if(this.isShowing())
this._update();else
this._needsUpdateWhenVisible=true;}
_update(){this._logTreeView.setCommandLog([]);this._paintProfilerView.setSnapshotAndLog(null,[],null);var snapshotPromise;if(this._pendingSnapshot){snapshotPromise=Promise.resolve({rect:null,snapshot:this._pendingSnapshot});}else if(this._event.name===TimelineModel.TimelineModel.RecordType.Paint){var picture=TimelineModel.TimelineData.forEvent(this._event).picture;snapshotPromise=picture.objectPromise().then(data=>this._paintProfilerModel.loadSnapshot(data['skp64'])).then(snapshot=>snapshot&&{rect:null,snapshot:snapshot});}else if(this._event.name===TimelineModel.TimelineModel.RecordType.RasterTask){snapshotPromise=this._frameModel.rasterTilePromise(this._event);}else{console.assert(false,'Unexpected event type or no snapshot');return;}
snapshotPromise.then(snapshotWithRect=>{this._releaseSnapshot();if(!snapshotWithRect){this._imageView.showImage();return;}
var snapshot=snapshotWithRect.snapshot;this._lastLoadedSnapshot=snapshot;this._imageView.setMask(snapshotWithRect.rect);snapshot.commandLog().then(log=>onCommandLogDone.call(this,snapshot,snapshotWithRect.rect,log));});function onCommandLogDone(snapshot,clipRect,log){this._logTreeView.setCommandLog(log||[]);this._paintProfilerView.setSnapshotAndLog(snapshot,log||[],clipRect);}}
_releaseSnapshot(){if(!this._lastLoadedSnapshot)
return;this._lastLoadedSnapshot.release();this._lastLoadedSnapshot=null;}
_onWindowChanged(){this._logTreeView.updateWindow(this._paintProfilerView.selectionWindow());}};Timeline.TimelinePaintImageView=class extends UI.Widget{constructor(){super(true);this.registerRequiredCSS('timeline/timelinePaintProfiler.css');this.contentElement.classList.add('fill','paint-profiler-image-view');this._imageContainer=this.contentElement.createChild('div','paint-profiler-image-container');this._imageElement=this._imageContainer.createChild('img');this._maskElement=this._imageContainer.createChild('div');this._imageElement.addEventListener('load',this._updateImagePosition.bind(this),false);this._transformController=new LayerViewer.TransformController(this.contentElement,true);this._transformController.addEventListener(LayerViewer.TransformController.Events.TransformChanged,this._updateImagePosition,this);}
onResize(){if(this._imageElement.src)
this._updateImagePosition();}
_updateImagePosition(){var width=this._imageElement.naturalWidth;var height=this._imageElement.naturalHeight;var clientWidth=this.contentElement.clientWidth;var clientHeight=this.contentElement.clientHeight;var paddingFraction=0.1;var paddingX=clientWidth*paddingFraction;var paddingY=clientHeight*paddingFraction;var scaleX=(clientWidth-paddingX)/width;var scaleY=(clientHeight-paddingY)/height;var scale=Math.min(scaleX,scaleY);if(this._maskRectangle){var style=this._maskElement.style;style.width=width+'px';style.height=height+'px';style.borderLeftWidth=this._maskRectangle.x+'px';style.borderTopWidth=this._maskRectangle.y+'px';style.borderRightWidth=(width-this._maskRectangle.x-this._maskRectangle.width)+'px';style.borderBottomWidth=(height-this._maskRectangle.y-this._maskRectangle.height)+'px';}
this._transformController.setScaleConstraints(0.5,10/scale);var matrix=new WebKitCSSMatrix().scale(this._transformController.scale(),this._transformController.scale()).translate(clientWidth/2,clientHeight/2).scale(scale,scale).translate(-width/2,-height/2);var bounds=UI.Geometry.boundsForTransformedPoints(matrix,[0,0,0,width,height,0]);this._transformController.clampOffsets(paddingX-bounds.maxX,clientWidth-paddingX-bounds.minX,paddingY-bounds.maxY,clientHeight-paddingY-bounds.minY);matrix=new WebKitCSSMatrix().translate(this._transformController.offsetX(),this._transformController.offsetY()).multiply(matrix);this._imageContainer.style.webkitTransform=matrix.toString();}
showImage(imageURL){this._imageContainer.classList.toggle('hidden',!imageURL);if(imageURL)
this._imageElement.src=imageURL;}
setMask(maskRectangle){this._maskRectangle=maskRectangle;this._maskElement.classList.toggle('hidden',!maskRectangle);}};;Timeline.TimelinePanel=class extends UI.Panel{constructor(){super('timeline');this.registerRequiredCSS('timeline/timelinePanel.css');this.element.addEventListener('contextmenu',this._contextMenu.bind(this),false);this._dropTarget=new UI.DropTarget(this.element,[UI.DropTarget.Types.Files,UI.DropTarget.Types.URIList],Common.UIString('Drop timeline file or URL here'),this._handleDrop.bind(this));this._recordingOptionUIControls=[];this._state=Timeline.TimelinePanel.State.Idle;this._windowStartTime=0;this._windowEndTime=Infinity;this._millisecondsToRecordAfterLoadEvent=3000;this._toggleRecordAction=(UI.actionRegistry.action('timeline.toggle-recording'));this._filters=[];if(!Runtime.experiments.isEnabled('timelineShowAllEvents')){this._filters.push(Timeline.TimelineUIUtils.visibleEventsFilter());this._filters.push(new TimelineModel.ExcludeTopLevelFilter());}
if(!Runtime.experiments.isEnabled('timelinePaintTimingMarkers'))
this._filters.push(Timeline.TimelineUIUtils.paintEventsFilter());this._performanceModel=null;this._pendingPerformanceModel=null;this._cpuThrottlingManager=new Components.CPUThrottlingManager();this._viewModeSetting=Common.settings.createSetting('timelineViewMode',Timeline.TimelinePanel.ViewMode.FlameChart);this._disableCaptureJSProfileSetting=Common.settings.createSetting('timelineDisableJSSampling',false);this._disableCaptureJSProfileSetting.setTitle(Common.UIString('Disable JavaScript Samples'));this._captureLayersAndPicturesSetting=Common.settings.createSetting('timelineCaptureLayersAndPictures',false);this._captureLayersAndPicturesSetting.setTitle(Common.UIString('Enable advanced paint instrumentation (slow)'));this._showScreenshotsSetting=Common.settings.createSetting('timelineShowScreenshots',true);this._showScreenshotsSetting.setTitle(Common.UIString('Screenshots'));this._showScreenshotsSetting.addChangeListener(this._onModeChanged,this);this._showMemorySetting=Common.settings.createSetting('timelineShowMemory',false);this._showMemorySetting.setTitle(Common.UIString('Memory'));this._showMemorySetting.addChangeListener(this._onModeChanged,this);this._panelToolbar=new UI.Toolbar('',this.element);this._createSettingsPane();this._updateShowSettingsToolbarButton();this._timelinePane=new UI.VBox();this._timelinePane.show(this.element);var topPaneElement=this._timelinePane.element.createChild('div','hbox');topPaneElement.id='timeline-overview-panel';this._overviewPane=new PerfUI.TimelineOverviewPane('timeline');this._overviewPane.addEventListener(PerfUI.TimelineOverviewPane.Events.WindowChanged,this._onWindowChanged.bind(this));this._overviewPane.show(topPaneElement);this._overviewControls=[];this._statusPaneContainer=this._timelinePane.element.createChild('div','status-pane-container fill');this._createFileSelector();SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.PageReloadRequested,this._pageReloadRequested,this);SDK.targetManager.addModelListener(SDK.ResourceTreeModel,SDK.ResourceTreeModel.Events.Load,this._loadEventFired,this);if(Runtime.experiments.isEnabled('timelineMultipleMainViews')){var viewMode=Timeline.TimelinePanel.ViewMode;this._tabbedPane=new UI.TabbedPane();this._tabbedPane.appendTab(viewMode.FlameChart,Common.UIString('Flame Chart'),new UI.VBox());this._tabbedPane.appendTab(viewMode.BottomUp,Common.UIString('Bottom-Up'),new UI.VBox());this._tabbedPane.appendTab(viewMode.CallTree,Common.UIString('Call Tree'),new UI.VBox());this._tabbedPane.appendTab(viewMode.EventLog,Common.UIString('Event Log'),new UI.VBox());this._tabbedPane.addEventListener(UI.TabbedPane.Events.TabSelected,this._onMainViewChanged.bind(this));this._tabbedPane.selectTab(this._viewModeSetting.get());}
this._onModeChanged();this._populateToolbar();this._showLandingPage();Extensions.extensionServer.addEventListener(Extensions.ExtensionServer.Events.TraceProviderAdded,this._appendExtensionsToToolbar,this);SDK.targetManager.addEventListener(SDK.TargetManager.Events.SuspendStateChanged,this._onSuspendStateChanged,this);this._selectedSearchResult;}
static instance(){return(self.runtime.sharedInstance(Timeline.TimelinePanel));}
searchableView(){return this._searchableView;}
wasShown(){UI.context.setFlavor(Timeline.TimelinePanel,this);}
willHide(){UI.context.setFlavor(Timeline.TimelinePanel,null);}
_onWindowChanged(event){this._windowStartTime=event.data.startTime;this._windowEndTime=event.data.endTime;this._currentView.setWindowTimes(this._windowStartTime,this._windowEndTime);if(!this._selection||this._selection.type()===Timeline.TimelineSelection.Type.Range)
this.select(null);}
_onMainViewChanged(){this._viewModeSetting.set(this._tabbedPane.selectedTabId);this._onModeChanged();}
_onOverviewSelectionChanged(event){var selection=(event.data);this.select(selection);}
requestWindowTimes(windowStartTime,windowEndTime){this._overviewPane.requestWindowTimes(windowStartTime,windowEndTime);}
_setState(state){this._state=state;this._updateTimelineControls();}
_createSettingCheckbox(setting,tooltip){const checkboxItem=new UI.ToolbarSettingCheckbox(setting,tooltip);this._recordingOptionUIControls.push(checkboxItem);return checkboxItem;}
_populateToolbar(){this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButton(this._toggleRecordAction));this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButtonForId('main.reload'));this._clearButton=new UI.ToolbarButton(Common.UIString('Clear'),'largeicon-clear');this._clearButton.addEventListener(UI.ToolbarButton.Events.Click,()=>this._clear());this._panelToolbar.appendToolbarItem(this._clearButton);this._panelToolbar.appendSeparator();this._panelToolbar.appendSeparator();this._showScreenshotsToolbarCheckbox=this._createSettingCheckbox(this._showScreenshotsSetting,Common.UIString('Capture screenshots'));this._panelToolbar.appendToolbarItem(this._showScreenshotsToolbarCheckbox);this._showMemoryToolbarCheckbox=this._createSettingCheckbox(this._showMemorySetting,Common.UIString('Show memory timeline'));this._panelToolbar.appendToolbarItem(this._showMemoryToolbarCheckbox);this._panelToolbar.appendToolbarItem(UI.Toolbar.createActionButtonForId('components.collect-garbage'));this._panelToolbar.appendSpacer();this._panelToolbar.appendText('');this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._showSettingsPaneButton);}
_createSettingsPane(){this._showSettingsPaneSetting=Common.settings.createSetting('timelineShowSettingsToolbar',false);this._showSettingsPaneButton=new UI.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',Common.UIString('Capture settings'));SDK.multitargetNetworkManager.addEventListener(SDK.MultitargetNetworkManager.Events.ConditionsChanged,this._updateShowSettingsToolbarButton,this);this._cpuThrottlingManager.addEventListener(Components.CPUThrottlingManager.Events.RateChanged,this._updateShowSettingsToolbarButton,this);this._disableCaptureJSProfileSetting.addChangeListener(this._updateShowSettingsToolbarButton,this);this._captureLayersAndPicturesSetting.addChangeListener(this._updateShowSettingsToolbarButton,this);this._settingsPane=new UI.HBox();this._settingsPane.element.classList.add('timeline-settings-pane');this._settingsPane.show(this.element);var captureToolbar=new UI.Toolbar('',this._settingsPane.element);captureToolbar.element.classList.add('flex-auto');captureToolbar.makeVertical();captureToolbar.appendToolbarItem(this._createSettingCheckbox(this._disableCaptureJSProfileSetting,Common.UIString('Disables JavaScript sampling, reduces overhead when running against mobile devices')));captureToolbar.appendToolbarItem(this._createSettingCheckbox(this._captureLayersAndPicturesSetting,Common.UIString('Captures advanced paint instrumentation, introduces significant performance overhead')));var throttlingPane=new UI.VBox();throttlingPane.element.classList.add('flex-auto');throttlingPane.show(this._settingsPane.element);var throttlingToolbar1=new UI.Toolbar('',throttlingPane.element);throttlingToolbar1.appendText(Common.UIString('Network:'));throttlingToolbar1.appendToolbarItem(this._createNetworkConditionsSelect());var throttlingToolbar2=new UI.Toolbar('',throttlingPane.element);throttlingToolbar2.appendText(Common.UIString('CPU:'));throttlingToolbar2.appendToolbarItem(this._cpuThrottlingManager.createControl());this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this));this._updateSettingsPaneVisibility();}
_appendExtensionsToToolbar(event){var provider=(event.data);const setting=Timeline.TimelinePanel._settingForTraceProvider(provider);const checkbox=this._createSettingCheckbox(setting,provider.longDisplayName());this._panelToolbar.appendToolbarItem(checkbox);}
static _settingForTraceProvider(traceProvider){var setting=traceProvider[Timeline.TimelinePanel._traceProviderSettingSymbol];if(!setting){var providerId=traceProvider.persistentIdentifier();setting=Common.settings.createSetting(providerId,false);setting.setTitle(traceProvider.shortDisplayName());traceProvider[Timeline.TimelinePanel._traceProviderSettingSymbol]=setting;}
return setting;}
_createNetworkConditionsSelect(){var toolbarItem=new UI.ToolbarComboBox(null);toolbarItem.setMaxWidth(140);NetworkConditions.NetworkConditionsSelector.decorateSelect(toolbarItem.selectElement());return toolbarItem;}
_prepareToLoadTimeline(){console.assert(this._state===Timeline.TimelinePanel.State.Idle);this._setState(Timeline.TimelinePanel.State.Loading);this._pendingPerformanceModel=new Timeline.PerformanceModel();}
_createFileSelector(){if(this._fileSelectorElement)
this._fileSelectorElement.remove();this._fileSelectorElement=UI.createFileSelectorElement(this._loadFromFile.bind(this));this._timelinePane.element.appendChild(this._fileSelectorElement);}
_contextMenu(event){var contextMenu=new UI.ContextMenu(event);contextMenu.appendItemsAtLocation('timelineMenu');contextMenu.show();}
_saveToFile(){if(this._state!==Timeline.TimelinePanel.State.Idle)
return true;if(!this._performanceModel)
return true;var now=new Date();var fileName='Profile-'+now.toISO8601Compact()+'.json';var stream=new Bindings.FileOutputStream();function callback(accepted){if(!accepted)
return;var saver=new Timeline.TracingTimelineSaver();this._backingStorage.writeToStream(stream,saver);}
stream.open(fileName,callback.bind(this));return true;}
_selectFileToLoad(){this._fileSelectorElement.click();return true;}
_loadFromFile(file){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;this._prepareToLoadTimeline();this._loader=Timeline.TimelineLoader.loadFromFile(file,this);this._createFileSelector();}
_loadFromURL(url){if(this._state!==Timeline.TimelinePanel.State.Idle)
return;this._prepareToLoadTimeline();this._loader=Timeline.TimelineLoader.loadFromURL(url,this);}
_onModeChanged(){this._overviewControls=[];this._overviewControls.push(new Timeline.TimelineEventOverviewResponsiveness());if(Runtime.experiments.isEnabled('inputEventsOnTimelineOverview'))
this._overviewControls.push(new Timeline.TimelineEventOverviewInput());this._overviewControls.push(new Timeline.TimelineEventOverviewFrames());this._overviewControls.push(new Timeline.TimelineEventOverviewCPUActivity());this._overviewControls.push(new Timeline.TimelineEventOverviewNetwork());if(this._showScreenshotsSetting.get())
this._overviewControls.push(new Timeline.TimelineFilmStripOverview());if(this._showMemorySetting.get())
this._overviewControls.push(new Timeline.TimelineEventOverviewMemory());for(var control of this._overviewControls)
control.setModel(this._performanceModel);this._overviewPane.setOverviewControls(this._overviewControls);if(this._currentView)
this._currentView.detach();var viewMode=Runtime.experiments.isEnabled('timelineMultipleMainViews')?this._tabbedPane.selectedTabId:Timeline.TimelinePanel.ViewMode.FlameChart;this._flameChart=null;var mainView;if(viewMode===Timeline.TimelinePanel.ViewMode.FlameChart){this._flameChart=new Timeline.TimelineFlameChartView(this,this._filters);mainView=this._flameChart;this._currentView=this._flameChart;}else{switch(viewMode){case Timeline.TimelinePanel.ViewMode.CallTree:mainView=new Timeline.CallTreeTimelineTreeView(this._filters);break;case Timeline.TimelinePanel.ViewMode.EventLog:mainView=new Timeline.EventsTimelineTreeView(this._filters,this);break;default:mainView=new Timeline.BottomUpTimelineTreeView(this._filters);break;}
var treeView=new Timeline.TimelineTreeModeView(this,mainView);this._currentView=treeView;}
this._currentView.setModel(this._performanceModel);this._currentView.setWindowTimes(this._windowStartTime,this._windowEndTime);if(this._searchableView)
this._searchableView.detach();this._searchableView=new UI.SearchableView(mainView);this._searchableView.setMinimumSize(0,100);this._searchableView.element.classList.add('searchable-view');this._searchableView.show(this._timelinePane.element);if(Runtime.experiments.isEnabled('timelineMultipleMainViews')){this._tabbedPane.show(this._searchableView.element);this._currentView.show(this._tabbedPane.visibleView.element);}else{this._currentView.show(this._searchableView.element);}
mainView.setSearchableView(this._searchableView);if(this._lastViewMode!==viewMode){this._lastViewMode=viewMode;this._searchableView.cancelSearch();}
this.doResize();this.select(null);}
_updateSettingsPaneVisibility(){if(this._showSettingsPaneSetting.get())
this._settingsPane.showWidget();else
this._settingsPane.hideWidget();}
_updateShowSettingsToolbarButton(){var messages=[];if(this._cpuThrottlingManager.rate()!==1)
messages.push(Common.UIString('- CPU throttling is enabled'));if(SDK.multitargetNetworkManager.isThrottling())
messages.push(Common.UIString('- Network throttling is enabled'));if(this._captureLayersAndPicturesSetting.get())
messages.push(Common.UIString('- Significant overhead due to paint instrumentation'));if(this._disableCaptureJSProfileSetting.get())
messages.push(Common.UIString('- JavaScript sampling is disabled'));this._showSettingsPaneButton.setDefaultWithRedColor(messages.length);this._showSettingsPaneButton.setToggleWithRedColor(messages.length);if(messages.length){var tooltipElement=createElement('div');messages.forEach(message=>{tooltipElement.createChild('div').textContent=message;});this._showSettingsPaneButton.setTitle(tooltipElement);}else{this._showSettingsPaneButton.setTitle(Common.UIString('Capture settings'));}}
_setUIControlsEnabled(enabled){this._recordingOptionUIControls.forEach(control=>control.setEnabled(enabled));}
_startRecording(tracingManager,userInitiated){console.assert(!this._statusPane,'Status pane is already opened.');this._setState(Timeline.TimelinePanel.State.StartPending);this._showRecordingStarted();this._autoRecordGeneration=userInitiated?null:{tracingManager:tracingManager};var enabledTraceProviders=Extensions.extensionServer.traceProviders().filter(provider=>Timeline.TimelinePanel._settingForTraceProvider(provider).get());const recordingOptions={enableJSSampling:!this._disableCaptureJSProfileSetting.get(),capturePictures:this._captureLayersAndPicturesSetting.get(),captureFilmStrip:this._showScreenshotsSetting.get()};this._pendingPerformanceModel=new Timeline.PerformanceModel();this._controller=new Timeline.TimelineController(tracingManager,this._pendingPerformanceModel,this);Host.userMetrics.actionTaken(userInitiated?Host.UserMetrics.Action.TimelineStarted:Host.UserMetrics.Action.TimelinePageReloadStarted);this._setUIControlsEnabled(false);this._hideLandingPage();return this._controller.startRecording(recordingOptions,enabledTraceProviders).then(()=>this._recordingStarted());}
_stopRecording(){if(this._statusPane){this._statusPane.finish();this._statusPane.updateStatus(Common.UIString('Stopping timeline\u2026'));this._statusPane.updateProgressBar(Common.UIString('Received'),0);}
this._setState(Timeline.TimelinePanel.State.StopPending);this._autoRecordGeneration=null;this._controller.stopRecording();this._controller=null;this._setUIControlsEnabled(true);}
_onSuspendStateChanged(){this._updateTimelineControls();}
_updateTimelineControls(){var state=Timeline.TimelinePanel.State;this._toggleRecordAction.setToggled(this._state===state.Recording);this._toggleRecordAction.setEnabled(this._state===state.Recording||this._state===state.Idle);this._clearButton.setEnabled(this._state===state.Idle);this._panelToolbar.setEnabled(this._state!==state.Loading);this._dropTarget.setEnabled(this._state===state.Idle);}
_toggleRecording(){if(this._state===Timeline.TimelinePanel.State.Idle){var tracingManagers=SDK.targetManager.models(SDK.TracingManager);if(tracingManagers.length)
this._startRecording(tracingManagers[0],true);}else if(this._state===Timeline.TimelinePanel.State.Recording){this._stopRecording();}}
_clear(){this._showLandingPage();this._reset();}
_reset(){PerfUI.LineLevelProfile.instance().reset();this._setModel(null);delete this._selection;}
_setModel(model){if(this._performanceModel)
this._performanceModel.dispose();this._performanceModel=model;this._currentView.setModel(model);this._overviewPane.reset();if(model){this._overviewPane.setBounds(model.timelineModel().minimumRecordTime(),model.timelineModel().maximumRecordTime());}
for(var control of this._overviewControls)
control.setModel(model);if(model){var cpuProfiles=model.timelineModel().cpuProfiles();cpuProfiles.forEach(profile=>PerfUI.LineLevelProfile.instance().appendCPUProfile(profile));this._setAutoWindowTimes(model.timelineModel());this._setMarkers(model.timelineModel());}else{this.requestWindowTimes(0,Infinity);}
this._overviewPane.scheduleUpdate();this.select(null);if(this._flameChart)
this._flameChart.resizeToPreferredHeights();}
_recordingStarted(){this._reset();this._setState(Timeline.TimelinePanel.State.Recording);this._showRecordingStarted();this._statusPane.updateStatus(Common.UIString('Profiling\u2026'));this._statusPane.updateProgressBar(Common.UIString('Buffer usage'),0);this._statusPane.startTimer();this._hideLandingPage();}
recordingProgress(usage){this._statusPane.updateProgressBar(Common.UIString('Buffer usage'),usage*100);}
_showLandingPage(){if(this._landingPage){this._landingPage.show(this._statusPaneContainer);return;}
function encloseWithTag(tagName,contents){var e=createElement(tagName);e.textContent=contents;return e;}
var learnMoreNode=UI.createExternalLink('https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/',Common.UIString('Learn\xa0more'));var learnMoreMigrationNode=UI.createExternalLink('https://developers.google.com/web/updates/2016/12/devtools-javascript-cpu-profile-migration',Common.UIString('Learn\xa0more'));var recordKey=encloseWithTag('b',UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording')[0].name);var reloadKey=encloseWithTag('b',UI.shortcutRegistry.shortcutDescriptorsForAction('main.reload')[0].name);var navigateNode=encloseWithTag('b',Common.UIString('WASD'));this._landingPage=new UI.VBox();this._landingPage.contentElement.classList.add('timeline-landing-page','fill');var centered=this._landingPage.contentElement.createChild('div');var recordButton=UI.Toolbar.createActionButton(this._toggleRecordAction).element;var reloadButton=UI.Toolbar.createActionButtonForId('main.reload').element;centered.createChild('p').appendChild(UI.formatLocalized('Click the record button %s or hit %s to capture a new recording.\n'+'Click the reload button %s or hit %s to record and evaluate the page load.',[recordButton,recordKey,reloadButton,reloadKey]));centered.createChild('p').appendChild(UI.formatLocalized('After recording, select an area of interest in the overview by dragging.\n'+'Then, zoom and pan the timeline with the mousewheel or %s keys.\n%s',[navigateNode,learnMoreNode]));var cpuProfilerHintSetting=Common.settings.createSetting('timelineShowProfilerHint',true);if(cpuProfilerHintSetting.get()){var warning=centered.createChild('p','timeline-landing-warning');var closeButton=warning.createChild('div','timeline-landing-warning-close','dt-close-button');closeButton.addEventListener('click',()=>{warning.style.visibility='hidden';cpuProfilerHintSetting.set(false);},false);var performanceSpan=encloseWithTag('b',Common.UIString('Performance'));warning.createChild('div').appendChild(UI.formatLocalized(`The %s panel provides the combined functionality of Timeline and JavaScript CPU profiler. %s%s`+`The JavaScript CPU profiler will be removed shortly. Meanwhile, it's available under `+`%s \u2192 More Tools \u2192 JavaScript Profiler.`,[performanceSpan,learnMoreMigrationNode,createElement('p'),UI.Icon.create('largeicon-menu')]));}
this._landingPage.show(this._statusPaneContainer);}
_hideLandingPage(){this._landingPage.detach();}
loadingStarted(){this._hideLandingPage();if(this._statusPane)
this._statusPane.hide();this._statusPane=new Timeline.TimelinePanel.StatusPane(false,this._cancelLoading.bind(this));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(Common.UIString('Loading profile\u2026'));if(!this._loader)
this._statusPane.finish();this.loadingProgress(0);}
loadingProgress(progress){if(typeof progress==='number')
this._statusPane.updateProgressBar(Common.UIString('Received'),progress*100);}
processingStarted(){this._statusPane.updateStatus(Common.UIString('Processing profile\u2026'));}
loadingComplete(tracingModel,backingStorage){delete this._loader;this._setState(Timeline.TimelinePanel.State.Idle);var performanceModel=this._pendingPerformanceModel;this._pendingPerformanceModel=null;this._backingStorage=backingStorage;if(this._statusPane)
this._statusPane.hide();delete this._statusPane;if(!tracingModel){performanceModel.dispose();this._clear();return;}
performanceModel.setTracingModel(tracingModel);this._backingStorage=backingStorage;this._setModel(performanceModel);}
_showRecordingStarted(){if(this._statusPane)
return;this._statusPane=new Timeline.TimelinePanel.StatusPane(true,this._stopRecording.bind(this));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(Common.UIString('Initializing profiler\u2026'));}
_cancelLoading(){if(this._loader)
this._loader.cancel();}
_setMarkers(timelineModel){var markers=new Map();var recordTypes=TimelineModel.TimelineModel.RecordType;var zeroTime=timelineModel.minimumRecordTime();for(var event of timelineModel.eventDividers()){if(event.name===recordTypes.TimeStamp||event.name===recordTypes.ConsoleTime)
continue;markers.set(event.startTime,Timeline.TimelineUIUtils.createEventDivider(event,zeroTime));}
this._overviewPane.setMarkers(markers);}
_pageReloadRequested(event){if(this._state!==Timeline.TimelinePanel.State.Idle||!this.isShowing())
return;var resourceTreeModel=(event.data);var tracingManager=resourceTreeModel.target().model(SDK.TracingManager);if(resourceTreeModel.target()!==SDK.targetManager.mainTarget()||!tracingManager)
return;resourceTreeModel.suspendReload();this._startRecording(tracingManager,false).then(()=>resourceTreeModel.resumeReload());}
_loadEventFired(event){if(this._state!==Timeline.TimelinePanel.State.Recording||!this._autoRecordGeneration||this._autoRecordGeneration.tracingManager.target()!==event.data.resourceTreeModel.target())
return;setTimeout(stopRecordingOnReload.bind(this,this._autoRecordGeneration),this._millisecondsToRecordAfterLoadEvent);function stopRecordingOnReload(recordGeneration){if(this._state!==Timeline.TimelinePanel.State.Recording||this._autoRecordGeneration!==recordGeneration)
return;this._stopRecording();}}
_frameForSelection(selection){switch(selection.type()){case Timeline.TimelineSelection.Type.Frame:return(selection.object());case Timeline.TimelineSelection.Type.Range:return null;case Timeline.TimelineSelection.Type.TraceEvent:return this._performanceModel.frameModel().filteredFrames(selection._endTime,selection._endTime)[0];default:console.assert(false,'Should never be reached');return null;}}
_jumpToFrame(offset){var currentFrame=this._frameForSelection(this._selection);if(!currentFrame)
return;var frames=this._performanceModel.frames();var index=frames.indexOf(currentFrame);console.assert(index>=0,'Can\'t find current frame in the frame list');index=Number.constrain(index+offset,0,frames.length-1);var frame=frames[index];this._revealTimeRange(frame.startTime,frame.endTime);this.select(Timeline.TimelineSelection.fromFrame(frame));return true;}
select(selection,preferredTab){if(!selection)
selection=Timeline.TimelineSelection.fromRange(this._windowStartTime,this._windowEndTime);this._selection=selection;this._currentView.setSelection(selection);}
selectEntryAtTime(time){var events=this._performanceModel?this._performanceModel.timelineModel().mainThreadEvents():[];for(var index=events.upperBound(time,(time,event)=>time-event.startTime)-1;index>=0;--index){var event=events[index];var endTime=event.endTime||event.startTime;if(SDK.TracingModel.isTopLevelEvent(event)&&endTime<time)
break;if(TimelineModel.TimelineModel.isVisible(this._filters,event)&&endTime>=time){this.select(Timeline.TimelineSelection.fromTraceEvent(event));return;}}
this.select(null);}
highlightEvent(event){this._currentView.highlightEvent(event);}
_revealTimeRange(startTime,endTime){var timeShift=0;if(this._windowEndTime<endTime)
timeShift=endTime-this._windowEndTime;else if(this._windowStartTime>startTime)
timeShift=startTime-this._windowStartTime;if(timeShift)
this.requestWindowTimes(this._windowStartTime+timeShift,this._windowEndTime+timeShift);}
_handleDrop(dataTransfer){var items=dataTransfer.items;if(!items.length)
return;var item=items[0];if(item.kind==='string'){var url=dataTransfer.getData('text/uri-list');if(new Common.ParsedURL(url).isValid)
this._loadFromURL(url);}else if(item.kind==='file'){var entry=items[0].webkitGetAsEntry();if(!entry.isFile)
return;entry.file(this._loadFromFile.bind(this));}}
_setAutoWindowTimes(timelineModel){var tasks=timelineModel.mainThreadTasks();if(!tasks.length){this.requestWindowTimes(timelineModel.minimumRecordTime(),timelineModel.maximumRecordTime());return;}
function findLowUtilizationRegion(startIndex,stopIndex){var threshold=0.1;var cutIndex=startIndex;var cutTime=(tasks[cutIndex].startTime+tasks[cutIndex].endTime)/2;var usedTime=0;var step=Math.sign(stopIndex-startIndex);for(var i=startIndex;i!==stopIndex;i+=step){var task=tasks[i];var taskTime=(task.startTime+task.endTime)/2;var interval=Math.abs(cutTime-taskTime);if(usedTime<threshold*interval){cutIndex=i;cutTime=taskTime;usedTime=0;}
usedTime+=task.duration;}
return cutIndex;}
var rightIndex=findLowUtilizationRegion(tasks.length-1,0);var leftIndex=findLowUtilizationRegion(0,rightIndex);var leftTime=tasks[leftIndex].startTime;var rightTime=tasks[rightIndex].endTime;var span=rightTime-leftTime;var totalSpan=timelineModel.maximumRecordTime()-timelineModel.minimumRecordTime();if(span<totalSpan*0.1){leftTime=timelineModel.minimumRecordTime();rightTime=timelineModel.maximumRecordTime();}else{leftTime=Math.max(leftTime-0.05*span,timelineModel.minimumRecordTime());rightTime=Math.min(rightTime+0.05*span,timelineModel.maximumRecordTime());}
this.requestWindowTimes(leftTime,rightTime);}};Timeline.TimelinePanel.State={Idle:Symbol('Idle'),StartPending:Symbol('StartPending'),Recording:Symbol('Recording'),StopPending:Symbol('StopPending'),Loading:Symbol('Loading')};Timeline.TimelinePanel.ViewMode={FlameChart:'FlameChart',BottomUp:'BottomUp',CallTree:'CallTree',EventLog:'EventLog'};Timeline.TimelinePanel.rowHeight=18;Timeline.TimelinePanel.headerHeight=20;Timeline.TimelineSelection=class{constructor(type,startTime,endTime,object){this._type=type;this._startTime=startTime;this._endTime=endTime;this._object=object||null;}
static fromFrame(frame){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.Frame,frame.startTime,frame.endTime,frame);}
static fromNetworkRequest(request){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.NetworkRequest,request.startTime,request.endTime||request.startTime,request);}
static fromTraceEvent(event){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.TraceEvent,event.startTime,event.endTime||(event.startTime+1),event);}
static fromRange(startTime,endTime){return new Timeline.TimelineSelection(Timeline.TimelineSelection.Type.Range,startTime,endTime);}
type(){return this._type;}
object(){return this._object;}
startTime(){return this._startTime;}
endTime(){return this._endTime;}};Timeline.TimelineSelection.Type={Frame:'Frame',NetworkRequest:'NetworkRequest',TraceEvent:'TraceEvent',Range:'Range'};Timeline.TimelineModeView=function(){};Timeline.TimelineModeView.prototype={view(){},resizerElement(){},setModel(model){},setWindowTimes(startTime,endTime){},setSelection(selection){},highlightEvent(event){}};Timeline.TimelineModeViewDelegate=function(){};Timeline.TimelineModeViewDelegate.prototype={requestWindowTimes(startTime,endTime){},select(selection,preferredTab){},selectEntryAtTime(time){},highlightEvent(event){}};Timeline.TimelinePanel.StatusPane=class extends UI.VBox{constructor(showTimer,stopCallback){super(true);this.registerRequiredCSS('timeline/timelineStatusDialog.css');this.contentElement.classList.add('timeline-status-dialog');var statusLine=this.contentElement.createChild('div','status-dialog-line status');statusLine.createChild('div','label').textContent=Common.UIString('Status');this._status=statusLine.createChild('div','content');if(showTimer){var timeLine=this.contentElement.createChild('div','status-dialog-line time');timeLine.createChild('div','label').textContent=Common.UIString('Time');this._time=timeLine.createChild('div','content');}
var progressLine=this.contentElement.createChild('div','status-dialog-line progress');this._progressLabel=progressLine.createChild('div','label');this._progressBar=progressLine.createChild('div','indicator-container').createChild('div','indicator');this._stopButton=UI.createTextButton(Common.UIString('Stop'),stopCallback);this.contentElement.createChild('div','stop-button').appendChild(this._stopButton);}
finish(){this._stopTimer();this._stopButton.disabled=true;}
hide(){this.element.parentNode.classList.remove('tinted');this.element.remove();}
showPane(parent){this.show(parent);parent.classList.add('tinted');}
updateStatus(text){this._status.textContent=text;}
updateProgressBar(activity,percent){this._progressLabel.textContent=activity;this._progressBar.style.width=percent.toFixed(1)+'%';this._updateTimer();}
startTimer(){this._startTime=Date.now();this._timeUpdateTimer=setInterval(this._updateTimer.bind(this,false),1000);this._updateTimer();}
_stopTimer(){if(!this._timeUpdateTimer)
return;clearInterval(this._timeUpdateTimer);this._updateTimer(true);delete this._timeUpdateTimer;}
_updateTimer(precise){if(!this._timeUpdateTimer)
return;var elapsed=(Date.now()-this._startTime)/1000;this._time.textContent=Common.UIString('%s\xa0sec',elapsed.toFixed(precise?1:0));}};Timeline.LoadTimelineHandler=class{handleQueryParam(value){UI.viewManager.showView('timeline').then(()=>{Timeline.TimelinePanel.instance()._loadFromURL(window.decodeURIComponent(value));});}};Timeline.TimelinePanel.ActionDelegate=class{handleAction(context,actionId){var panel=UI.context.flavor(Timeline.TimelinePanel);console.assert(panel&&panel instanceof Timeline.TimelinePanel);switch(actionId){case'timeline.toggle-recording':panel._toggleRecording();return true;case'timeline.save-to-file':panel._saveToFile();return true;case'timeline.load-from-file':panel._selectFileToLoad();return true;case'timeline.jump-to-previous-frame':panel._jumpToFrame(-1);return true;case'timeline.jump-to-next-frame':panel._jumpToFrame(1);return true;}
return false;}};Timeline.TimelinePanel._traceProviderSettingSymbol=Symbol('traceProviderSetting');;Runtime.cachedResources["timeline/invalidationsTree.css"]="/*\n * Copyright 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.header, .children, .content {\n    min-height: initial;\n    line-height: initial;\n}\n\n/* This TreeElement is always expanded and has no arrow.   */\n/* FIXME(crbug.com/475618): Implement this in TreeElement. */\n.children li::before {\n    display: none;\n}\n\n.content {\n    margin-bottom: 4px;\n}\n\n.content .stack-preview-container {\n    margin-left: 8px;\n}\n\n.content .node-list {\n    margin-left: 10px;\n}\n\n/*# sourceURL=timeline/invalidationsTree.css */";Runtime.cachedResources["timeline/timelineFlamechartPopover.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.timeline-flamechart-popover {\n    overflow: hidden;\n}\n\n.timeline-flamechart-popover span {\n    margin-right: 5px;\n}\n\n.timeline-flamechart-popover span.timeline-info-network-time {\n    color: #009;\n}\n\n.timeline-flamechart-popover span.timeline-info-time {\n    color: #282;\n}\n\n.timeline-flamechart-popover span.timeline-info-warning {\n    color: #e44;\n}\n\n.timeline-flamechart-popover span.timeline-info-warning * {\n    color: inherit;\n}\n\n/*# sourceURL=timeline/timelineFlamechartPopover.css */";Runtime.cachedResources["timeline/timelinePanel.css"]="/*\n * Copyright (C) 2006, 2007, 2008 Apple Inc.  All rights reserved.\n * Copyright (C) 2009 Anthony Ricaud <rik@webkit.org>\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1.  Redistributions of source code must retain the above copyright\n *     notice, this list of conditions and the following disclaimer.\n * 2.  Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n * 3.  Neither the name of Apple Computer, Inc. (\"Apple\") nor the names of\n *     its contributors may be used to endorse or promote products derived\n *     from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS \"AS IS\" AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY\n * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF\n * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n.panel.timeline > .toolbar {\n    border-bottom: 1px solid #dadada;\n}\n\n.timeline-settings-pane {\n    flex: none;\n    border-bottom: 1px solid #dadada;\n}\n\n#timeline-overview-panel {\n    flex: none;\n    position: relative;\n    border-bottom: 1px solid #bbb;\n}\n\n#timeline-overview-panel .timeline-graph-bar {\n    pointer-events: none;\n}\n\n#timeline-overview-grid {\n    background-color: rgb(255, 255, 255);\n}\n\n#timeline-overview-grid .timeline-grid-header {\n    height: 12px;\n}\n\n#timeline-overview-grid .resources-dividers-label-bar {\n    pointer-events: auto;\n    height: 12px;\n}\n\n#timeline-overview-grid .resources-divider-label {\n    top: 1px;\n}\n\n.timeline-details-split {\n    flex: auto;\n}\n\n.timeline-view-stack {\n    flex: auto;\n    display: flex;\n}\n\n#timeline-container .devtools-link {\n    color: inherit;\n}\n\n.timeline-graph-side.hovered {\n    background-color: rgba(0, 0, 0, 0.05) !important;\n}\n\n.timeline.panel .status-pane-container {\n    z-index: 1000;\n    display: flex;\n    align-items: center;\n    pointer-events: none;\n}\n\n.timeline.panel .status-pane-container.tinted {\n    background-color: hsla(0, 0%, 90%, 0.8);\n    pointer-events: auto;\n}\n\n.timeline.panel .status-pane-container > div {\n    pointer-events: auto;\n}\n\n#timeline-overview-panel .overview-strip {\n    margin-top: 2px;\n    justify-content: center;\n}\n\n#timeline-overview-panel .overview-strip .timeline-overview-strip-title {\n    color: #666;\n    font-size: 10px;\n    font-weight: bold;\n    z-index: 100;\n    background-color: rgba(255, 255, 255, 0.7);\n    padding: 0 4px;\n    position: absolute;\n    top: -2px;\n    right: 0;\n}\n\n#timeline-overview-cpu-activity {\n    flex-basis: 20px;\n}\n\n#timeline-overview-network {\n    flex-basis: 8px;\n}\n\n#timeline-overview-framerate {\n    flex-basis: 16px;\n    margin-top: 0 !important;\n}\n\n#timeline-overview-filmstrip {\n    flex-basis: 30px;\n}\n\n#timeline-overview-memory {\n    flex-basis: 20px;\n}\n\n#timeline-overview-framerate::before,\n#timeline-overview-network::before,\n#timeline-overview-cpu-activity::before {\n    content: \"\";\n    position: absolute;\n    left: 0;\n    right: 0;\n    bottom: 0;\n    border-bottom: 1px solid hsla(0, 0%, 0%, 0.06);\n    z-index: -200;\n}\n\n.overview-strip .background {\n    z-index: -10;\n}\n\n#timeline-overview-responsiveness {\n    flex-basis: 5px;\n    margin-top: 0 !important;\n}\n\n#timeline-overview-input {\n    flex-basis: 6px;\n}\n\n#timeline-overview-pane {\n    flex: auto;\n    position: relative;\n    overflow: hidden;\n}\n\n#timeline-overview-container {\n    display: flex;\n    flex-direction: column;\n    flex: none;\n    position: relative;\n    overflow: hidden;\n}\n\n#timeline-overview-container canvas {\n    width: 100%;\n    height: 100%;\n}\n\n#timeline-graphs {\n    position: absolute;\n    left: 0;\n    right: 0;\n    max-height: 100%;\n    top: 20px;\n}\n\n.timeline-aggregated-legend-title {\n    display: inline-block;\n}\n\n.timeline-aggregated-legend-value {\n    display: inline-block;\n    width: 70px;\n    text-align: right;\n}\n\n.timeline-aggregated-legend-swatch {\n    display: inline-block;\n    width: 11px;\n    height: 11px;\n    margin: 0 6px;\n    position: relative;\n    top: 1px;\n    border: 1px solid rgba(0, 0, 0, 0.2);\n}\n\n.popover ul {\n    margin: 0;\n    padding: 0;\n    list-style-type: none;\n}\n\n#resources-container-content {\n    overflow: hidden;\n    min-height: 100%;\n}\n\n.timeline-toolbar-resizer {\n    background-image: url(Images/toolbarResizerVertical.png);\n    background-repeat: no-repeat;\n    background-position: right center, center;\n}\n\n.memory-graph-label {\n    position: absolute;\n    right: 0;\n    bottom: 0;\n    font-size: 9px;\n    color: #888;\n    white-space: nowrap;\n    padding: 0 4px;\n    background-color: hsla(0, 0%, 100%, 0.8);\n}\n\n#memory-graphs-canvas-container {\n    overflow: hidden;\n    flex: auto;\n    position: relative;\n}\n\n#memory-counters-graph {\n    flex: auto;\n}\n\n#memory-graphs-canvas-container .memory-counter-marker {\n    position: absolute;\n    border-radius: 3px;\n    width: 5px;\n    height: 5px;\n    margin-left: -3px;\n    margin-top: -2px;\n}\n\n#memory-graphs-container .memory-counter-selector-swatches {\n    flex: 0 0 24px;\n    padding: 5px 0;\n    background-color: #eee;\n    border-bottom: 1px solid #ddd;\n}\n\n.memory-counter-selector-info {\n    flex: 0 0 auto;\n    margin-left: 5px;\n    white-space: nowrap;\n}\n\n.memory-counter-selector-info .range {\n    margin: 0 4px;\n    align-items: center;\n    display: inline-flex;\n}\n\n.memory-counter-value {\n    margin: 8px;\n}\n\n#counter-values-bar {\n    flex: 0 0 20px;\n    border-top: solid 1px lightgray;\n    width: 100%;\n    overflow: hidden;\n    line-height: 18px;\n}\n\n.timeline-filters-header {\n    overflow: hidden;\n    flex: none;\n}\n\n.timeline-details {\n    vertical-align: top;\n}\n\n.timeline-details-title {\n    border-bottom: 1px solid #B8B8B8;\n    font-weight: bold;\n    padding-bottom: 5px;\n    padding-top: 0;\n    white-space: nowrap;\n}\n\n.timeline-details-row-title {\n    font-weight: bold;\n    text-align: right;\n    white-space: nowrap;\n}\n\n.timeline-details-row-data {\n    white-space: nowrap;\n}\n\n.timeline-details-view {\n    color: #333;\n    overflow: hidden;\n}\n\n.timeline-details-view-body {\n    flex: auto;\n    overflow: auto;\n    position: relative;\n    background-color: #f3f3f3;\n    -webkit-user-select: text;\n}\n\n.timeline-details-view-body > div {\n    overflow: hidden;\n}\n\n.timeline-details-view-block {\n    flex: none;\n    display: flex;\n    background-color: white;\n    flex-direction: column;\n    padding-bottom: 5px;\n    border-bottom: 1px solid #ccc;\n}\n\n.timeline-details-view-row {\n    padding-left: 10px;\n    flex-direction: row;\n    display: flex;\n    line-height: 20px;\n}\n\n.timeline-details-view-block .timeline-details-stack-values {\n    flex-direction: column !important;\n}\n\n.timeline-details-chip-title {\n    font-size: 13px;\n    padding: 8px;\n    display: flex;\n    align-items: center;\n}\n\n.timeline-details-chip-title > div {\n    width: 12px;\n    height: 12px;\n    border: 1px solid rgba(0, 0, 0, 0.2);\n    display: inline-block;\n    margin-right: 4px;\n    content: \" \";\n}\n\n.timeline-details-view-row-title {\n    color: rgb(152, 152, 152);\n    overflow: hidden;\n}\n\n.timeline-details-warning {\n    background-color: rgba(250, 209, 209, 0.48);\n}\n\n.timeline-details-warning .timeline-details-view-row-title {\n    color: red;\n}\n\n.timeline-details-warning .timeline-details-view-row-value {\n    white-space: nowrap;\n    overflow: hidden;\n    text-overflow: ellipsis;\n}\n\n.timeline-details-view-row-value {\n    -webkit-user-select: text;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    overflow: hidden;\n    padding-left: 10px;\n}\n\n.timeline-details-view-row-value .stack-preview-container {\n    line-height: 11px;\n}\n\n.timeline-details-view-row-value .timeline-details-warning-marker {\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    overflow: hidden;\n}\n\n.timeline-details-view-pie-chart-wrapper {\n    margin: 4px 0;\n}\n\n.timeline-details-view-pie-chart {\n    margin-top: 5px;\n}\n\n.timeline-details-view-row-stack-trace {\n    padding: 4px 0;\n    line-height: inherit;\n}\n\n.timeline-details-view-row-stack-trace div {\n    white-space: nowrap;\n    text-overflow: ellipsis;\n    line-height: 12px;\n}\n\n.timeline-aggregated-info-legend > div {\n    overflow: hidden;\n    white-space: nowrap;\n    text-overflow: ellipsis;\n}\n\n.timeline-flamechart {\n    overflow: hidden;\n}\n\n.timeline-flamechart-resizer {\n    height: 8px;\n    background-color: #f3f3f3;\n    border: 1px #a3a3a3;\n    border-style: solid none;\n    display: flex;\n    flex-direction: row;\n    align-items: flex-end;\n    justify-content: center;\n}\n\n.timeline-network-resizer-disabled > .timeline-flamechart-resizer {\n    display: none;\n}\n\n.timeline-flamechart-resizer:after {\n    content: \"...\";\n    font-size: 14px;\n    margin-bottom: -1px;\n}\n\n.timeline-status-pane.full-widget-dimmed-banner {\n    text-align: left !important;\n}\n\n.timeline-layers-view > div:last-child,\n.timeline-layers-view-properties > div:last-child {\n    background-color: #eee;\n}\n\n.timeline-layers-view-properties table {\n    width: 100%;\n    border-collapse: collapse;\n}\n\n.timeline-layers-view-properties td {\n    border: 1px solid #e1e1e1;\n    line-height: 22px;\n}\n\n.timeline-paint-profiler-log-split > div:last-child {\n    background-color: #eee;\n    z-index: 0;\n}\n\n.timeline-gap {\n    flex: none;\n}\n\n.timeline-filmstrip-preview {\n    margin-top: 10px;\n    max-width: 200px;\n    max-height: 200px;\n    cursor: pointer;\n    border: 1px solid #ddd;\n}\n\n.timeline-tree-view {\n    display: flex;\n    overflow: hidden;\n}\n\n.timeline-tree-view .toolbar {\n    border-bottom: 1px solid #dadada;\n}\n\n.timeline-tree-view .data-grid {\n    border: none;\n    flex: auto;\n}\n\n.timeline-tree-view .data-grid .data-container {\n    overflow-y: scroll;\n}\n\n.timeline-tree-view .data-grid.data-grid-fits-viewport .corner {\n    display: table-cell;\n}\n\n.timeline-tree-view .data-grid table.data {\n    background: white;\n}\n\n.timeline-tree-view .data-grid tr:not(.selected) .highlight {\n    background-color: rgb(255, 230, 179);\n}\n\n.timeline-tree-view .data-grid tr:hover td:not(.bottom-filler-td) {\n    background-color: rgba(0, 0, 0, 0.1);\n}\n\n.timeline-tree-view .data-grid td.numeric-column {\n    text-align: right;\n    position: relative;\n}\n\n.timeline-tree-view .data-grid div.background-percent-bar {\n    float: right;\n}\n\n.timeline-tree-view .data-grid span.percent-column {\n    color: #888;\n    width: 45px;\n    display: inline-block;\n}\n\n.timeline-tree-view .data-grid tr.selected span {\n    color: inherit;\n}\n\n.timeline-tree-view .data-grid .name-container {\n    display: flex;\n    align-items: center;\n}\n\n.timeline-tree-view .data-grid .name-container div {\n    flex: none;\n}\n\n.timeline-tree-view .data-grid .name-container .activity-icon {\n    width: 10px;\n    height: 10px;\n    margin: 0 4px 0 2px;\n    border: 1px solid rgba(0, 0, 0, 0.05);\n}\n\n.timeline-tree-view .data-grid .name-container .activity-warning::after {\n    content: \"[deopt]\";\n    margin: 0 4px;\n    line-height: 12px;\n    font-size: 10px;\n    color: #777;\n}\n\n.timeline-tree-view .data-grid tr.selected .name-container .activity-warning::after {\n    color: white;\n}\n\n.timeline-tree-view .data-grid .name-container .activity-link {\n    flex: auto;\n    text-align: right;\n    overflow: hidden;\n    text-overflow: ellipsis;\n    margin-left: 5px;\n}\n\n.timeline-tree-view .data-grid .background-bar-container {\n    position: absolute;\n    left: 3px;\n    right: 0;\n}\n\n.timeline-tree-view .data-grid .background-bar {\n    float: right;\n    height: 18px;\n    background-color: hsla(43, 84%, 64%, 0.2);\n    border-bottom: 1px solid hsl(43, 84%, 64%);\n}\n\n.timeline-tree-view .data-grid .selected .background-bar {\n    background-color: rgba(255, 255, 255, 0.3);\n    border-bottom-color: rgba(255, 255, 255, 0.9);\n}\n\n.timeline-tree-view .timeline-details-view-body .full-widget-dimmed-banner {\n    background-color: inherit;\n}\n\n.timeline-details .filter-input-field {\n    width: 120px;\n}\n\n.timeline-tree-view .data-grid .header-container {\n    height: 21px;\n}\n\n.timeline-tree-view .data-grid .data-container {\n    top: 21px;\n}\n\n.timeline-stack-view-header {\n    height: 26px;\n    background-color: white;\n    padding: 6px 10px;\n    color: #5a5a5a;\n    white-space: nowrap;\n}\n\n.timeline-landing-page {\n    position: absolute;\n    background-color: white;\n    justify-content: center;\n    align-items: center;\n    overflow: auto;\n    font-size: 13px;\n    line-height: 15px;\n    color: #777;\n}\n\n.timeline-landing-page > div {\n    max-width: 450px;\n    margin: 10px;\n}\n\n.timeline-landing-page > div > p {\n    flex: none;\n    white-space: pre-line;\n}\n\n.timeline-landing-page button {\n    padding: 0;\n    vertical-align: sub;\n    border: 1px solid #ddd;\n    margin-top: 4px;\n    background-color: #f3f3f3;\n}\n\n.timeline-landing-page button > span {\n    margin: -1px 2px -3px -2px;\n}\n\n.timeline-landing-page button > span:hover {\n    background-color: #333;\n}\n\n.timeline-landing-warning {\n    background-color: #fffde7;\n    padding: 16px 20px;\n    margin-top: 40px;\n    box-shadow: 1px 1px 3px rgba(0,0,0,0.2);\n}\n\n.timeline-landing-warning-close {\n    float: right;\n    margin-top: -10px;\n    margin-right: -13px;\n}\n\n.timeline-landing-warning span[is=ui-icon] {\n    margin: -8px;\n}\n\n/*# sourceURL=timeline/timelinePanel.css */";Runtime.cachedResources["timeline/timelinePaintProfiler.css"]="/*\n * Copyright 2016 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.paint-profiler-image-view {\n    overflow: hidden;\n}\n\n.paint-profiler-image-view .paint-profiler-image-container {\n    -webkit-transform-origin: 0 0;\n}\n\n.paint-profiler-image-view .paint-profiler-image-container div {\n    border-color: rgba(100, 100, 100, 0.4);\n    border-style: solid;\n    z-index: 100;\n    position: absolute;\n    top: 0;\n    left: 0;\n}\n\n.paint-profiler-image-view img {\n    border: solid 1px black;\n}\n\n/*# sourceURL=timeline/timelinePaintProfiler.css */";Runtime.cachedResources["timeline/timelineStatusDialog.css"]="/*\n * Copyright (c) 2015 The Chromium Authors. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n */\n\n.timeline-status-dialog {\n    display: flex;\n    flex-direction: column;\n    padding: 12px 16px;\n    align-self: center;\n    background-color: white;\n    box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.2),\n                0 2px 4px rgba(0, 0, 0, 0.2),\n                0 2px 6px rgba(0, 0, 0, 0.1);\n    margin-top: -1px;\n}\n\n.status-dialog-line {\n    margin: 2px;\n    height: 14px;\n    display: flex;\n    align-items: baseline;\n}\n\n.status-dialog-line .label {\n    display: inline-block;\n    width: 80px;\n    text-align: right;\n    color: #aaa;\n    margin-right: 10px;\n}\n\n.timeline-status-dialog .progress .indicator-container {\n    display: inline-block;\n    width: 200px;\n    height: 8px;\n    background-color: #f4f4f4;\n    display: inline-block;\n    margin: 0 10px 0 0;\n}\n\n.timeline-status-dialog .progress .indicator {\n    background-color: rgb(112, 166, 255);\n    height: 100%;\n    width: 0;\n    margin: 0;\n}\n\n.timeline-status-dialog .stop-button {\n    margin-top: 8px;\n    height: 100%;\n    align-self: center;\n}\n\n/*# sourceURL=timeline/timelineStatusDialog.css */";