import{UIString,Console,Settings,ParsedURL,ObjectWrapper,Color,EventTarget,Linkifier as Linkifier$1}from'../common/common.js';import{TimelineOverviewPane,FlameChart,NetworkPriorities,LineLevelProfile,PieChart,FilmStripView,TimelineGrid}from'../perf_ui/perf_ui.js';import{NumberUtilities,StringUtilities}from'../platform/platform.js';import{TimelineJSProfile,TimelineModel,TimelineModelFilter,TimelineProfileTree,TimelineIRModel,TimelineFrameModel}from'../timeline_model/timeline_model.js';import{UIUtils,Widget,SplitWidget,Toolbar,ARIAUtils,Geometry,TabbedPane,Fragment,Utils,GlassPane,ListModel,ListControl,Icon,Action,Panel,DropTarget,SearchableView,ContextMenu,ViewManager,XLink,TreeOutline}from'../ui/ui.js';import{TempFile,FileUtils,BlackboxManager,ResourceUtils,DebuggerWorkspaceBinding}from'../bindings/bindings.js';import{TracingModel,TracingManager,SDKModel,CPUProfilerModel,RuntimeModel,PaintProfiler,OverlayModel,DOMModel,ResourceTreeModel,NetworkManager,DebuggerModel,FilmStripModel}from'../sdk/sdk.js';import{Linkifier,ImagePreview,JSPresentationUtils}from'../components/components.js';import{ExtensionServer}from'../extensions/extensions.js';import{ResourceLoader,Platform as Platform$1,userMetrics,UserMetrics}from'../host/host.js';import{ThrottlingManager}from'../mobile_throttling/mobile_throttling.js';import{InspectorBackend}from'../protocol_client/protocol_client.js';import{TextUtils}from'../text_utils/text_utils.js';import{CoverageModel}from'../coverage/coverage.js';import{SortableDataGrid,DataGrid,ViewportDataGrid}from'../data_grid/data_grid.js';import{LayerViewHost,LayerTreeOutline,Layers3DView,LayerDetailsView,PaintProfilerView,TransformController}from'../layer_viewer/layer_viewer.js';class TimelineLoader{constructor(client){this._client=client;this._backingStorage=new TempFile.TempFileBackingStorage();this._tracingModel=new TracingModel.TracingModel(this._backingStorage);this._canceledCallback=null;this._state=State.Initial;this._buffer='';this._firstRawChunk=true;this._firstChunk=true;this._loadedBytes=0;this._totalSize;this._jsonTokenizer=new TextUtils.BalancedJSONTokenizer(this._writeBalancedJSON.bind(this),true);}
static loadFromFile(file,client){const loader=new TimelineLoader(client);const fileReader=new FileUtils.ChunkedFileReader(file,TransferChunkLengthBytes);loader._canceledCallback=fileReader.cancel.bind(fileReader);loader._totalSize=file.size;fileReader.read(loader).then(success=>{if(!success){loader._reportErrorAndCancelLoading(fileReader.error().message);}});return loader;}
static loadFromEvents(events,client){const loader=new TimelineLoader(client);setTimeout(async()=>{const eventsPerChunk=5000;client.loadingStarted();for(let i=0;i<events.length;i+=eventsPerChunk){const chunk=events.slice(i,i+eventsPerChunk);loader._tracingModel.addEvents(chunk);client.loadingProgress((i+chunk.length)/events.length);await new Promise(r=>setTimeout(r));}
loader.close();});return loader;}
static loadFromURL(url,client){const loader=new TimelineLoader(client);ResourceLoader.loadAsStream(url,null,loader);return loader;}
cancel(){this._tracingModel=null;this._backingStorage.reset();this._client.loadingComplete(null);this._client=null;if(this._canceledCallback){this._canceledCallback();}}
write(chunk){if(!this._client){return Promise.resolve();}
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===State.Initial){if(chunk.startsWith('{"nodes":[')){this._state=State.LoadingCPUProfileFormat;}else if(chunk[0]==='{'){this._state=State.LookingForEvents;}else if(chunk[0]==='['){this._state=State.ReadingEvents;}else{this._reportErrorAndCancelLoading(UIString.UIString('Malformed timeline data: Unknown JSON format'));return Promise.resolve();}}
if(this._state===State.LoadingCPUProfileFormat){this._buffer+=chunk;return Promise.resolve();}
if(this._state===State.LookingForEvents){const objectName='"traceEvents":';const startPos=this._buffer.length-objectName.length;this._buffer+=chunk;const pos=this._buffer.indexOf(objectName,startPos);if(pos===-1){return Promise.resolve();}
chunk=this._buffer.slice(pos+objectName.length);this._state=State.ReadingEvents;}
if(this._state!==State.ReadingEvents){return Promise.resolve();}
if(this._jsonTokenizer.write(chunk)){return Promise.resolve();}
this._state=State.SkippingTail;if(this._firstChunk){this._reportErrorAndCancelLoading(UIString.UIString('Malformed timeline input, wrong JSON brackets balance'));}
return Promise.resolve();}
_writeBalancedJSON(data){let json=data+']';if(!this._firstChunk){const commaIndex=json.indexOf(',');if(commaIndex!==-1){json=json.slice(commaIndex+1);}
json='['+json;}
let items;try{items=(JSON.parse(json));}catch(e){this._reportErrorAndCancelLoading(UIString.UIString('Malformed timeline data: %s',e.toString()));return;}
if(this._firstChunk){this._firstChunk=false;if(this._looksLikeAppVersion(items[0])){this._reportErrorAndCancelLoading(UIString.UIString('Legacy Timeline format is not supported.'));return;}}
try{this._tracingModel.addEvents(items);}catch(e){this._reportErrorAndCancelLoading(UIString.UIString('Malformed timeline data: %s',e.toString()));}}
_reportErrorAndCancelLoading(message){if(message){Console.Console.instance().error(message);}
this.cancel();}
_looksLikeAppVersion(item){return typeof item==='string'&&item.indexOf('Chrome')!==-1;}
async close(){if(!this._client){return;}
this._client.processingStarted();setTimeout(()=>this._finalizeTrace(),0);}
_finalizeTrace(){if(this._state===State.LoadingCPUProfileFormat){this._parseCPUProfileFormat(this._buffer);this._buffer='';}
this._tracingModel.tracingComplete();this._client.loadingComplete(this._tracingModel);}
_parseCPUProfileFormat(text){let traceEvents;try{const profile=JSON.parse(text);traceEvents=TimelineJSProfile.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile(profile,1,true);}catch(e){this._reportErrorAndCancelLoading(UIString.UIString('Malformed CPU profile format'));return;}
this._tracingModel.addEvents(traceEvents);}}
const TransferChunkLengthBytes=5000000;class Client{loadingStarted(){}
loadingProgress(progress){}
processingStarted(){}
loadingComplete(tracingModel){}}
const State={Initial:Symbol('Initial'),LookingForEvents:Symbol('LookingForEvents'),ReadingEvents:Symbol('ReadingEvents'),SkippingTail:Symbol('SkippingTail'),LoadingCPUProfileFormat:Symbol('LoadingCPUProfileFormat')};var TimelineLoader$1=Object.freeze({__proto__:null,TimelineLoader:TimelineLoader,TransferChunkLengthBytes:TransferChunkLengthBytes,Client:Client,State:State});class ExtensionTracingSession{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){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;TimelineLoader.loadFromURL(url,this);}
start(){this._provider.start(this);}
stop(){this._provider.stop();return this._completionPromise;}}
var ExtensionTracingSession$1=Object.freeze({__proto__:null,ExtensionTracingSession:ExtensionTracingSession});class TimelineController{constructor(target,client){this._target=target;this._tracingManager=target.model(TracingManager.TracingManager);this._performanceModel=new PerformanceModel();this._performanceModel.setMainTarget(target);this._client=client;const backingStorage=new TempFile.TempFileBackingStorage();this._tracingModel=new TracingModel.TracingModel(backingStorage);this._extensionSessions=[];SDKModel.TargetManager.instance().observeModels(CPUProfilerModel.CPUProfilerModel,this);}
dispose(){SDKModel.TargetManager.instance().unobserveModels(CPUProfilerModel.CPUProfilerModel,this);}
mainTarget(){return this._target;}
async startRecording(options,providers){this._extensionTraceProviders=self.Extensions.extensionServer.traceProviders().slice();function disabledByDefault(category){return'disabled-by-default-'+category;}
const categoriesArray=['-*','devtools.timeline',disabledByDefault('devtools.timeline'),disabledByDefault('devtools.timeline.frame'),'v8.execute',TimelineModel.TimelineModelImpl.Category.Console,TimelineModel.TimelineModelImpl.Category.UserTiming,TimelineModel.TimelineModelImpl.Category.Loading,];categoriesArray.push(TimelineModel.TimelineModelImpl.Category.LatencyInfo);if(Root.Runtime.experiments.isEnabled('timelineFlowEvents')){categoriesArray.push('devtools.timeline.async');}
if(Root.Runtime.experiments.isEnabled('timelineV8RuntimeCallStats')&&options.enableJSSampling){categoriesArray.push(disabledByDefault('v8.runtime_stats_sampling'));}
if(!Root.Runtime.queryParam('timelineTracingJSProfileDisabled')&&options.enableJSSampling){categoriesArray.push(disabledByDefault('v8.cpu_profiler'));if(Settings.Settings.instance().moduleSetting('highResolutionCpuProfiling').get()){categoriesArray.push(disabledByDefault('v8.cpu_profiler.hires'));}}
categoriesArray.push(disabledByDefault('devtools.timeline.stack'));if(Root.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 ExtensionTracingSession(provider,this._performanceModel));this._extensionSessions.forEach(session=>session.start());this._performanceModel.setRecordStartTime(Date.now());const response=await this._startRecordingWithCategories(categoriesArray.join(','),options.enableJSSampling);if(response[InspectorBackend.ProtocolError]){await this._waitForTracingToStop(false);await SDKModel.TargetManager.instance().resumeAllTargets();}
return response;}
async stopRecording(){if(this._tracingManager){this._tracingManager.stop();}
this._client.loadingStarted();await this._waitForTracingToStop(true);this._allSourcesFinished();return this._performanceModel;}
_waitForTracingToStop(awaitTracingCompleteCallback){const tracingStoppedPromises=[];if(this._tracingManager&&awaitTracingCompleteCallback){tracingStoppedPromises.push(new Promise(resolve=>this._tracingCompleteCallback=resolve));}
tracingStoppedPromises.push(this._stopProfilingOnAllModels());const extensionCompletionPromises=this._extensionSessions.map(session=>session.stop());if(extensionCompletionPromises.length){tracingStoppedPromises.push(Promise.race([Promise.all(extensionCompletionPromises),new Promise(r=>setTimeout(r,5000))]));}
return Promise.all(tracingStoppedPromises);}
modelAdded(cpuProfilerModel){if(this._profiling){cpuProfilerModel.startRecording();}}
modelRemoved(cpuProfilerModel){}
_startProfilingOnAllModels(){this._profiling=true;const models=SDKModel.TargetManager.instance().models(CPUProfilerModel.CPUProfilerModel);return Promise.all(models.map(model=>model.startRecording()));}
_addCpuProfile(targetId,cpuProfile){if(!cpuProfile){Console.Console.instance().warn(UIString.UIString('CPU profile for a target is not available.'));return;}
if(!this._cpuProfiles){this._cpuProfiles=new Map();}
this._cpuProfiles.set(targetId,cpuProfile);}
_stopProfilingOnAllModels(){const models=this._profiling?SDKModel.TargetManager.instance().models(CPUProfilerModel.CPUProfilerModel):[];this._profiling=false;const promises=[];for(const model of models){const targetId=model.target().id();const modelPromise=model.stopRecording().then(this._addCpuProfile.bind(this,targetId));promises.push(modelPromise);}
return Promise.all(promises);}
async _startRecordingWithCategories(categories,enableJSSampling){await SDKModel.TargetManager.instance().suspendAllTargets('performance-timeline');if(enableJSSampling&&Root.Runtime.queryParam('timelineTracingJSProfileDisabled')){await this._startProfilingOnAllModels();}
if(!this._tracingManager){return;}
const samplingFrequencyHz=Settings.Settings.instance().moduleSetting('highResolutionCpuProfiling').get()?10000:1000;const options='sampling-frequency='+samplingFrequencyHz;return 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);}
async _finalizeTrace(){this._injectCpuProfileEvents();await SDKModel.TargetManager.instance().resumeAllTargets();this._tracingModel.tracingComplete();this._client.loadingComplete(this._tracingModel);}
_injectCpuProfileEvent(pid,tid,cpuProfile){if(!cpuProfile){return;}
const cpuProfileEvent=({cat:TracingModel.DevToolsMetadataEventCategory,ph:TracingModel.Phase.Instant,ts:this._tracingModel.maximumRecordTime()*1000,pid:pid,tid:tid,name:TimelineModel.RecordType.CpuProfile,args:{data:{cpuProfile:cpuProfile}}});this._tracingModel.addEvents([cpuProfileEvent]);}
_buildTargetToProcessIdMap(){const metadataEventTypes=TimelineModel.TimelineModelImpl.DevToolsMetadataEvent;const metadataEvents=this._tracingModel.devToolsMetadataEvents();const browserMetaEvent=metadataEvents.find(e=>e.name===metadataEventTypes.TracingStartedInBrowser);if(!browserMetaEvent){return null;}
const pseudoPidToFrames=new Platform.Multimap();const targetIdToPid=new Map();const frames=browserMetaEvent.args.data['frames'];for(const frameInfo of frames){targetIdToPid.set(frameInfo.frame,frameInfo.processId);}
for(const event of metadataEvents){const data=event.args.data;switch(event.name){case metadataEventTypes.FrameCommittedInBrowser:if(data.processId){targetIdToPid.set(data.frame,data.processId);}else{pseudoPidToFrames.set(data.processPseudoId,data.frame);}
break;case metadataEventTypes.ProcessReadyInBrowser:for(const frame of pseudoPidToFrames.get(data.processPseudoId)||[]){targetIdToPid.set(frame,data.processId);}
break;}}
const mainFrame=frames.find(frame=>!frame.parent);const mainRendererProcessId=mainFrame.processId;const mainProcess=this._tracingModel.processById(mainRendererProcessId);if(mainProcess){targetIdToPid.set(SDKModel.TargetManager.instance().mainTarget().id(),mainProcess.id());}
return targetIdToPid;}
_injectCpuProfileEvents(){if(!this._cpuProfiles){return;}
const metadataEventTypes=TimelineModel.TimelineModelImpl.DevToolsMetadataEvent;const metadataEvents=this._tracingModel.devToolsMetadataEvents();const targetIdToPid=this._buildTargetToProcessIdMap();if(targetIdToPid){for(const[id,profile]of this._cpuProfiles){const pid=targetIdToPid.get(id);if(!pid){continue;}
const process=this._tracingModel.processById(pid);const thread=process&&process.threadByName(TimelineModel.TimelineModelImpl.RendererMainThreadName);if(thread){this._injectCpuProfileEvent(pid,thread.id(),profile);}}}else{const mainMetaEvent=metadataEvents.filter(event=>event.name===metadataEventTypes.TracingStartedInPage).peekLast();if(mainMetaEvent){const pid=mainMetaEvent.thread.process().id();const mainCpuProfile=this._cpuProfiles.get(this._tracingManager.target().id());this._injectCpuProfileEvent(pid,mainMetaEvent.thread.id(),mainCpuProfile);}else{let tid=0;for(const pair of this._cpuProfiles){const target=SDKModel.TargetManager.instance().targetById(pair[0]);const name=target&&target.name();this._tracingModel.addEvents(TimelineJSProfile.TimelineJSProfileProcessor.buildTraceProfileFromCpuProfile(pair[1],++tid,tid===1,name));}}}
const workerMetaEvents=metadataEvents.filter(event=>event.name===metadataEventTypes.TracingSessionIdForWorker);for(const metaEvent of workerMetaEvents){const workerId=metaEvent.args['data']['workerId'];const 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);}}
class Client$1{recordingProgress(usage){}}
let RecordingOptions;var TimelineController$1=Object.freeze({__proto__:null,TimelineController:TimelineController,Client:Client$1,RecordingOptions:RecordingOptions});class TimelineEventOverview extends TimelineOverviewPane.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){const x=begin;const width=end-begin;const ctx=this.context();ctx.fillStyle=color;ctx.fillRect(x,position,width,height);}}
class TimelineEventOverviewInput extends TimelineEventOverview{constructor(){super('input',null);}
update(){super.update();if(!this._model){return;}
const height=this.height();const descriptors=TimelineUIUtils.eventDispatchDesciptors();const descriptorsByType=new Map();let maxPriority=-1;for(const descriptor of descriptors){for(const type of descriptor.eventTypes){descriptorsByType.set(type,descriptor);}
maxPriority=Math.max(maxPriority,descriptor.priority);}
const minWidth=2*window.devicePixelRatio;const timeOffset=this._model.timelineModel().minimumRecordTime();const timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;const canvasWidth=this.width();const scale=canvasWidth/timeSpan;for(let priority=0;priority<=maxPriority;++priority){for(const track of this._model.timelineModel().tracks()){for(let i=0;i<track.events.length;++i){const event=track.events[i];if(event.name!==TimelineModel.RecordType.EventDispatch){continue;}
const descriptor=descriptorsByType.get(event.args['data']['type']);if(!descriptor||descriptor.priority!==priority){continue;}
const start=NumberUtilities.clamp(Math.floor((event.startTime-timeOffset)*scale),0,canvasWidth);const end=NumberUtilities.clamp(Math.ceil((event.endTime-timeOffset)*scale),0,canvasWidth);const width=Math.max(end-start,minWidth);this._renderBar(start,start+width,0,height,descriptor.color);}}}}}
class TimelineEventOverviewNetwork extends TimelineEventOverview{constructor(){super('network',UIString.UIString('NET'));}
update(){super.update();if(!this._model){return;}
const timelineModel=this._model.timelineModel();const bandHeight=this.height()/2;const timeOffset=timelineModel.minimumRecordTime();const timeSpan=timelineModel.maximumRecordTime()-timeOffset;const canvasWidth=this.width();const scale=canvasWidth/timeSpan;const highPath=new Path2D();const lowPath=new Path2D();const priorities=Protocol.Network.ResourcePriority;const highPrioritySet=new Set([priorities.VeryHigh,priorities.High,priorities.Medium]);for(const request of timelineModel.networkRequests()){const path=highPrioritySet.has(request.priority)?highPath:lowPath;const s=Math.max(Math.floor((request.startTime-timeOffset)*scale),0);const e=Math.min(Math.ceil((request.endTime-timeOffset)*scale+1),canvasWidth);path.rect(s,0,e-s,bandHeight-1);}
const 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();}}
class TimelineEventOverviewCPUActivity extends TimelineEventOverview{constructor(){super('cpu-activity',UIString.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;}
const timelineModel=this._model.timelineModel();const quantSizePx=4*window.devicePixelRatio;const width=this.width();const height=this.height();const baseLine=height;const timeOffset=timelineModel.minimumRecordTime();const timeSpan=timelineModel.maximumRecordTime()-timeOffset;const scale=width/timeSpan;const quantTime=quantSizePx/scale;const categories=TimelineUIUtils.categories();const categoryOrder=TimelineUIUtils.getTimelineMainEventCategories();const otherIndex=categoryOrder.indexOf('other');const idleIndex=0;console.assert(idleIndex===categoryOrder.indexOf('idle'));for(let i=idleIndex+1;i<categoryOrder.length;++i){categories[categoryOrder[i]]._overviewIndex=i;}
const backgroundContext=this._backgroundCanvas.getContext('2d');for(const track of timelineModel.tracks()){if(track.type===TimelineModel.TrackType.MainThread&&track.forMainFrame){drawThreadEvents(this.context(),track.events);}else{drawThreadEvents(backgroundContext,track.events);}}
applyPattern(backgroundContext);function drawThreadEvents(ctx,events){const quantizer=new Quantizer(timeOffset,quantTime,drawSample);let x=0;const categoryIndexStack=[];const paths=[];const lastY=[];for(let i=0;i<categoryOrder.length;++i){paths[i]=new Path2D();paths[i].moveTo(0,height);lastY[i]=height;}
function drawSample(counters){let y=baseLine;for(let i=idleIndex+1;i<categoryOrder.length;++i){const 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){const index=categoryIndexStack.length?categoryIndexStack.peekLast():idleIndex;quantizer.appendInterval(e.startTime,index);categoryIndexStack.push(TimelineUIUtils.eventStyle(e).category._overviewIndex||otherIndex);}
function onEventEnd(e){quantizer.appendInterval(e.endTime,categoryIndexStack.pop());}
TimelineModel.TimelineModelImpl.forEachEvent(events,onEventStart,onEventEnd);quantizer.appendInterval(timeOffset+timeSpan+quantTime,idleIndex);for(let 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){const step=4*window.devicePixelRatio;ctx.save();ctx.lineWidth=step/Math.sqrt(8);for(let 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();}}}
class TimelineEventOverviewResponsiveness extends TimelineEventOverview{constructor(){super('responsiveness',null);}
update(){super.update();if(!this._model){return;}
const height=this.height();const timeOffset=this._model.timelineModel().minimumRecordTime();const timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;const scale=this.width()/timeSpan;const frames=this._model.frames();const ctx=(this.context());const fillPath=new Path2D();const markersPath=new Path2D();for(let i=0;i<frames.length;++i){const frame=frames[i];if(!frame.hasWarnings()){continue;}
paintWarningDecoration(frame.startTime,frame.duration);}
for(const track of this._model.timelineModel().tracks()){const events=track.events;for(let 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){const x=Math.round(scale*(time-timeOffset));const w=Math.round(scale*duration);fillPath.rect(x,0,w,height);markersPath.moveTo(x+w,0);markersPath.lineTo(x+w,height);}}}
class TimelineFilmStripOverview extends TimelineEventOverview{constructor(){super('filmstrip',null);this.reset();}
update(){super.update();const frames=this._model?this._model.filmStripModel().frames():[];if(!frames.length){return;}
const drawGeneration=Symbol('drawGeneration');this._drawGeneration=drawGeneration;this._imageByFrame(frames[0]).then(image=>{if(this._drawGeneration!==drawGeneration){return;}
if(!image||!image.naturalWidth||!image.naturalHeight){return;}
const imageHeight=this.height()-2*TimelineFilmStripOverview.Padding;const imageWidth=Math.ceil(imageHeight*image.naturalWidth/image.naturalHeight);const popoverScale=Math.min(200/image.naturalWidth,1);this._emptyImage=new Image(image.naturalWidth*popoverScale,image.naturalHeight*popoverScale);this._drawFrames(imageWidth,imageHeight);});}
_imageByFrame(frame){let imagePromise=this._frameToImagePromise.get(frame);if(!imagePromise){imagePromise=frame.imageDataPromise().then(data=>UIUtils.loadImageFromData(data));this._frameToImagePromise.set(frame,imagePromise);}
return imagePromise;}
_drawFrames(imageWidth,imageHeight){if(!imageWidth||!this._model){return;}
const filmStripModel=this._model.filmStripModel();if(!filmStripModel.frames().length){return;}
const padding=TimelineFilmStripOverview.Padding;const width=this.width();const zeroTime=filmStripModel.zeroTime();const spanTime=filmStripModel.spanTime();const scale=spanTime/width;const context=this.context();const drawGeneration=this._drawGeneration;context.beginPath();for(let x=padding;x<width;x+=imageWidth+2*padding){const time=zeroTime+(x+imageWidth/2)*scale;const 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||!image){return;}
context.drawImage(image,x,1,imageWidth,imageHeight);}}
overviewInfoPromise(x){if(!this._model||!this._model.filmStripModel().frames().length){return Promise.resolve((null));}
const time=this.calculator().positionToTime(x);const frame=this._model.filmStripModel().frameByTimestamp(time);if(frame===this._lastFrame){return Promise.resolve(this._lastElement);}
const imagePromise=frame?this._imageByFrame(frame):Promise.resolve(this._emptyImage);return imagePromise.then(createFrameElement.bind(this));function createFrameElement(image){const element=createElementWithClass('div','frame');if(image){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;}}
TimelineFilmStripOverview.Padding=2;class TimelineEventOverviewFrames extends TimelineEventOverview{constructor(){super('framerate',UIString.UIString('FPS'));}
update(){super.update();if(!this._model){return;}
const frames=this._model.frames();if(!frames.length){return;}
const height=this.height();const padding=1*window.devicePixelRatio;const baseFrameDurationMs=1e3/60;const visualHeight=height-2*padding;const timeOffset=this._model.timelineModel().minimumRecordTime();const timeSpan=this._model.timelineModel().maximumRecordTime()-timeOffset;const scale=this.width()/timeSpan;const baseY=height-padding;const ctx=this.context();const bottomY=baseY+10*window.devicePixelRatio;let x=0;let y=bottomY;const lineWidth=window.devicePixelRatio;const offset=lineWidth&1?0.5:0;const tickDepth=1.5*window.devicePixelRatio;ctx.beginPath();ctx.moveTo(0,y);for(let i=0;i<frames.length;++i){const 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);}
const 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();}}
class TimelineEventOverviewMemory extends TimelineEventOverview{constructor(){super('memory',UIString.UIString('HEAP'));this._heapSizeLabel=this.element.createChild('div','memory-graph-label');}
resetHeapSizeLabels(){this._heapSizeLabel.textContent='';}
update(){super.update();const ratio=window.devicePixelRatio;if(!this._model){this.resetHeapSizeLabels();return;}
const tracks=this._model.timelineModel().tracks().filter(track=>track.type===TimelineModel.TrackType.MainThread&&track.forMainFrame);const trackEvents=tracks.map(track=>track.events);const lowerOffset=3*ratio;let maxUsedHeapSize=0;let minUsedHeapSize=100000000000;const minTime=this._model.timelineModel().minimumRecordTime();const maxTime=this._model.timelineModel().maximumRecordTime();function isUpdateCountersEvent(event){return event.name===TimelineModel.RecordType.UpdateCounters;}
for(let i=0;i<trackEvents.length;i++){trackEvents[i]=trackEvents[i].filter(isUpdateCountersEvent);}
function calculateMinMaxSizes(event){const counters=event.args.data;if(!counters||!counters.jsHeapSizeUsed){return;}
maxUsedHeapSize=Math.max(maxUsedHeapSize,counters.jsHeapSizeUsed);minUsedHeapSize=Math.min(minUsedHeapSize,counters.jsHeapSizeUsed);}
for(let i=0;i<trackEvents.length;i++){trackEvents[i].forEach(calculateMinMaxSizes);}
minUsedHeapSize=Math.min(minUsedHeapSize,maxUsedHeapSize);const lineWidth=1;const width=this.width();const height=this.height()-lowerOffset;const xFactor=width/(maxTime-minTime);const yFactor=(height-lineWidth)/Math.max(maxUsedHeapSize-minUsedHeapSize,1);const histogram=new Array(width);function buildHistogram(event){const counters=event.args.data;if(!counters||!counters.jsHeapSizeUsed){return;}
const x=Math.round((event.startTime-minTime)*xFactor);const y=Math.round((counters.jsHeapSizeUsed-minUsedHeapSize)*yFactor);histogram[x]=Math.max(histogram[x]||0,y);}
for(let i=0;i<trackEvents.length;i++){trackEvents[i].forEach(buildHistogram);}
const ctx=this.context();const heightBeyondView=height+lowerOffset+lineWidth;ctx.translate(0.5,0.5);ctx.beginPath();ctx.moveTo(-lineWidth,heightBeyondView);let y=0;let isFirstPoint=true;let lastX=0;for(let x=0;x<histogram.length;x++){if(typeof histogram[x]==='undefined'){continue;}
if(isFirstPoint){isFirstPoint=false;y=histogram[x];ctx.lineTo(-lineWidth,height-y);}
const 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=UIString.UIString('%s \u2013 %s',Number.bytesToString(minUsedHeapSize),Number.bytesToString(maxUsedHeapSize));}}
class Quantizer{constructor(startTime,quantDuration,callback){this._lastTime=startTime;this._quantDuration=quantDuration;this._callback=callback;this._counters=[];this._remainder=quantDuration;}
appendInterval(time,group){let 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){const 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;}}
class TimelineEventOverviewCoverage extends TimelineEventOverview{constructor(){super('coverage',UIString.UIString('COVERAGE'));this._heapSizeLabel=this.element.createChild('div','timeline-overview-coverage-label');}
resetHeapSizeLabels(){this._heapSizeLabel.textContent='';}
setModel(model){super.setModel(model);if(this._model){this._coverageModel=model.mainTarget().model(CoverageModel.CoverageModel);}}
update(){super.update();const ratio=window.devicePixelRatio;if(!this._coverageModel){return;}
let total=0;let total_used=0;const usedByTimestamp=new Map();const totalByTimestamp=new Map();for(const urlInfo of this._coverageModel.entries()){for(const info of urlInfo.entries()){total+=info.size();for(const[stamp,used]of info.usedByTimestamp()){total_used+=used;if(!totalByTimestamp.has(stamp)){totalByTimestamp.set(stamp,new Set());}
totalByTimestamp.get(stamp).add(info);if(!usedByTimestamp.has(stamp)){usedByTimestamp.set(stamp,used);}else{usedByTimestamp.set(stamp,usedByTimestamp.get(stamp)+used);}}}}
const seen=new Set();const coverageByTimestamp=new Map();let sumTotal=0,sumUsed=0;const sortedByTimestamp=Array.from(totalByTimestamp.entries()).sort((a,b)=>a[0]-b[0]);for(const[stamp,infos]of sortedByTimestamp){for(const info of infos.values()){if(seen.has(info)){continue;}
seen.add(info);sumTotal+=info.size();}
sumUsed+=usedByTimestamp.get(stamp);coverageByTimestamp.set(stamp,sumUsed/sumTotal);}
const percentUsed=total?Math.round(100*total_used/total):0;const lowerOffset=3*ratio;const millisecondsPerSecond=1000;const minTime=this._model.timelineModel().minimumRecordTime()/millisecondsPerSecond;const maxTime=this._model.timelineModel().maximumRecordTime()/millisecondsPerSecond;const lineWidth=1;const width=this.width();const height=this.height()-lowerOffset;const xFactor=width/(maxTime-minTime);const yFactor=height-lineWidth;let yOffset=0;const ctx=this.context();const heightBeyondView=height+lowerOffset+lineWidth;ctx.translate(0.5,0.5);ctx.beginPath();ctx.moveTo(-lineWidth,heightBeyondView);ctx.lineTo(-lineWidth,height-yOffset);let previous=null;for(const stamp of this._coverageModel.coverageUpdateTimes()){const coverage=coverageByTimestamp.get(stamp)||previous;previous=coverage;if(!coverage){continue;}
if(stamp>maxTime){break;}
const x=(stamp-minTime)*xFactor;yOffset=coverage*yFactor;ctx.lineTo(x,height-yOffset);}
const white='hsl(0, 100%, 100%)';const blue='hsl(220, 90%, 70%)';const transparentBlue='hsla(220, 90%, 70%, 0.2)';ctx.lineTo(width+lineWidth,height-yOffset);ctx.lineTo(width+lineWidth,heightBeyondView);ctx.closePath();ctx.fillStyle=transparentBlue;ctx.fill();ctx.lineWidth=lineWidth;ctx.strokeStyle=blue;ctx.stroke();previous=null;for(const stamp of this._coverageModel.coverageUpdateTimes()){const coverage=coverageByTimestamp.get(stamp)||previous;previous=coverage;if(!coverage){continue;}
ctx.beginPath();const x=(stamp-minTime)*xFactor;const y=height-coverage*yFactor;ctx.arc(x,y,2*lineWidth,0,2*Math.PI,false);ctx.closePath();ctx.stroke();ctx.fillStyle=coverageByTimestamp.has(stamp)?blue:white;ctx.fill();}
this._heapSizeLabel.textContent=`${percentUsed}% used`;}}
var TimelineEventOverview$1=Object.freeze({__proto__:null,TimelineEventOverview:TimelineEventOverview,TimelineEventOverviewInput:TimelineEventOverviewInput,TimelineEventOverviewNetwork:TimelineEventOverviewNetwork,TimelineEventOverviewCPUActivity:TimelineEventOverviewCPUActivity,TimelineEventOverviewResponsiveness:TimelineEventOverviewResponsiveness,TimelineFilmStripOverview:TimelineFilmStripOverview,TimelineEventOverviewFrames:TimelineEventOverviewFrames,TimelineEventOverviewMemory:TimelineEventOverviewMemory,Quantizer:Quantizer,TimelineEventOverviewCoverage:TimelineEventOverviewCoverage});class IsLong extends TimelineModelFilter.TimelineModelFilter{constructor(){super();this._minimumRecordDuration=0;}
setMinimumRecordDuration(value){this._minimumRecordDuration=value;}
accept(event){const duration=event.endTime?event.endTime-event.startTime:0;return duration>=this._minimumRecordDuration;}}
class Category extends TimelineModelFilter.TimelineModelFilter{constructor(){super();}
accept(event){return!TimelineUIUtils.eventStyle(event).category.hidden;}}
class TimelineRegExp extends TimelineModelFilter.TimelineModelFilter{constructor(regExp){super();this._regExp;this.setRegExp(regExp||null);}
setRegExp(regExp){this._regExp=regExp;}
regExp(){return this._regExp;}
accept(event){return!this._regExp||TimelineUIUtils.testContentMatching(event,this._regExp);}}
var TimelineFilters=Object.freeze({__proto__:null,IsLong:IsLong,Category:Category,TimelineRegExp:TimelineRegExp});class TimelineTreeView extends Widget.VBox{constructor(){super();this._model=null;this._track=null;this._tree=null;this.element.classList.add('timeline-tree-view');}
static eventNameForSorting(event){if(event.name===TimelineModel.RecordType.JSFrame){const data=event.args['data'];return data['functionName']+'@'+(data['scriptId']||data['url']||'');}
return event.name+':@'+TimelineProfileTree.eventURL(event);}
setSearchableView(searchableView){this._searchableView=searchableView;}
setModel(model,track){this._model=model;this._track=track;this.refreshTree();}
getToolbarInputAccessiblePlaceHolder(){return'';}
model(){return this._model;}
init(){this._linkifier=new Linkifier.Linkifier();this._taskFilter=new TimelineModelFilter.ExclusiveNameFilter([TimelineModel.RecordType.Task]);this._textFilter=new TimelineRegExp();this._currentThreadSetting=Settings.Settings.instance().createSetting('timelineTreeCurrentThread',0);this._currentThreadSetting.addChangeListener(this.refreshTree,this);const columns=([]);this.populateColumns(columns);this._splitWidget=new SplitWidget.SplitWidget(true,true,'timelineTreeViewDetailsSplitWidget');const mainView=new Widget.VBox();const toolbar=new Toolbar.Toolbar('',mainView.element);this.populateToolbar(toolbar);this._dataGrid=new SortableDataGrid.SortableDataGrid({displayName:ls`Performance`,columns});this._dataGrid.addEventListener(DataGrid.Events.SortingChanged,this._sortingChanged,this);this._dataGrid.element.addEventListener('mousemove',this._onMouseMove.bind(this),true);this._dataGrid.setResizeMethod(DataGrid.ResizeMethod.Last);this._dataGrid.setRowContextMenuCallback(this._onContextMenu.bind(this));this._dataGrid.asWidget().show(mainView.element);this._dataGrid.addEventListener(DataGrid.Events.SelectedNode,this._updateDetailsForSelection,this);this._detailsView=new Widget.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(SplitWidget.Events.ShowModeChanged,this._onShowModeChanged,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();}
filters(){return[this._taskFilter,this._textFilter,...this._model.filters()];}
filtersWithoutTextFilter(){return[this._taskFilter,...this._model.filters()];}
textFilter(){return this._textFilter;}
_exposePercentages(){return false;}
populateToolbar(toolbar){this._textFilterUI=new Toolbar.ToolbarInput(UIString.UIString('Filter'),this.getToolbarInputAccessiblePlaceHolder());this._textFilterUI.addEventListener(Toolbar.ToolbarInput.Event.TextChanged,textFilterChanged,this);toolbar.appendToolbarItem(this._textFilterUI);function textFilterChanged(){const searchQuery=this._textFilterUI.value();this._textFilter.setRegExp(searchQuery?createPlainTextSearchRegex(searchQuery,'i'):null);this.refreshTree();}}
_modelEvents(){return this._track?this._track.syncEvents():[];}
_onHover(node){}
_appendContextMenuItems(contextMenu,node){}
_linkifyLocation(event){const target=this._model.timelineModel().targetByEvent(event);if(!target){return null;}
const frame=TimelineProfileTree.eventStackFrame(event);if(!frame){return null;}
return this._linkifier.maybeLinkifyConsoleCallFrame(target,frame);}
selectProfileNode(treeNode,suppressSelectedEvent){const pathToRoot=[];for(let node=treeNode;node;node=node.parent){pathToRoot.push(node);}
for(let i=pathToRoot.length-1;i>0;--i){const gridNode=this.dataGridNodeForTreeNode(pathToRoot[i]);if(gridNode&&gridNode.dataGrid){gridNode.expand();}}
const gridNode=this.dataGridNodeForTreeNode(treeNode);if(gridNode.dataGrid){gridNode.reveal();gridNode.select(suppressSelectedEvent);}}
refreshTree(){this._linkifier.reset();this._dataGrid.rootNode().removeChildren();if(!this._model){this._updateDetailsForSelection();return;}
this._root=this._buildTree();const children=this._root.children();let maxSelfTime=0;let maxTotalTime=0;const totalUsedTime=this._root.totalTime-this._root.selfTime;for(const child of children.values()){maxSelfTime=Math.max(maxSelfTime,child.selfTime);maxTotalTime=Math.max(maxTotalTime,child.totalTime);}
for(const child of children.values()){const gridNode=new TreeGridNode(child,totalUsedTime,maxSelfTime,maxTotalTime,this);this._dataGrid.insertChild(gridNode);}
this._sortingChanged();this._updateDetailsForSelection();if(this._searchableView){this._searchableView.refreshSearch();}
const rootNode=this._dataGrid.rootNode();if(rootNode.children.length>0){rootNode.children[0].select();}}
_buildTree(){throw new Error('Not Implemented');}
buildTopDownTree(doNotAggregate,groupIdCallback){return new TimelineProfileTree.TopDownRootNode(this._modelEvents(),this.filters(),this._startTime,this._endTime,doNotAggregate,groupIdCallback);}
populateColumns(columns){columns.push({id:'self',title:UIString.UIString('Self Time'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'total',title:UIString.UIString('Total Time'),width:'120px',fixedWidth:true,sortable:true});columns.push({id:'activity',title:UIString.UIString('Activity'),disclosure:true,sortable:true});}
_sortingChanged(){const columnId=this._dataGrid.sortColumnId();if(!columnId){return;}
let 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){const nodeA=(a);const nodeB=(b);return nodeA._profileNode[field]-nodeB._profileNode[field];}
function compareStartTime(a,b){const nodeA=(a);const nodeB=(b);return nodeA._profileNode.event.startTime-nodeB._profileNode.event.startTime;}
function compareName(a,b){const nodeA=(a);const nodeB=(b);const nameA=TimelineTreeView.eventNameForSorting(nodeA._profileNode.event);const nameB=TimelineTreeView.eventNameForSorting(nodeB._profileNode.event);return nameA.localeCompare(nameB);}}
_onShowModeChanged(){if(this._splitWidget.showMode()===SplitWidget.ShowMode.OnlyMain){return;}
this._lastSelectedNode=undefined;this._updateDetailsForSelection();}
_updateDetailsForSelection(){const selectedNode=this._dataGrid.selectedNode?(this._dataGrid.selectedNode)._profileNode:null;if(selectedNode===this._lastSelectedNode){return;}
this._lastSelectedNode=selectedNode;if(this._splitWidget.showMode()===SplitWidget.ShowMode.OnlyMain){return;}
this._detailsView.detachChildWidgets();this._detailsView.element.removeChildren();if(selectedNode&&this._showDetailsForNode(selectedNode)){return;}
const banner=this._detailsView.element.createChild('div','full-widget-dimmed-banner');banner.createTextChild(UIString.UIString('Select item for details.'));}
_showDetailsForNode(node){return false;}
_onMouseMove(event){const gridNode=event.target&&(event.target instanceof Node)?(this._dataGrid.dataGridNodeFromNode((event.target))):null;const profileNode=gridNode&&gridNode._profileNode;if(profileNode===this._lastHoveredProfileNode){return;}
this._lastHoveredProfileNode=profileNode;this._onHover(profileNode);}
_onContextMenu(contextMenu,gridNode){if(gridNode._linkElement&&!contextMenu.containsTarget(gridNode._linkElement)){contextMenu.appendApplicableItems(gridNode._linkElement);}
const profileNode=gridNode._profileNode;if(profileNode){this._appendContextMenuItems(contextMenu,profileNode);}}
dataGridNodeForTreeNode(treeNode){return treeNode[TreeGridNode._gridNodeSymbol]||null;}
searchCanceled(){this._searchResults=[];this._currentResult=0;}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchResults=[];this._currentResult=0;if(!this._root){return;}
const searchRegex=searchConfig.toSearchRegex();this._searchResults=this._root.searchTree(event=>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=NumberUtilities.mod(this._currentResult+1,this._searchResults.length);}
jumpToPreviousSearchResult(){if(!this._searchResults.length){return;}
this.selectProfileNode(this._searchResults[this._currentResult],false);this._currentResult=NumberUtilities.mod(this._currentResult-1,this._searchResults.length);}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}}
class GridNode extends SortableDataGrid.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;this._linkElement=null;}
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 iconContainer=container.createChild('div','activity-icon-container');const icon=iconContainer.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;if(info.icon){iconContainer.insertBefore(info.icon,icon);}}else if(event){const data=event.args['data'];const deoptReason=data&&data['deoptReason'];if(deoptReason){container.createChild('div','activity-warning').title=UIString.UIString('Not optimized: %s',deoptReason);}
name.textContent=TimelineUIUtils.eventTitle(event);this._linkElement=this._treeView._linkifyLocation(event);if(this._linkElement){container.createChild('div','activity-link').appendChild(this._linkElement);}
const eventStyle=TimelineUIUtils.eventStyle(event);const eventCategory=eventStyle.category;ARIAUtils.setAccessibleName(icon,eventCategory.title);icon.style.backgroundColor=eventCategory.color;}
return cell;}
_createValueCell(columnId){if(columnId!=='self'&&columnId!=='total'&&columnId!=='startTime'){return null;}
let showPercents=false;let value;let 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;}
const cell=this.createTD(columnId);cell.className='numeric-column';const textDiv=cell.createChild('div');textDiv.createChild('span').textContent=UIString.UIString('%.1f\xa0ms',value);if(showPercents&&this._treeView._exposePercentages()){textDiv.createChild('span','percent-column').textContent=UIString.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;}}
class TreeGridNode extends GridNode{constructor(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView){super(profileNode,grandTotalTime,maxSelfTime,maxTotalTime,treeView);this.setHasChildren(this._profileNode.hasChildren());profileNode[TreeGridNode._gridNodeSymbol]=this;}
populate(){if(this._populated){return;}
this._populated=true;if(!this._profileNode.children){return;}
for(const node of this._profileNode.children().values()){const gridNode=new TreeGridNode(node,this._grandTotalTime,this._maxSelfTime,this._maxTotalTime,this._treeView);this.insertChildOrdered(gridNode);}}}
TreeGridNode._gridNodeSymbol=Symbol('treeGridNode');class AggregatedTimelineTreeView extends TimelineTreeView{constructor(){super();this._groupBySetting=Settings.Settings.instance().createSetting('timelineTreeGroupBy',AggregatedTimelineTreeView.GroupBy.None);this._groupBySetting.addChangeListener(this.refreshTree.bind(this));this.init();this._stackView=new TimelineStackView(this);this._stackView.addEventListener(TimelineStackView.Events.SelectionChanged,this._onStackViewSelectionChanged,this);this._productByURLCache=new Map();this._colorByURLCache=new Map();}
setModel(model,track){super.setModel(model,track);}
updateContents(selection){this._updateExtensionResolver();super.updateContents(selection);const rootNode=this._dataGrid.rootNode();if(rootNode.children.length){rootNode.children[0].select();}}
_updateExtensionResolver(){this._executionContextNamesByOrigin=new Map();for(const runtimeModel of SDKModel.TargetManager.instance().models(RuntimeModel.RuntimeModel)){for(const context of runtimeModel.executionContexts()){this._executionContextNamesByOrigin.set(context.origin,context.name);}}}
_beautifyDomainName(name){if(AggregatedTimelineTreeView._isExtensionInternalURL(name)){name=UIString.UIString('[Chrome extensions overhead]');}else if(AggregatedTimelineTreeView._isV8NativeURL(name)){name=UIString.UIString('[V8 Runtime]');}else if(name.startsWith('chrome-extension')){name=this._executionContextNamesByOrigin.get(name)||name;}
return name;}
_displayInfoForGroupNode(node){const categories=TimelineUIUtils.categories();const color=node.id?TimelineUIUtils.eventColor((node.event)):categories['other'].color;const unattributed=UIString.UIString('[unattributed]');const id=typeof node.id==='symbol'?undefined:node.id;switch(this._groupBySetting.get()){case AggregatedTimelineTreeView.GroupBy.Category:{const category=id?categories[id]||categories['other']:unattributed;return{name:category.title,color:category.color};}
case AggregatedTimelineTreeView.GroupBy.Domain:case AggregatedTimelineTreeView.GroupBy.Subdomain:{const domainName=id?this._beautifyDomainName(id):undefined;return{name:domainName||unattributed,color:color};}
case AggregatedTimelineTreeView.GroupBy.EventName:{const name=node.event.name===TimelineModel.RecordType.JSFrame?UIString.UIString('JavaScript'):TimelineUIUtils.eventTitle(node.event);return{name:name,color:node.event.name===TimelineModel.RecordType.JSFrame?TimelineUIUtils.eventStyle(node.event).category.color:color};}
case AggregatedTimelineTreeView.GroupBy.URL:break;case AggregatedTimelineTreeView.GroupBy.Frame:{const frame=id?this._model.timelineModel().pageFrameById(id):undefined;const frameName=frame?TimelineUIUtils.displayNameForFrame(frame,80):UIString.UIString('Page');return{name:frameName,color:color};}
default:console.assert(false,'Unexpected grouping type');}
return{name:id||unattributed,color:color};}
populateToolbar(toolbar){super.populateToolbar(toolbar);const groupBy=AggregatedTimelineTreeView.GroupBy;const options=[{label:UIString.UIString('No Grouping'),value:groupBy.None},{label:UIString.UIString('Group by Activity'),value:groupBy.EventName},{label:UIString.UIString('Group by Category'),value:groupBy.Category},{label:UIString.UIString('Group by Domain'),value:groupBy.Domain},{label:UIString.UIString('Group by Frame'),value:groupBy.Frame},{label:UIString.UIString('Group by Subdomain'),value:groupBy.Subdomain},{label:UIString.UIString('Group by URL'),value:groupBy.URL},];toolbar.appendToolbarItem(new Toolbar.ToolbarSettingComboBox(options,this._groupBySetting,ls`Group by`));toolbar.appendSpacer();toolbar.appendToolbarItem(this._splitWidget.createShowHideSidebarButton(UIString.UIString('heaviest stack')));}
_buildHeaviestStack(treeNode){console.assert(!!treeNode.parent,'Attempt to build stack for tree root');let result=[];for(let node=treeNode;node&&node.parent;node=node.parent){result.push(node);}
result=result.reverse();for(let node=treeNode;node&&node.children()&&node.children().size;){const 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;}
_onStackViewSelectionChanged(){const treeNode=this._stackView.selectedTreeNode();if(treeNode){this.selectProfileNode(treeNode,true);}}
_showDetailsForNode(node){const stack=this._buildHeaviestStack(node);this._stackView.setStack(stack,node);this._stackView.show(this._detailsView.element);return true;}
_groupingFunction(groupBy){const GroupBy=AggregatedTimelineTreeView.GroupBy;switch(groupBy){case GroupBy.None:return null;case GroupBy.EventName:return event=>TimelineUIUtils.eventStyle(event).title;case GroupBy.Category:return event=>TimelineUIUtils.eventStyle(event).category.name;case GroupBy.Subdomain:return this._domainByEvent.bind(this,false);case GroupBy.Domain:return this._domainByEvent.bind(this,true);case GroupBy.URL:return event=>TimelineProfileTree.eventURL(event)||'';case GroupBy.Frame:return event=>TimelineModel.TimelineData.forEvent(event).frameId;default:console.assert(false,`Unexpected aggregation setting: ${groupBy}`);return null;}}
_domainByEvent(groupSubdomains,event){const url=TimelineProfileTree.eventURL(event);if(!url){return'';}
if(AggregatedTimelineTreeView._isExtensionInternalURL(url)){return AggregatedTimelineTreeView._extensionInternalPrefix;}
if(AggregatedTimelineTreeView._isV8NativeURL(url)){return AggregatedTimelineTreeView._v8NativePrefix;}
const parsedURL=ParsedURL.ParsedURL.fromString(url);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;}
const domainMatch=/([^.]*\.)?[^.]*$/.exec(parsedURL.host);return domainMatch&&domainMatch[0]||'';}
_appendContextMenuItems(contextMenu,node){if(this._groupBySetting.get()!==AggregatedTimelineTreeView.GroupBy.Frame){return;}
if(!node.isGroupNode()){return;}
const frame=this._model.timelineModel().pageFrameById((node.id));if(!frame||!frame.ownerNode){return;}
contextMenu.appendApplicableItems(frame.ownerNode);}
static _isExtensionInternalURL(url){return url.startsWith(AggregatedTimelineTreeView._extensionInternalPrefix);}
static _isV8NativeURL(url){return url.startsWith(AggregatedTimelineTreeView._v8NativePrefix);}}
AggregatedTimelineTreeView._extensionInternalPrefix='extensions::';AggregatedTimelineTreeView._v8NativePrefix='native ';AggregatedTimelineTreeView.GroupBy={None:'None',EventName:'EventName',Category:'Category',Domain:'Domain',Subdomain:'Subdomain',URL:'URL',Frame:'Frame'};class CallTreeTimelineTreeView extends AggregatedTimelineTreeView{constructor(){super();this._dataGrid.markColumnAsSortedBy('total',DataGrid.Order.Descending);}
getToolbarInputAccessiblePlaceHolder(){return ls`Filter call tree`;}
_buildTree(){const grouping=this._groupBySetting.get();return this.buildTopDownTree(false,this._groupingFunction(grouping));}}
class BottomUpTimelineTreeView extends AggregatedTimelineTreeView{constructor(){super();this._dataGrid.markColumnAsSortedBy('self',DataGrid.Order.Descending);}
getToolbarInputAccessiblePlaceHolder(){return ls`Filter bottom-up`;}
_buildTree(){return new TimelineProfileTree.BottomUpRootNode(this._modelEvents(),this.textFilter(),this.filtersWithoutTextFilter(),this._startTime,this._endTime,this._groupingFunction(this._groupBySetting.get()));}}
class TimelineStackView extends Widget.VBox{constructor(treeView){super();const header=this.element.createChild('div','timeline-stack-view-header');header.textContent=UIString.UIString('Heaviest stack');this._treeView=treeView;const columns=([{id:'total',title:UIString.UIString('Total Time'),fixedWidth:true,width:'110px'},{id:'activity',title:UIString.UIString('Activity')}]);this._dataGrid=new ViewportDataGrid.ViewportDataGrid({displayName:ls`Timeline Stack`,columns});this._dataGrid.setResizeMethod(DataGrid.ResizeMethod.Last);this._dataGrid.addEventListener(DataGrid.Events.SelectedNode,this._onSelectionChanged,this);this._dataGrid.asWidget().show(this.element);}
setStack(stack,selectedNode){const rootNode=this._dataGrid.rootNode();rootNode.removeChildren();let nodeToReveal=null;const totalTime=Math.max.apply(Math,stack.map(node=>node.totalTime));for(const node of stack){const gridNode=new GridNode(node,totalTime,totalTime,totalTime,this._treeView);rootNode.appendChild(gridNode);if(node===selectedNode){nodeToReveal=gridNode;}}
nodeToReveal.revealAndSelect();}
selectedTreeNode(){const selectedNode=this._dataGrid.selectedNode;return selectedNode&&(selectedNode)._profileNode;}
_onSelectionChanged(){this.dispatchEventToListeners(TimelineStackView.Events.SelectionChanged);}}
TimelineStackView.Events={SelectionChanged:Symbol('SelectionChanged')};var TimelineTreeView$1=Object.freeze({__proto__:null,TimelineTreeView:TimelineTreeView,GridNode:GridNode,TreeGridNode:TreeGridNode,AggregatedTimelineTreeView:AggregatedTimelineTreeView,CallTreeTimelineTreeView:CallTreeTimelineTreeView,BottomUpTimelineTreeView:BottomUpTimelineTreeView,TimelineStackView:TimelineStackView});class EventsTimelineTreeView extends TimelineTreeView{constructor(delegate){super();this._filtersControl=new Filters();this._filtersControl.addEventListener(Filters.Events.FilterChanged,this._onFilterChanged,this);this.init();this._delegate=delegate;this._dataGrid.markColumnAsSortedBy('startTime',DataGrid.Order.Ascending);this._splitWidget.showBoth();}
filters(){return[...super.filters(),...this._filtersControl.filters()];}
updateContents(selection){super.updateContents(selection);if(selection.type()===TimelineSelection.Type.TraceEvent){const event=(selection.object());this._selectEvent(event,true);}}
getToolbarInputAccessiblePlaceHolder(){return ls`Filter event log`;}
_buildTree(){this._currentTree=this.buildTopDownTree(true,null);return this._currentTree;}
_onFilterChanged(){const selectedEvent=this.lastSelectedNode()&&this.lastSelectedNode().event;this.refreshTree();if(selectedEvent){this._selectEvent(selectedEvent,false);}}
_findNodeWithEvent(event){const iterators=[this._currentTree.children().values()];while(iterators.length){const iterator=iterators.peekLast().next();if(iterator.done){iterators.pop();continue;}
const child=(iterator.value);if(child.event===event){return child;}
iterators.push(child.children().values());}
return null;}
_selectEvent(event,expand){const node=this._findNodeWithEvent(event);if(!node){return;}
this.selectProfileNode(node,false);if(expand){this.dataGridNodeForTreeNode(node).expand();}}
populateColumns(columns){columns.push({id:'startTime',title:UIString.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){const traceEvent=node.event;if(!traceEvent){return false;}
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);}}
class Filters extends ObjectWrapper.ObjectWrapper{constructor(){super();this._categoryFilter=new Category();this._durationFilter=new IsLong();this._filters=[this._categoryFilter,this._durationFilter];}
filters(){return this._filters;}
populateToolbar(toolbar){const durationFilterUI=new Toolbar.ToolbarComboBox(durationFilterChanged.bind(this),ls`Duration filter`);for(const durationMs of Filters._durationFilterPresetsMs){durationFilterUI.addOption(durationFilterUI.createOption(durationMs?UIString.UIString('\u2265 %d\xa0ms',durationMs):UIString.UIString('All'),String(durationMs)));}
toolbar.appendToolbarItem(durationFilterUI);const categoryFiltersUI={};const categories=TimelineUIUtils.categories();for(const categoryName in categories){const category=categories[categoryName];if(!category.visible){continue;}
const checkbox=new Toolbar.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(){const duration=durationFilterUI.selectedOption().value;const minimumRecordDuration=parseInt(duration,10);this._durationFilter.setMinimumRecordDuration(minimumRecordDuration);this._notifyFiltersChanged();}
function categoriesFilterChanged(name){const categories=TimelineUIUtils.categories();categories[name].hidden=!categoryFiltersUI[name].checked();this._notifyFiltersChanged();}}
_notifyFiltersChanged(){this.dispatchEventToListeners(Filters.Events.FilterChanged);}}
Filters._durationFilterPresetsMs=[0,1,15];Filters.Events={FilterChanged:Symbol('FilterChanged')};var EventsTimelineTreeView$1=Object.freeze({__proto__:null,EventsTimelineTreeView:EventsTimelineTreeView,Filters:Filters});class TimelineLayersView extends SplitWidget.SplitWidget{constructor(model,showPaintProfilerCallback){super(true,false,'timelineLayersView');this._model=model;this._showPaintProfilerCallback=showPaintProfilerCallback;this.element.classList.add('timeline-layers-view');this._rightSplitWidget=new SplitWidget.SplitWidget(true,true,'timelineLayersViewDetails');this._rightSplitWidget.element.classList.add('timeline-layers-view-properties');this.setMainWidget(this._rightSplitWidget);const vbox=new Widget.VBox();this.setSidebarWidget(vbox);this._layerViewHost=new LayerViewHost.LayerViewHost();const layerTreeOutline=new LayerTreeOutline.LayerTreeOutline(this._layerViewHost);vbox.element.appendChild(layerTreeOutline.element);this._layers3DView=new Layers3DView.Layers3DView(this._layerViewHost);this._layers3DView.addEventListener(Layers3DView.Events.PaintProfilerRequested,this._onPaintProfilerRequested,this);this._rightSplitWidget.setMainWidget(this._layers3DView);const layerDetailsView=new LayerDetailsView.LayerDetailsView(this._layerViewHost);this._rightSplitWidget.setSidebarWidget(layerDetailsView);layerDetailsView.addEventListener(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){const 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));}}
var TimelineLayersView$1=Object.freeze({__proto__:null,TimelineLayersView:TimelineLayersView});class TimelinePaintProfilerView extends SplitWidget.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 SplitWidget.SplitWidget(true,false);this._logAndImageSplitWidget.element.classList.add('timeline-paint-profiler-log-split');this.setMainWidget(this._logAndImageSplitWidget);this._imageView=new TimelinePaintImageView();this._logAndImageSplitWidget.setMainWidget(this._imageView);this._paintProfilerView=new PaintProfilerView.PaintProfilerView(this._imageView.showImage.bind(this._imageView));this._paintProfilerView.addEventListener(PaintProfilerView.Events.WindowChanged,this._onWindowChanged,this);this.setSidebarWidget(this._paintProfilerView);this._logTreeView=new PaintProfilerView.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.RecordType.Paint){return!!TimelineModel.TimelineData.forEvent(event).picture;}
if(this._event.name===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);let snapshotPromise;if(this._pendingSnapshot){snapshotPromise=Promise.resolve({rect:null,snapshot:this._pendingSnapshot});}else if(this._event.name===TimelineModel.RecordType.Paint){const 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.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;}
const 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());}}
class TimelinePaintImageView extends Widget.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 TransformController.TransformController(this.contentElement,true);this._transformController.addEventListener(TransformController.Events.TransformChanged,this._updateImagePosition,this);}
onResize(){if(this._imageElement.src){this._updateImagePosition();}}
_updateImagePosition(){const width=this._imageElement.naturalWidth;const height=this._imageElement.naturalHeight;const clientWidth=this.contentElement.clientWidth;const clientHeight=this.contentElement.clientHeight;const paddingFraction=0.1;const paddingX=clientWidth*paddingFraction;const paddingY=clientHeight*paddingFraction;const scaleX=(clientWidth-paddingX)/width;const scaleY=(clientHeight-paddingY)/height;const scale=Math.min(scaleX,scaleY);if(this._maskRectangle){const 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);let matrix=new WebKitCSSMatrix().scale(this._transformController.scale(),this._transformController.scale()).translate(clientWidth/2,clientHeight/2).scale(scale,scale).translate(-width/2,-height/2);const bounds=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);}}
var TimelinePaintProfilerView$1=Object.freeze({__proto__:null,TimelinePaintProfilerView:TimelinePaintProfilerView,TimelinePaintImageView:TimelinePaintImageView});class TimelineDetailsView extends Widget.VBox{constructor(delegate){super();this.element.classList.add('timeline-details');this._detailsLinkifier=new Linkifier.Linkifier();this._tabbedPane=new TabbedPane.TabbedPane();this._tabbedPane.show(this.element);const tabIds=Tab;this._defaultDetailsWidget=new Widget.VBox();this._defaultDetailsWidget.element.classList.add('timeline-details-view');this._defaultDetailsContentElement=this._defaultDetailsWidget.element.createChild('div','timeline-details-view-body vbox');this._appendTab(tabIds.Details,UIString.UIString('Summary'),this._defaultDetailsWidget);this.setPreferredTab(tabIds.Details);this._rangeDetailViews=new Map();const bottomUpView=new BottomUpTimelineTreeView();this._appendTab(tabIds.BottomUp,UIString.UIString('Bottom-Up'),bottomUpView);this._rangeDetailViews.set(tabIds.BottomUp,bottomUpView);const callTreeView=new CallTreeTimelineTreeView();this._appendTab(tabIds.CallTree,UIString.UIString('Call Tree'),callTreeView);this._rangeDetailViews.set(tabIds.CallTree,callTreeView);const eventsView=new EventsTimelineTreeView(delegate);this._appendTab(tabIds.EventLog,UIString.UIString('Event Log'),eventsView);this._rangeDetailViews.set(tabIds.EventLog,eventsView);this._tabbedPane.addEventListener(TabbedPane.Events.TabSelected,this._tabSelected,this);}
setModel(model,track){if(this._model!==model){if(this._model){this._model.removeEventListener(Events$1.WindowChanged,this._onWindowChanged,this);}
this._model=model;if(this._model){this._model.addEventListener(Events$1.WindowChanged,this._onWindowChanged,this);}}
this._track=track;this._tabbedPane.closeTabs([Tab.PaintProfiler,Tab.LayerViewer],false);for(const view of this._rangeDetailViews.values()){view.setModel(model,track);}
this._lazyPaintProfilerView=null;this._lazyLayersView=null;this.setSelection(null);}
_setContent(node){const allTabs=this._tabbedPane.otherTabs(Tab.Details);for(let 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){const window=this._model.window();view.updateContents(this._selection||TimelineSelection.fromRange(window.left,window.right));}}
_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;}
_onWindowChanged(event){if(!this._selection){this._updateContentsFromWindow();}}
_updateContentsFromWindow(){if(!this._model){this._setContent(Fragment.html`<div/>`);return;}
const window=this._model.window();this._updateSelectedRangeStats(window.left,window.right);this._updateContents();}
setSelection(selection){this._detailsLinkifier.reset();this._selection=selection;if(!this._selection){this._updateContentsFromWindow();return;}
switch(this._selection.type()){case TimelineSelection.Type.TraceEvent:{const event=(this._selection.object());TimelineUIUtils.buildTraceEventDetails(event,this._model.timelineModel(),this._detailsLinkifier,true).then(fragment=>this._appendDetailsTabsForTraceEventAndShowDetails(event,fragment));break;}
case TimelineSelection.Type.Frame:{const frame=(this._selection.object());const filmStripFrame=this._model.filmStripModelFrame(frame);this._setContent(TimelineUIUtils.generateDetailsContentForFrame(frame,filmStripFrame));if(frame.layerTree){const layersView=this._layersView();layersView.showLayerTree(frame.layerTree);if(!this._tabbedPane.hasTab(Tab.LayerViewer)){this._appendTab(Tab.LayerViewer,UIString.UIString('Layers'),layersView);}}
break;}
case TimelineSelection.Type.NetworkRequest:{const request=(this._selection.object());TimelineUIUtils.buildNetworkRequestDetails(request,this._model.timelineModel(),this._detailsLinkifier).then(this._setContent.bind(this));break;}
case 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 TimelineLayersView(this._model.timelineModel(),this._showSnapshotInPaintProfiler.bind(this));return this._lazyLayersView;}
_paintProfilerView(){if(this._lazyPaintProfilerView){return this._lazyPaintProfilerView;}
this._lazyPaintProfilerView=new TimelinePaintProfilerView(this._model.frameModel());return this._lazyPaintProfilerView;}
_showSnapshotInPaintProfiler(snapshot){const paintProfilerView=this._paintProfilerView();paintProfilerView.setSnapshot(snapshot);if(!this._tabbedPane.hasTab(Tab.PaintProfiler)){this._appendTab(Tab.PaintProfiler,UIString.UIString('Paint Profiler'),paintProfilerView,true);}
this._tabbedPane.selectTab(Tab.PaintProfiler,true);}
_appendDetailsTabsForTraceEventAndShowDetails(event,content){this._setContent(content);if(event.name===TimelineModel.RecordType.Paint||event.name===TimelineModel.RecordType.RasterTask){this._showEventInPaintProfiler(event);}}
_showEventInPaintProfiler(event){const paintProfilerModel=SDKModel.TargetManager.instance().models(PaintProfiler.PaintProfilerModel)[0];if(!paintProfilerModel){return;}
const paintProfilerView=this._paintProfilerView();const hasProfileData=paintProfilerView.setEvent(paintProfilerModel,event);if(!hasProfileData){return;}
if(this._tabbedPane.hasTab(Tab.PaintProfiler)){return;}
this._appendTab(Tab.PaintProfiler,UIString.UIString('Paint Profiler'),paintProfilerView);}
_updateSelectedRangeStats(startTime,endTime){if(!this._model||!this._track){return;}
const aggregatedStats=TimelineUIUtils.statsForTimeRange(this._track.syncEvents(),startTime,endTime);const startOffset=startTime-this._model.timelineModel().minimumRecordTime();const endOffset=endTime-this._model.timelineModel().minimumRecordTime();const contentHelper=new TimelineDetailsContentHelper(null,null);contentHelper.addSection(ls`Range:  ${Number.millisToString(startOffset)} \u2013 ${Number.millisToString(endOffset)}`);const pieChart=TimelineUIUtils.generatePieChart(aggregatedStats);contentHelper.appendElementRow('',pieChart);this._setContent(contentHelper.fragment);}}
const Tab={Details:'Details',EventLog:'EventLog',CallTree:'CallTree',BottomUp:'BottomUp',PaintProfiler:'PaintProfiler',LayerViewer:'LayerViewer'};var TimelineDetailsView$1=Object.freeze({__proto__:null,TimelineDetailsView:TimelineDetailsView,Tab:Tab});class TimelineFlameChartDataProvider extends ObjectWrapper.ObjectWrapper{constructor(){super();this.reset();this._font='11px '+Platform$1.fontFamily();this._timelineData=null;this._currentLevel=0;this._performanceModel=null;this._model=null;this._minimumBoundary=0;this._maximumBoundary=0;this._timeSpan=0;this._consoleColorGenerator=new Color.Generator({min:30,max:55},{min:70,max:100,count:6},50,0.7);this._extensionColorGenerator=new Color.Generator({min:210,max:300},{min:70,max:100,count:6},70,0.7);this._headerLevel1=this._buildGroupStyle({shareHeaderLine:false});this._headerLevel2=this._buildGroupStyle({padding:2,nestingLevel:1,collapsible:false});this._staticHeader=this._buildGroupStyle({collapsible:false});this._framesHeader=this._buildGroupStyle({useFirstLineForOverview:true});this._collapsibleTimingsHeader=this._buildGroupStyle({shareHeaderLine:true,useFirstLineForOverview:true,collapsible:true});this._timingsHeader=this._buildGroupStyle({shareHeaderLine:true,useFirstLineForOverview:true,collapsible:false});this._screenshotsHeader=this._buildGroupStyle({useFirstLineForOverview:true,nestingLevel:1,collapsible:false,itemsHeight:150});this._interactionsHeaderLevel1=this._buildGroupStyle({useFirstLineForOverview:true});this._interactionsHeaderLevel2=this._buildGroupStyle({padding:2,nestingLevel:1});this._experienceHeader=this._buildGroupStyle({collapsible:false});this._flowEventIndexById=new Map();}
_buildGroupStyle(extra){const defaultGroupStyle={padding:4,height:17,collapsible:true,color:self.UI.themeSupport.patchColorText('#222',UIUtils.ThemeSupport.ColorUsage.Foreground),backgroundColor:self.UI.themeSupport.patchColorText('white',UIUtils.ThemeSupport.ColorUsage.Background),font:this._font,nestingLevel:0,shareHeaderLine:true};return(Object.assign(defaultGroupStyle,extra));}
setModel(performanceModel){this.reset();this._performanceModel=performanceModel;this._model=performanceModel&&performanceModel.timelineModel();}
groupTrack(group){return group._track||null;}
entryTitle(entryIndex){const entryTypes=EntryType;const entryType=this._entryType(entryIndex);if(entryType===entryTypes.Event){const event=(this._entryData[entryIndex]);if(event.phase===TracingModel.Phase.AsyncStepInto||event.phase===TracingModel.Phase.AsyncStepPast){return event.name+':'+event.args['step'];}
if(event._blackboxRoot){return UIString.UIString('Blackboxed');}
if(this._performanceModel.timelineModel().isMarkerEvent(event)){return TimelineUIUtils.markerShortTitle(event);}
return TimelineUIUtils.eventTitle(event);}
if(entryType===entryTypes.ExtensionEvent){const event=(this._entryData[entryIndex]);return event.name;}
if(entryType===entryTypes.Screenshot){return'';}
let title=this._entryIndexToTitle[entryIndex];if(!title){title=UIString.UIString('Unexpected entryIndex %d',entryIndex);console.error(title);}
return title;}
textColor(index){const event=this._entryData[index];return event&&event._blackboxRoot?'#888':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=[];this._screenshotImageCache=new Map();}
maxStackDepth(){return this._currentLevel;}
timelineData(){if(this._timelineData){return this._timelineData;}
this._timelineData=new 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;if(this._model.isGenericTrace()){this._processGenericTrace();}else{this._processInspectorTrace();}
return this._timelineData;}
_processGenericTrace(){const processGroupStyle=this._buildGroupStyle({shareHeaderLine:false});const threadGroupStyle=this._buildGroupStyle({padding:2,nestingLevel:1,shareHeaderLine:false});const eventEntryType=EntryType.Event;const tracksByProcess=new Platform.Multimap();for(const track of this._model.tracks()){if(track.thread!==null){tracksByProcess.set(track.thread.process(),track);}else{console.error('Failed to process track');}}
for(const process of tracksByProcess.keysArray()){if(tracksByProcess.size>1){const name=`${process.name()} ${process.id()}`;this._appendHeader(name,processGroupStyle,false);}
for(const track of tracksByProcess.get(process)){const group=this._appendSyncEvents(track,track.events,track.name,threadGroupStyle,eventEntryType,true);if(!this._timelineData.selectedGroup||track.name===TimelineModel.TimelineModelImpl.BrowserMainThreadName){this._timelineData.selectedGroup=group;}}}}
_processInspectorTrace(){this._appendFrames();this._appendInteractionRecords();const eventEntryType=EntryType.Event;const weight=track=>{switch(track.type){case TimelineModel.TrackType.Input:return 0;case TimelineModel.TrackType.Animation:return 1;case TimelineModel.TrackType.Timings:return 2;case TimelineModel.TrackType.Console:return 3;case TimelineModel.TrackType.Experience:return 4;case TimelineModel.TrackType.MainThread:return track.forMainFrame?5:6;case TimelineModel.TrackType.Worker:return 7;case TimelineModel.TrackType.Raster:return 8;case TimelineModel.TrackType.GPU:return 9;case TimelineModel.TrackType.Other:return 10;}};const tracks=this._model.tracks().slice();tracks.sort((a,b)=>weight(a)-weight(b));let rasterCount=0;for(const track of tracks){switch(track.type){case TimelineModel.TrackType.Input:{this._appendAsyncEventsGroup(track,ls`Input`,track.asyncEvents,this._interactionsHeaderLevel2,eventEntryType,false);break;}
case TimelineModel.TrackType.Animation:{this._appendAsyncEventsGroup(track,ls`Animation`,track.asyncEvents,this._interactionsHeaderLevel2,eventEntryType,false);break;}
case TimelineModel.TrackType.Timings:{const style=track.asyncEvents.length>0?this._collapsibleTimingsHeader:this._timingsHeader;const group=this._appendHeader(ls`Timings`,style,true);group._track=track;this._appendPageMetrics();this._appendAsyncEventsGroup(track,null,track.asyncEvents,style,eventEntryType,true);break;}
case TimelineModel.TrackType.Console:{this._appendAsyncEventsGroup(track,ls`Console`,track.asyncEvents,this._headerLevel1,eventEntryType,true);break;}
case TimelineModel.TrackType.MainThread:{if(track.forMainFrame){const group=this._appendSyncEvents(track,track.events,track.url?ls`Main \u2014 ${track.url}`:ls`Main`,this._headerLevel1,eventEntryType,true);if(group){this._timelineData.selectedGroup=group;}}else{this._appendSyncEvents(track,track.events,track.url?ls`Frame \u2014 ${track.url}`:ls`Subframe`,this._headerLevel1,eventEntryType,true);}
break;}
case TimelineModel.TrackType.Worker:{this._appendSyncEvents(track,track.events,track.url?ls`Worker \u2014 ${track.url}`:ls`Dedicated Worker`,this._headerLevel1,eventEntryType,true);break;}
case TimelineModel.TrackType.Raster:{if(!rasterCount){this._appendHeader(ls`Raster`,this._headerLevel1,false);}
++rasterCount;this._appendSyncEvents(track,track.events,ls`Rasterizer Thread ${rasterCount}`,this._headerLevel2,eventEntryType,true);break;}
case TimelineModel.TrackType.GPU:{this._appendSyncEvents(track,track.events,ls`GPU`,this._headerLevel1,eventEntryType,true);break;}
case TimelineModel.TrackType.Other:{this._appendSyncEvents(track,track.events,track.name||ls`Thread`,this._headerLevel1,eventEntryType,true);this._appendAsyncEventsGroup(track,track.name,track.asyncEvents,this._headerLevel1,eventEntryType,true);break;}
case TimelineModel.TrackType.Experience:{this._appendSyncEvents(track,track.events,ls`Experience`,this._experienceHeader,eventEntryType,true);break;}}}
if(this._timelineData.selectedGroup){this._timelineData.selectedGroup.expanded=true;}
for(let extensionIndex=0;extensionIndex<this._extensionInfo.length;extensionIndex++){this._innerAppendExtensionEvents(extensionIndex);}
this._markers.sort((a,b)=>a.startTime()-b.startTime());this._timelineData.markers=this._markers;this._flowEventIndexById.clear();}
minimumBoundary(){return this._minimumBoundary;}
totalTime(){return this._timeSpan;}
search(startTime,endTime,filter){const result=[];const entryTypes=EntryType;this.timelineData();for(let i=0;i<this._entryData.length;++i){if(this._entryType(i)!==entryTypes.Event){continue;}
const event=(this._entryData[i]);if(event.startTime>endTime){continue;}
if((event.endTime||event.startTime)<startTime){continue;}
if(filter.accept(event)){result.push(i);}}
result.sort((a,b)=>TracingModel.Event.compareStartTime((this._entryData[a]),(this._entryData[b])));return result;}
_appendSyncEvents(track,events,title,style,entryType,selectable){if(!events.length){return null;}
const isExtension=entryType===EntryType.ExtensionEvent;const openEvents=[];const flowEventsEnabled=Root.Runtime.experiments.isEnabled('timelineFlowEvents');const blackboxingEnabled=!isExtension&&Root.Runtime.experiments.isEnabled('blackboxJSFramesOnTimeline');let maxStackDepth=0;let group=null;if(track&&track.type===TimelineModel.TrackType.MainThread){group=this._appendHeader(title,style,selectable);group._track=track;}
for(let i=0;i<events.length;++i){const e=events[i];if(track&&track.type===TimelineModel.TrackType.MainThread&&this._performanceModel&&this._performanceModel.timelineModel().isLayoutShiftEvent(e)){continue;}
if(this._performanceModel&&this._performanceModel.timelineModel().isLayoutShiftEvent(e)){for(const frame of this._performanceModel.frames()){if(typeof e.endTime==='undefined'){e.setEndTime(e.startTime);}
const isAfterStartTime=e.startTime>=frame.startTime;const isBeforeEndTime=e.endTime&&e.endTime<=frame.endTime;const eventIsInFrame=isAfterStartTime&&isBeforeEndTime;if(!eventIsInFrame){continue;}
e.startTime=frame.startTime;e.setEndTime(frame.endTime);}}
if(!isExtension&&this._performanceModel.timelineModel().isMarkerEvent(e)){this._markers.push(new TimelineFlameChartMarker(e.startTime,e.startTime-this._model.minimumRecordTime(),TimelineUIUtils.markerStyleForEvent(e)));}
if(!TracingModel.TracingModel.isFlowPhase(e.phase)){if(!e.endTime&&e.phase!==TracingModel.Phase.Instant){continue;}
if(TracingModel.TracingModel.isAsyncPhase(e.phase)){continue;}
if(!isExtension&&!this._performanceModel.isVisible(e)){continue;}}
while(openEvents.length&&openEvents.peekLast().endTime<=e.startTime){openEvents.pop();}
e._blackboxRoot=false;if(blackboxingEnabled&&this._isBlackboxedEvent(e)){const parent=openEvents.peekLast();if(parent&&parent._blackboxRoot){continue;}
e._blackboxRoot=true;}
if(!group){group=this._appendHeader(title,style,selectable);if(selectable){group._track=track;}}
const level=this._currentLevel+openEvents.length;if(flowEventsEnabled){this._appendFlowEvent(e,level);}
const index=this._appendEvent(e,level);if(openEvents.length){this._entryParent[index]=openEvents.peekLast();}
if(!isExtension&&this._performanceModel.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;return group;}
_isBlackboxedEvent(event){if(event.name!==TimelineModel.RecordType.JSFrame){return false;}
const url=event.args['data']['url'];return url&&this._isBlackboxedURL(url);}
_isBlackboxedURL(url){return BlackboxManager.BlackboxManager.instance().isBlackboxedURL(url);}
_appendAsyncEventsGroup(track,header,events,style,entryType,selectable){if(!events.length){return null;}
const lastUsedTimeByLevel=[];let group=null;for(let i=0;i<events.length;++i){const asyncEvent=events[i];if(!this._performanceModel.isVisible(asyncEvent)){continue;}
if(!group&&header){group=this._appendHeader(header,style,selectable);if(selectable){group._track=track;}}
const startTime=asyncEvent.startTime;let 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;return group;}
_appendInteractionRecords(){const interactionRecords=this._performanceModel.interactionRecords();if(!interactionRecords.length){return;}
this._appendHeader(ls`Interactions`,this._interactionsHeaderLevel1,false);for(const segment of interactionRecords){const 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;}
this._entryTypeByLevel[this._currentLevel++]=EntryType.InteractionRecord;}
_appendPageMetrics(){this._entryTypeByLevel[this._currentLevel]=EntryType.Event;const metricEvents=[];const lcpEvents=[];const timelineModel=this._performanceModel.timelineModel();for(const track of this._model.tracks()){for(const event of track.events){if(!timelineModel.isMarkerEvent(event)){continue;}
if(timelineModel.isLCPCandidateEvent(event)||timelineModel.isLCPInvalidateEvent(event)){lcpEvents.push(event);}else{metricEvents.push(event);}}}
if(lcpEvents.length>0){const lcpEventsByNavigationId=new Map();for(const e of lcpEvents){const key=e.args['data']['navigationId'];const previousLastEvent=lcpEventsByNavigationId.get(key);if(!previousLastEvent||previousLastEvent.args['data']['candidateIndex']<e.args['data']['candidateIndex']){lcpEventsByNavigationId.set(key,e);}}
const latestCandidates=Array.from(lcpEventsByNavigationId.values());const latestEvents=latestCandidates.filter(e=>timelineModel.isLCPCandidateEvent(e));metricEvents.push(...latestEvents);}
metricEvents.sort(TracingModel.Event.compareStartTime);const totalTimes=this._timelineData.entryTotalTimes;for(const event of metricEvents){this._appendEvent(event,this._currentLevel);totalTimes[totalTimes.length-1]=Number.NaN;}
++this._currentLevel;}
_appendFrames(){const screenshots=this._performanceModel.filmStripModel().frames();const hasFilmStrip=!!screenshots.length;this._framesHeader.collapsible=hasFilmStrip;this._appendHeader(UIString.UIString('Frames'),this._framesHeader,false);this._frameGroup=this._timelineData.groups.peekLast();const style=TimelineUIUtils.markerStyleForFrame();this._entryTypeByLevel[this._currentLevel]=EntryType.Frame;for(const frame of this._performanceModel.frames()){this._markers.push(new TimelineFlameChartMarker(frame.startTime,frame.startTime-this._model.minimumRecordTime(),style));this._appendFrame(frame);}
++this._currentLevel;if(!hasFilmStrip){return;}
this._appendHeader('',this._screenshotsHeader,false);this._entryTypeByLevel[this._currentLevel]=EntryType.Screenshot;let prevTimestamp;for(const screenshot of screenshots){this._entryData.push(screenshot);this._timelineData.entryLevels.push(this._currentLevel);this._timelineData.entryStartTimes.push(screenshot.timestamp);if(prevTimestamp){this._timelineData.entryTotalTimes.push(screenshot.timestamp-prevTimestamp);}
prevTimestamp=screenshot.timestamp;}
if(screenshots.length){this._timelineData.entryTotalTimes.push(this._model.maximumRecordTime()-prevTimestamp);}
++this._currentLevel;}
_entryType(entryIndex){return this._entryTypeByLevel[this._timelineData.entryLevels[entryIndex]];}
prepareHighlightedEntryInfo(entryIndex){let time='';let title;let warning;const type=this._entryType(entryIndex);if(type===EntryType.Event){const event=(this._entryData[entryIndex]);const totalTime=event.duration;const selfTime=event.selfTime;const eps=1e-6;if(typeof totalTime==='number'){time=Math.abs(totalTime-selfTime)>eps&&selfTime>eps?UIString.UIString('%s (self %s)',Number.millisToString(totalTime,true),Number.millisToString(selfTime,true)):Number.millisToString(totalTime,true);}
if(this._performanceModel.timelineModel().isMarkerEvent(event)){title=TimelineUIUtils.eventTitle(event);}else{title=this.entryTitle(entryIndex);}
warning=TimelineUIUtils.eventWarning(event);if(this._model&&this._model.isLayoutShiftEvent(event)){const occurrences=1;time=ls`Occurrences: ${occurrences}`;}}else if(type===EntryType.Frame){const frame=(this._entryData[entryIndex]);time=UIString.UIString('%s ~ %.0f\xa0fps',Number.preciseMillisToString(frame.duration,1),(1000/frame.duration));title=frame.idle?UIString.UIString('Idle Frame'):UIString.UIString('Frame');if(frame.hasWarnings()){warning=createElement('span');warning.textContent=UIString.UIString('Long frame');}}else{return null;}
const element=createElement('div');const root=Utils.createShadowRootWithCoreStyles(element,'timeline/timelineFlamechartPopover.css');const 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){let color=cache.get(key);if(color){return color;}
const parsedColor=Color.Color.parse(lookupColor(key));color=parsedColor.setAlpha(0.7).asString(Color.Format.RGBA)||'';cache.set(key,color);return color;}
const entryTypes=EntryType;const type=this._entryType(entryIndex);if(type===entryTypes.Event){const event=(this._entryData[entryIndex]);if(this._model.isGenericTrace()){return this._genericTraceEventColor(event);}
if(this._performanceModel.timelineModel().isMarkerEvent(event)){return TimelineUIUtils.markerStyleForEvent(event).color;}
if(!TracingModel.TracingModel.isAsyncPhase(event.phase)){return this._colorForEvent(event);}
if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.Console)||event.hasCategory(TimelineModel.TimelineModelImpl.Category.UserTiming)){return this._consoleColorGenerator.colorForID(event.name);}
if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.LatencyInfo)){const phase=TimelineIRModel.TimelineIRModel.phaseForEvent(event)||TimelineIRModel.Phases.Uncategorized;return patchColorAndCache(this._asyncColorByInteractionPhase,phase,TimelineUIUtils.interactionPhaseColor);}
const category=TimelineUIUtils.eventStyle(event).category;return patchColorAndCache(this._asyncColorByCategory,category,()=>category.color);}
if(type===entryTypes.Frame){return'white';}
if(type===entryTypes.InteractionRecord){return'transparent';}
if(type===entryTypes.ExtensionEvent){const event=(this._entryData[entryIndex]);return this._extensionColorGenerator.colorForID(event.name);}
return'';}
_genericTraceEventColor(event){const key=event.categoriesString||event.name;return key?`hsl(${String.hashCode(key) % 300 + 30}, 40%, 70%)`:'#ccc';}
_drawFrame(entryIndex,context,text,barX,barY,barWidth,barHeight){const hPadding=1;const frame=(this._entryData[entryIndex]);barX+=hPadding;barWidth-=2*hPadding;context.fillStyle=frame.idle?'white':(frame.hasWarnings()?'#fad1d1':'#d7f0d1');context.fillRect(barX,barY,barWidth,barHeight);const frameDurationText=Number.preciseMillisToString(frame.duration,1);const textWidth=context.measureText(frameDurationText).width;if(textWidth<=barWidth){context.fillStyle=this.textColor(entryIndex);context.fillText(frameDurationText,barX+(barWidth-textWidth)/2,barY+barHeight-4);}}
async _drawScreenshot(entryIndex,context,barX,barY,barWidth,barHeight){const screenshot=(this._entryData[entryIndex]);if(!this._screenshotImageCache.has(screenshot)){this._screenshotImageCache.set(screenshot,null);const data=await screenshot.imageDataPromise();const image=await UIUtils.loadImageFromData(data);this._screenshotImageCache.set(screenshot,image);this.dispatchEventToListeners(Events.DataChanged);return;}
const image=this._screenshotImageCache.get(screenshot);if(!image){return;}
const imageX=barX+1;const imageY=barY+1;const imageHeight=barHeight-2;const scale=imageHeight/image.naturalHeight;const imageWidth=Math.floor(image.naturalWidth*scale);context.save();context.beginPath();context.rect(barX,barY,barWidth,barHeight);context.clip();context.drawImage(image,imageX,imageY,imageWidth,imageHeight);context.strokeStyle='#ccc';context.strokeRect(imageX-0.5,imageY-0.5,Math.min(barWidth-1,imageWidth+1),imageHeight);context.restore();}
decorateEntry(entryIndex,context,text,barX,barY,barWidth,barHeight,unclippedBarX,timeToPixels){const data=this._entryData[entryIndex];const type=this._entryType(entryIndex);const entryTypes=EntryType;if(type===entryTypes.Frame){this._drawFrame(entryIndex,context,text,barX,barY,barWidth,barHeight);return true;}
if(type===entryTypes.Screenshot){this._drawScreenshot(entryIndex,context,barX,barY,barWidth,barHeight);return true;}
if(type===entryTypes.InteractionRecord){const color=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===entryTypes.Event){const event=(data);if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.LatencyInfo)){const timeWaitingForMainThread=TimelineModel.TimelineData.forEvent(event).timeWaitingForMainThread;if(timeWaitingForMainThread){context.fillStyle='hsla(0, 70%, 60%, 1)';const 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){const 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){const entryTypes=EntryType;const type=this._entryType(entryIndex);if(type===entryTypes.Frame){return true;}
if(type===entryTypes.Screenshot){return true;}
if(type===entryTypes.Event){const 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){const entry=this._extensionInfo[index];const entryType=EntryType.ExtensionEvent;const allThreads=[].concat(...entry.model.sortedProcesses().map(process=>process.sortedThreads()));if(!allThreads.length){return;}
const singleTrack=allThreads.length===1&&(!allThreads[0].events().length||!allThreads[0].asyncEvents().length);if(!singleTrack){this._appendHeader(entry.title,this._headerLevel1,false);}
const style=singleTrack?this._headerLevel2:this._headerLevel1;let threadIndex=0;for(const thread of allThreads){const title=singleTrack?entry.title:thread.name()||ls`Thread ${++threadIndex}`;this._appendAsyncEventsGroup(null,title,thread.asyncEvents(),style,entryType,false);this._appendSyncEvents(null,thread.events(),title,style,entryType,false);}}
_appendHeader(title,style,selectable){const group={startLevel:this._currentLevel,name:title,style:style,selectable:selectable};this._timelineData.groups.push(group);return group;}
_appendEvent(event,level){const index=this._entryData.length;this._entryData.push(event);this._timelineData.entryLevels[index]=level;this._timelineData.entryTotalTimes[index]=event.duration||InstantEventVisibleDurationMs;this._timelineData.entryStartTimes[index]=event.startTime;event[indexSymbol]=index;return index;}
_appendAsyncEvent(asyncEvent,level){if(TracingModel.TracingModel.isNestableAsyncPhase(asyncEvent.phase)){this._appendEvent(asyncEvent,level);return;}
const steps=asyncEvent.steps;const eventOffset=steps.length>1&&steps[1].phase===TracingModel.Phase.AsyncStepPast?1:0;for(let i=0;i<steps.length-1;++i){const index=this._entryData.length;this._entryData.push(steps[i+eventOffset]);const 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){const timelineData=this._timelineData;function pushStartFlow(event){const 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 TracingModel.Phase.FlowBegin:this._flowEventIndexById.set(event.id,pushStartFlow(event));break;case TracingModel.Phase.FlowStep:pushEndFlow(event,this._flowEventIndexById.get(event.id));this._flowEventIndexById.set(event.id,pushStartFlow(event));break;case TracingModel.Phase.FlowEnd:pushEndFlow(event,this._flowEventIndexById.get(event.id));this._flowEventIndexById.delete(event.id);break;}}
_appendFrame(frame){const 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;}
createSelection(entryIndex){const type=this._entryType(entryIndex);let timelineSelection=null;if(type===EntryType.Event){timelineSelection=TimelineSelection.fromTraceEvent((this._entryData[entryIndex]));}else if(type===EntryType.Frame){timelineSelection=TimelineSelection.fromFrame((this._entryData[entryIndex]));}
if(timelineSelection){this._lastSelection=new Selection(timelineSelection,entryIndex);}
return timelineSelection;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
canJumpToEntry(entryIndex){return false;}
entryIndexForSelection(selection){if(!selection||selection.type()===TimelineSelection.Type.Range){return-1;}
if(this._lastSelection&&this._lastSelection.timelineSelection.object()===selection.object()){return this._lastSelection.entryIndex;}
const index=this._entryData.indexOf((selection.object()));if(index!==-1){this._lastSelection=new Selection(selection,index);}
return index;}
buildFlowForInitiator(entryIndex){if(this._lastInitiatorEntry===entryIndex){return false;}
this._lastInitiatorEntry=entryIndex;let event=this.eventByIndex(entryIndex);const td=this._timelineData;td.flowStartTimes=[];td.flowStartLevels=[];td.flowEndTimes=[];td.flowEndLevels=[];while(event){let initiator;for(;event;event=this._eventParent(event)){initiator=TimelineModel.TimelineData.forEvent(event).initiator();if(initiator){break;}}
if(!initiator){break;}
const eventIndex=event[indexSymbol];const initiatorIndex=initiator[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[indexSymbol]]||null;}
eventByIndex(entryIndex){return entryIndex>=0&&this._entryType(entryIndex)===EntryType.Event?(this._entryData[entryIndex]):null;}
setEventColorMapping(colorForEvent){this._colorForEvent=colorForEvent;}}
const InstantEventVisibleDurationMs=0.001;const indexSymbol=Symbol('index');const Events={DataChanged:Symbol('DataChanged')};const EntryType={Frame:Symbol('Frame'),Event:Symbol('Event'),InteractionRecord:Symbol('InteractionRecord'),ExtensionEvent:Symbol('ExtensionEvent'),Screenshot:Symbol('Screenshot'),};var TimelineFlameChartDataProvider$1=Object.freeze({__proto__:null,TimelineFlameChartDataProvider:TimelineFlameChartDataProvider,InstantEventVisibleDurationMs:InstantEventVisibleDurationMs,indexSymbol:indexSymbol,Events:Events,EntryType:EntryType});class TimelineFlameChartNetworkDataProvider{constructor(){this._font='11px '+Platform$1.fontFamily();this.setModel(null);this._style={padding:4,height:17,collapsible:true,color:self.UI.themeSupport.patchColorText('#222',UIUtils.ThemeSupport.ColorUsage.Foreground),font:this._font,backgroundColor:self.UI.themeSupport.patchColorText('white',UIUtils.ThemeSupport.ColorUsage.Background),nestingLevel:0,useFirstLineForOverview:false,useDecoratorsForOverview:true,shareHeaderLine:false};this._group={startLevel:0,name:UIString.UIString('Network'),expanded:false,style:this._style};this._minimumBoundary=0;this._maximumBoundary=0;this._timeSpan=0;}
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 FlameChart.TimelineData([],[],[],[]);if(this._model){this._appendTimelineData();}
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;}
const request=this._requests[index];this._lastSelection=new Selection(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()!==TimelineSelection.Type.NetworkRequest){return-1;}
const request=(selection.object());const index=this._requests.indexOf(request);if(index!==-1){this._lastSelection=new Selection(TimelineSelection.fromNetworkRequest(request),index);}
return index;}
entryColor(index){const request=(this._requests[index]);const category=TimelineUIUtils.networkRequestCategory(request);return TimelineUIUtils.networkCategoryColor(category);}
textColor(index){return FlameChartStyle.textColor;}
entryTitle(index){const request=(this._requests[index]);const parsedURL=new ParsedURL.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){const request=(this._requests[index]);if(!request.timing){return false;}
const beginTime=request.beginTime();const timeToPixel=time=>Math.floor(unclippedBarX+(time-beginTime)*timeToPixelRatio);const minBarWidthPx=2;const startTime=request.getStartTime();const endTime=request.endTime;const{sendStartTime,headersEndTime}=request.getSendReceiveTiming();const sendStart=Math.max(timeToPixel(sendStartTime),unclippedBarX);const headersEnd=Math.max(timeToPixel(headersEndTime),sendStart);const finish=Math.max(timeToPixel(request.finishTime||endTime),headersEnd+minBarWidthPx);const start=timeToPixel(startTime);const 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=self.UI.themeSupport.patchColorText('white',UIUtils.ThemeSupport.ColorUsage.Background);context.fillRect(barX,barY-0.5,sendStart-barX,barHeight);context.fillRect(finish,barY-0.5,barX+barWidth-finish,barHeight);if(!request.cached()&&request.timing.pushStart){const pushStart=timeToPixel(request.timing.pushStart*1000);const pushEnd=request.timing.pushEnd?timeToPixel(request.timing.pushEnd*1000):start;const dentSize=NumberUtilities.clamp(pushEnd-pushStart-2,0,4);const padding=1;context.save();context.beginPath();context.moveTo(pushStart+dentSize,barY+barHeight/2);context.lineTo(pushStart,barY+padding);context.lineTo(pushEnd-dentSize,barY+padding);context.lineTo(pushEnd,barY+barHeight/2);context.lineTo(pushEnd-dentSize,barY+barHeight-padding);context.lineTo(pushStart,barY+barHeight-padding);context.closePath();if(request.timing.pushEnd){context.fillStyle=this.entryColor(index);}else{const gradient=context.createLinearGradient(pushStart,0,pushEnd,0);gradient.addColorStop(0,this.entryColor(index));gradient.addColorStop(1,'white');context.fillStyle=gradient;}
context.globalAlpha=0.3;context.fill();context.restore();}
function drawTick(begin,end,y){const tickHeightPx=6;context.moveTo(begin,y-tickHeightPx/2);context.lineTo(begin,y+tickHeightPx/2);context.moveTo(begin,y);context.lineTo(end,y);}
context.beginPath();context.lineWidth=1;context.strokeStyle='#ccc';const lineY=Math.floor(barY+barHeight/2)+0.5;const leftTick=start+0.5;const rightTick=end-0.5;drawTick(leftTick,sendStart,lineY);drawTick(rightTick,finish,lineY);context.stroke();if(typeof request.priority==='string'){const color=this._colorForPriority(request.priority);if(color){context.fillStyle=color;context.fillRect(sendStart+0.5,barY+0.5,3.5,3.5);}}
const textStart=Math.max(sendStart,0);const textWidth=finish-textStart;const minTextWidthPx=20;if(textWidth>=minTextWidthPx){text=this.entryTitle(index)||'';if(request.fromServiceWorker){text='⚙ '+text;}
if(text){const textPadding=4;const textBaseline=5;const textBaseHeight=barHeight-textBaseline;const trimmedText=UIUtils.trimTextEnd(context,text,textWidth-2*textPadding);context.fillStyle='#333';context.fillText(trimmedText,textStart+textPadding,barY+textBaseHeight);}}
return true;}
forceDecoration(index){return true;}
prepareHighlightedEntryInfo(index){const maxURLChars=80;const request=(this._requests[index]);if(!request.url){return null;}
const element=createElement('div');const root=Utils.createShadowRootWithCoreStyles(element,'timeline/timelineFlamechartPopover.css');const contents=root.createChild('div','timeline-flamechart-popover');const startTime=request.getStartTime();const duration=request.endTime-startTime;if(startTime&&isFinite(duration)){contents.createChild('span','timeline-info-network-time').textContent=Number.millisToString(duration,true);}
if(typeof request.priority==='string'){const div=contents.createChild('span');div.textContent=NetworkPriorities.uiLabelForNetworkPriority((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){const priorities=Protocol.Network.ResourcePriority;this._priorityToValue=new Map([[priorities.VeryLow,1],[priorities.Low,2],[priorities.Medium,3],[priorities.High,4],[priorities.VeryHigh,5]]);}
const value=this._priorityToValue.get(priority);return value?`hsla(214, 80%, 50%, ${value / 5})`:null;}
_appendTimelineData(){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;}
const lastTimeByLevel=[];let maxLevel=0;for(let i=0;i<this._requests.length;++i){const r=this._requests[i];const beginTime=r.beginTime();const visible=beginTime<this._endTime&&r.endTime>this._startTime;if(!visible){this._timelineData.entryLevels[i]=-1;continue;}
while(lastTimeByLevel.length&&lastTimeByLevel.peekLast()<=beginTime){lastTimeByLevel.pop();}
this._timelineData.entryLevels[i]=lastTimeByLevel.length;lastTimeByLevel.push(r.endTime);maxLevel=Math.max(maxLevel,lastTimeByLevel.length);}
for(let i=0;i<this._requests.length;++i){if(this._timelineData.entryLevels[i]===-1){this._timelineData.entryLevels[i]=maxLevel;}}
this._timelineData=new 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.beginTime());this._timelineData.entryTotalTimes.push(request.endTime-request.beginTime());this._timelineData.entryLevels.push(this._requests.length-1);}
preferredHeight(){return this._style.height*(this._group.expanded?NumberUtilities.clamp(this._maxLevel+1,4,8.5):1);}
isExpanded(){return this._group.expanded;}
formatValue(value,precision){return Number.preciseMillisToString(value,precision);}
canJumpToEntry(entryIndex){return false;}}
var TimelineFlameChartNetworkDataProvider$1=Object.freeze({__proto__:null,TimelineFlameChartNetworkDataProvider:TimelineFlameChartNetworkDataProvider});class TimelineFlameChartView extends Widget.VBox{constructor(delegate){super();this.element.classList.add('timeline-flamechart');this._delegate=delegate;this._model=null;this._searchResults;this._eventListeners=[];this._showMemoryGraphSetting=Settings.Settings.instance().createSetting('timelineShowMemory',false);this._networkSplitWidget=new SplitWidget.SplitWidget(false,false,'timelineFlamechartMainView',150);const mainViewGroupExpansionSetting=Settings.Settings.instance().createSetting('timelineFlamechartMainViewGroupExpansion',{});this._mainDataProvider=new TimelineFlameChartDataProvider();this._mainDataProvider.addEventListener(Events.DataChanged,()=>this._mainFlameChart.scheduleUpdate());this._mainFlameChart=new FlameChart.FlameChart(this._mainDataProvider,this,mainViewGroupExpansionSetting);this._mainFlameChart.alwaysShowVerticalScroll();this._mainFlameChart.enableRuler(false);this._networkFlameChartGroupExpansionSetting=Settings.Settings.instance().createSetting('timelineFlamechartNetworkViewGroupExpansion',{});this._networkDataProvider=new TimelineFlameChartNetworkDataProvider();this._networkFlameChart=new FlameChart.FlameChart(this._networkDataProvider,this,this._networkFlameChartGroupExpansionSetting);this._networkFlameChart.alwaysShowVerticalScroll();this._networkFlameChart.disableRangeSelection();this._networkPane=new Widget.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 SplitWidget.SplitWidget(false,true,'timelineCountersSplitViewState');this._countersView=new 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 SplitWidget.SplitWidget(false,true,'timelinePanelDetailsSplitViewState');this._detailsSplitWidget.element.classList.add('timeline-details-split');this._detailsView=new TimelineDetailsView(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(FlameChart.Events.EntrySelected,this._onMainEntrySelected,this);this._mainFlameChart.addEventListener(FlameChart.Events.EntryInvoked,this._onMainEntrySelected,this);this._networkFlameChart.addEventListener(FlameChart.Events.EntrySelected,this._onNetworkEntrySelected,this);this._networkFlameChart.addEventListener(FlameChart.Events.EntryInvoked,this._onNetworkEntrySelected,this);this._mainFlameChart.addEventListener(FlameChart.Events.EntryHighlighted,this._onEntryHighlighted,this);this._nextExtensionIndex=0;this._boundRefresh=this._refresh.bind(this);this._selectedTrack=null;this._mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor);this._groupBySetting=Settings.Settings.instance().createSetting('timelineTreeGroupBy',AggregatedTimelineTreeView.GroupBy.None);this._groupBySetting.addChangeListener(this._updateColorMapper,this);this._updateColorMapper();}
_updateColorMapper(){this._urlToColorCache=new Map();if(!this._model){return;}
this._mainDataProvider.setEventColorMapping(TimelineUIUtils.eventColor);this._mainFlameChart.update();}
_onWindowChanged(event){const window=(event.data.window);const animate=!!event.data.animate;this._mainFlameChart.setWindowTimes(window.left,window.right,animate);this._networkFlameChart.setWindowTimes(window.left,window.right,animate);this._networkDataProvider.setWindowTimes(window.left,window.right);this._updateSearchResults(false,false);}
windowChanged(windowStartTime,windowEndTime,animate){this._model.setWindow({left:windowStartTime,right:windowEndTime},animate);}
updateRangeSelection(startTime,endTime){this._delegate.select(TimelineSelection.fromRange(startTime,endTime));}
updateSelectedGroup(flameChart,group){if(flameChart!==this._mainFlameChart){return;}
const track=group?this._mainDataProvider.groupTrack(group):null;this._selectedTrack=track;this._updateTrack();}
setModel(model){if(model===this._model){return;}
EventTarget.EventTarget.removeEventListeners(this._eventListeners);this._model=model;this._selectedTrack=null;this._mainDataProvider.setModel(this._model);this._networkDataProvider.setModel(this._model);if(this._model){this._eventListeners=[this._model.addEventListener(Events$1.WindowChanged,this._onWindowChanged,this),this._model.addEventListener(Events$1.ExtensionDataAdded,this._appendExtensionData,this)];const window=model.window();this._mainFlameChart.setWindowTimes(window.left,window.right);this._networkFlameChart.setWindowTimes(window.left,window.right);this._networkDataProvider.setWindowTimes(window.left,window.right);this._updateSearchResults(false,false);}
this._updateColorMapper();this._updateTrack();this._nextExtensionIndex=0;this._appendExtensionData();this._refresh();}
_updateTrack(){this._countersView.setModel(this._model,this._selectedTrack);this._detailsView.setModel(this._model,this._selectedTrack);}
_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();this._updateSearchResults(false,false);}
_appendExtensionData(){if(!this._model){return;}
const extensions=this._model.extensionInfo();while(this._nextExtensionIndex<extensions.length){this._mainDataProvider.appendExtensionEvents(extensions[this._nextExtensionIndex++]);}
this._mainFlameChart.scheduleUpdate();}
_onEntryHighlighted(commonEvent){OverlayModel.OverlayModel.hideDOMNodeHighlight();const entryIndex=(commonEvent.data);const event=this._mainDataProvider.eventByIndex(entryIndex);if(!event){return;}
const target=this._model&&this._model.timelineModel().targetByEvent(event);if(!target){return;}
const timelineData=TimelineModel.TimelineData.forEvent(event);const backendNodeId=timelineData.backendNodeId;if(!backendNodeId){return;}
new DOMModel.DeferredDOMNode(target,backendNodeId).highlight();}
highlightEvent(event){const entryIndex=event?this._mainDataProvider.entryIndexForSelection(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);BlackboxManager.BlackboxManager.instance().removeChangeListener(this._boundRefresh);}
wasShown(){this._networkFlameChartGroupExpansionSetting.addChangeListener(this.resizeToPreferredHeights,this);this._showMemoryGraphSetting.addChangeListener(this._updateCountersGraphToggle,this);BlackboxManager.BlackboxManager.instance().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();}}
setSelection(selection){let index=this._mainDataProvider.entryIndexForSelection(selection);this._mainFlameChart.setSelectedEntry(index);index=this._networkDataProvider.entryIndexForSelection(selection);this._networkFlameChart.setSelectedEntry(index);if(this._detailsView){this._detailsView.setSelection(selection);}}
_onEntrySelected(dataProvider,event){const entryIndex=(event.data);if(Root.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+FlameChart.HeaderHeight+
2);}
setSearchableView(searchableView){this._searchableView=searchableView;}
jumpToNextSearchResult(){if(!this._searchResults||!this._searchResults.length){return;}
const index=typeof this._selectedSearchResult!=='undefined'?this._searchResults.indexOf(this._selectedSearchResult):-1;this._selectSearchResult(NumberUtilities.mod(index+1,this._searchResults.length));}
jumpToPreviousSearchResult(){if(!this._searchResults||!this._searchResults.length){return;}
const index=typeof this._selectedSearchResult!=='undefined'?this._searchResults.indexOf(this._selectedSearchResult):0;this._selectSearchResult(NumberUtilities.mod(index-1,this._searchResults.length));}
supportsCaseSensitiveSearch(){return true;}
supportsRegexSearch(){return true;}
_selectSearchResult(index){this._searchableView.updateCurrentMatchIndex(index);this._selectedSearchResult=this._searchResults[index];this._delegate.select(this._mainDataProvider.createSelection(this._selectedSearchResult));}
_updateSearchResults(shouldJump,jumpBackwards){const oldSelectedSearchResult=this._selectedSearchResult;delete this._selectedSearchResult;this._searchResults=[];if(!this._searchRegex||!this._model){return;}
const regExpFilter=new TimelineRegExp(this._searchRegex);const window=this._model.window();this._searchResults=this._mainDataProvider.search(window.left,window.right,regExpFilter);this._searchableView.updateSearchMatchesCount(this._searchResults.length);if(!shouldJump||!this._searchResults.length){return;}
let selectedIndex=this._searchResults.indexOf(oldSelectedSearchResult);if(selectedIndex===-1){selectedIndex=jumpBackwards?this._searchResults.length-1:0;}
this._selectSearchResult(selectedIndex);}
searchCanceled(){if(typeof this._selectedSearchResult!=='undefined'){this._delegate.select(null);}
delete this._searchResults;delete this._selectedSearchResult;delete this._searchRegex;}
performSearch(searchConfig,shouldJump,jumpBackwards){this._searchRegex=searchConfig.toSearchRegex();this._updateSearchResults(shouldJump,jumpBackwards);}}
class Selection{constructor(selection,entryIndex){this.timelineSelection=selection;this.entryIndex=entryIndex;}}
const FlameChartStyle={textColor:'#333'};class TimelineFlameChartMarker{constructor(startTime,startOffset,style){this._startTime=startTime;this._startOffset=startOffset;this._style=style;}
startTime(){return this._startTime;}
color(){return this._style.color;}
title(){if(this._style.lowPriority){return null;}
const startTime=Number.millisToString(this._startOffset);return ls`${this._style.title} at ${startTime}`;}
draw(context,x,height,pixelsPerMillisecond){const lowPriorityVisibilityThresholdInPixelsPerMs=4;if(this._style.lowPriority&&pixelsPerMillisecond<lowPriorityVisibilityThresholdInPixelsPerMs){return;}
context.save();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,0);context.setLineDash(this._style.dashStyle);context.lineTo(x,context.canvas.height);context.stroke();}
context.restore();}}
const ColorBy={URL:'URL',};var TimelineFlameChartView$1=Object.freeze({__proto__:null,TimelineFlameChartView:TimelineFlameChartView,Selection:Selection,FlameChartStyle:FlameChartStyle,TimelineFlameChartMarker:TimelineFlameChartMarker,ColorBy:ColorBy});class TimelineHistoryManager{constructor(){this._recordings=[];this._action=(self.UI.actionRegistry.action('timeline.show-history'));this._nextNumberByDomain=new Map();this._button=new ToolbarButton(this._action);ARIAUtils.markAsMenuButton(this._button.element);this.clear();this._allOverviews=[{constructor:TimelineEventOverviewResponsiveness,height:3},{constructor:TimelineEventOverviewFrames,height:16},{constructor:TimelineEventOverviewCPUActivity,height:20},{constructor:TimelineEventOverviewNetwork,height:8}];this._totalHeight=this._allOverviews.reduce((acc,entry)=>acc+entry.height,0);this._enabled=true;this._lastActiveModel=null;}
addRecording(performanceModel){this._lastActiveModel=performanceModel;this._recordings.unshift(performanceModel);this._buildPreview(performanceModel);const modelTitle=this._title(performanceModel);this._button.setText(modelTitle);const buttonTitle=this._action.title();ARIAUtils.setAccessibleName(this._button.element,ls`Current Session: ${modelTitle}. ${buttonTitle}`);this._updateState();if(this._recordings.length<=maxRecordings){return;}
const lruModel=this._recordings.reduce((a,b)=>lastUsedTime(a)<lastUsedTime(b)?a:b);this._recordings.splice(this._recordings.indexOf(lruModel),1);lruModel.dispose();function lastUsedTime(model){return TimelineHistoryManager._dataForModel(model).lastUsed;}}
setEnabled(enabled){this._enabled=enabled;this._updateState();}
button(){return this._button;}
clear(){this._recordings.forEach(model=>model.dispose());this._recordings=[];this._lastActiveModel=null;this._updateState();this._button.setText(UIString.UIString('(no recordings)'));this._nextNumberByDomain.clear();}
async showHistoryDropDown(){if(this._recordings.length<2||!this._enabled){return null;}
const model=await DropDown.show(this._recordings,(this._lastActiveModel),this._button.element);if(!model){return null;}
const index=this._recordings.indexOf(model);if(index<0){console.assert(false,'selected recording not found');return null;}
this._setCurrentModel(model);return model;}
cancelIfShowing(){DropDown.cancelIfShowing();}
navigate(direction){if(!this._enabled||!this._lastActiveModel){return null;}
const index=this._recordings.indexOf(this._lastActiveModel);if(index<0){return null;}
const newIndex=NumberUtilities.clamp(index+direction,0,this._recordings.length-1);const model=this._recordings[newIndex];this._setCurrentModel(model);return model;}
_setCurrentModel(model){TimelineHistoryManager._dataForModel(model).lastUsed=Date.now();this._lastActiveModel=model;const modelTitle=this._title(model);const buttonTitle=this._action.title();this._button.setText(modelTitle);ARIAUtils.setAccessibleName(this._button.element,ls`Current Session: ${modelTitle}. ${buttonTitle}`);}
_updateState(){this._action.setEnabled(this._recordings.length>1&&this._enabled);}
static _previewElement(performanceModel){const data=TimelineHistoryManager._dataForModel(performanceModel);const startedAt=performanceModel.recordStartTime();data.time.textContent=startedAt?UIString.UIString('(%s ago)',TimelineHistoryManager._coarseAge(startedAt)):'';return data.preview;}
static _coarseAge(time){const seconds=Math.round((Date.now()-time)/1000);if(seconds<50){return UIString.UIString('moments');}
const minutes=Math.round(seconds/60);if(minutes<50){return UIString.UIString('%s m',minutes);}
const hours=Math.round(minutes/60);return UIString.UIString('%s h',hours);}
_title(performanceModel){return TimelineHistoryManager._dataForModel(performanceModel).title;}
_buildPreview(performanceModel){const parsedURL=ParsedURL.ParsedURL.fromString(performanceModel.timelineModel().pageURL());const domain=parsedURL?parsedURL.host:'';const sequenceNumber=this._nextNumberByDomain.get(domain)||1;const title=UIString.UIString('%s #%d',domain,sequenceNumber);this._nextNumberByDomain.set(domain,sequenceNumber+1);const timeElement=createElement('span');const preview=createElementWithClass('div','preview-item vbox');const data={preview:preview,title:title,time:timeElement,lastUsed:Date.now()};performanceModel[previewDataSymbol]=data;preview.appendChild(this._buildTextDetails(performanceModel,title,timeElement));const screenshotAndOverview=preview.createChild('div','hbox');screenshotAndOverview.appendChild(this._buildScreenshotThumbnail(performanceModel));screenshotAndOverview.appendChild(this._buildOverview(performanceModel));return data.preview;}
_buildTextDetails(performanceModel,title,timeElement){const container=createElementWithClass('div','text-details hbox');const nameSpan=container.createChild('span','name');nameSpan.textContent=title;ARIAUtils.setAccessibleName(nameSpan,title);const tracingModel=performanceModel.tracingModel();const duration=Number.millisToString(tracingModel.maximumRecordTime()-tracingModel.minimumRecordTime(),false);const timeContainer=container.createChild('span','time');timeContainer.appendChild(createTextNode(duration));timeContainer.appendChild(timeElement);return container;}
_buildScreenshotThumbnail(performanceModel){const container=createElementWithClass('div','screenshot-thumb');const thumbnailAspectRatio=3/2;container.style.width=this._totalHeight*thumbnailAspectRatio+'px';container.style.height=this._totalHeight+'px';const filmStripModel=performanceModel.filmStripModel();const lastFrame=filmStripModel.frames().peekLast();if(!lastFrame){return container;}
lastFrame.imageDataPromise().then(data=>UIUtils.loadImageFromData(data)).then(image=>image&&container.appendChild(image));return container;}
_buildOverview(performanceModel){const container=createElement('div');container.style.width=previewWidth+'px';container.style.height=this._totalHeight+'px';const canvas=container.createChild('canvas');canvas.width=window.devicePixelRatio*previewWidth;canvas.height=window.devicePixelRatio*this._totalHeight;const ctx=canvas.getContext('2d');let yOffset=0;for(const overview of this._allOverviews){const timelineOverview=new overview.constructor();timelineOverview.setCanvasSize(previewWidth,overview.height);timelineOverview.setModel(performanceModel);timelineOverview.update();const sourceContext=timelineOverview.context();const imageData=sourceContext.getImageData(0,0,sourceContext.canvas.width,sourceContext.canvas.height);ctx.putImageData(imageData,0,yOffset);yOffset+=overview.height*window.devicePixelRatio;}
return container;}
static _dataForModel(model){return model[previewDataSymbol]||null;}}
const maxRecordings=5;const previewWidth=450;const previewDataSymbol=Symbol('previewData');class DropDown{constructor(models){this._glassPane=new GlassPane.GlassPane();this._glassPane.setSizeBehavior(GlassPane.SizeBehavior.MeasureContent);this._glassPane.setOutsideClickCallback(()=>this._close(null));this._glassPane.setPointerEventsBehavior(GlassPane.PointerEventsBehavior.BlockedByGlassPane);this._glassPane.setAnchorBehavior(GlassPane.AnchorBehavior.PreferBottom);this._glassPane.element.addEventListener('blur',()=>this._close(null));const shadowRoot=Utils.createShadowRootWithCoreStyles(this._glassPane.contentElement,'timeline/timelineHistoryManager.css');const contentElement=shadowRoot.createChild('div','drop-down');const listModel=new ListModel.ListModel();this._listControl=new ListControl.ListControl(listModel,this,ListControl.ListMode.NonViewport);this._listControl.element.addEventListener('mousemove',this._onMouseMove.bind(this),false);listModel.replaceAll(models);ARIAUtils.markAsMenu(this._listControl.element);ARIAUtils.setAccessibleName(this._listControl.element,ls`Select Timeline Session`);contentElement.appendChild(this._listControl.element);contentElement.addEventListener('keydown',this._onKeyDown.bind(this),false);contentElement.addEventListener('click',this._onClick.bind(this),false);this._focusRestorer=new UIUtils.ElementFocusRestorer(this._listControl.element);this._selectionDone=null;}
static show(models,currentModel,anchor){if(DropDown._instance){return Promise.resolve((null));}
const instance=new DropDown(models);return instance._show(anchor,currentModel);}
static cancelIfShowing(){if(!DropDown._instance){return;}
DropDown._instance._close(null);}
_show(anchor,currentModel){DropDown._instance=this;this._glassPane.setContentAnchorBox(anchor.boxInWindow());this._glassPane.show((this._glassPane.contentElement.ownerDocument));this._listControl.element.focus();this._listControl.selectItem(currentModel);return new Promise(fulfill=>this._selectionDone=fulfill);}
_onMouseMove(event){const node=event.target.enclosingNodeOrSelfWithClass('preview-item');const listItem=node&&this._listControl.itemForNode(node);if(!listItem){return;}
this._listControl.selectItem(listItem);}
_onClick(event){if(!event.target.enclosingNodeOrSelfWithClass('preview-item')){return;}
this._close(this._listControl.selectedItem());}
_onKeyDown(event){switch(event.key){case'Tab':case'Escape':this._close(null);break;case'Enter':this._close(this._listControl.selectedItem());break;default:return;}
event.consume(true);}
_close(model){this._selectionDone(model);this._focusRestorer.restore();this._glassPane.hide();DropDown._instance=null;}
createElementForItem(item){const element=TimelineHistoryManager._previewElement(item);ARIAUtils.markAsMenuItem(element);element.classList.remove('selected');return element;}
heightForItem(item){console.assert(false,'Should not be called');return 0;}
isItemSelectable(item){return true;}
selectedItemChanged(from,to,fromElement,toElement){if(fromElement){fromElement.classList.remove('selected');}
if(toElement){toElement.classList.add('selected');}}
updateSelectedItemARIA(fromElement,toElement){return false;}}
DropDown._instance=null;class ToolbarButton extends Toolbar.ToolbarItem{constructor(action){super(createElementWithClass('button','history-dropdown-button'));Utils.appendStyle(this.element,'timeline/historyToolbarButton.css');this._contentElement=this.element.createChild('span','content');const dropdownArrowIcon=Icon.Icon.create('smallicon-triangle-down');this.element.appendChild(dropdownArrowIcon);this.element.addEventListener('click',()=>void action.execute(),false);this.setEnabled(action.enabled());action.addEventListener(Action.Events.Enabled,event=>this.setEnabled((event.data)));this.setTitle(action.title());}
setText(text){this._contentElement.textContent=text;}}
let PreviewData;var TimelineHistoryManager$1=Object.freeze({__proto__:null,TimelineHistoryManager:TimelineHistoryManager,maxRecordings:maxRecordings,previewWidth:previewWidth,previewDataSymbol:previewDataSymbol,DropDown:DropDown,ToolbarButton:ToolbarButton,PreviewData:PreviewData});class UIDevtoolsUtils{static isUiDevTools(){return Root.Runtime.queryParam('uiDevTools')==='true';}
static categorizeEvents(){if(UIDevtoolsUtils._eventStylesMap){return UIDevtoolsUtils._eventStylesMap;}
const type=RecordType;const categories=UIDevtoolsUtils.categories();const drawing=categories['drawing'];const rasterizing=categories['rasterizing'];const layout=categories['layout'];const painting=categories['painting'];const other=categories['other'];const eventStyles={};eventStyles[type.ViewPaint]=new TimelineRecordStyle(ls`View::Paint`,painting);eventStyles[type.ViewOnPaint]=new TimelineRecordStyle(ls`View::OnPaint`,painting);eventStyles[type.ViewPaintChildren]=new TimelineRecordStyle(ls`View::PaintChildren`,painting);eventStyles[type.ViewOnPaintBackground]=new TimelineRecordStyle(ls`View::OnPaintBackground`,painting);eventStyles[type.ViewOnPaintBorder]=new TimelineRecordStyle(ls`View::OnPaintBorder`,painting);eventStyles[type.LayerPaintContentsToDisplayList]=new TimelineRecordStyle(ls`Layer::PaintContentsToDisplayList`,painting);eventStyles[type.ViewLayout]=new TimelineRecordStyle(ls`View::Layout`,layout);eventStyles[type.ViewLayoutBoundsChanged]=new TimelineRecordStyle(ls`View::Layout(bounds_changed)`,layout);eventStyles[type.RasterTask]=new TimelineRecordStyle(ls`RasterTask`,rasterizing);eventStyles[type.RasterizerTaskImplRunOnWorkerThread]=new TimelineRecordStyle(ls`RasterizerTaskImpl::RunOnWorkerThread`,rasterizing);eventStyles[type.DirectRendererDrawFrame]=new TimelineRecordStyle(ls`DirectRenderer::DrawFrame`,drawing);eventStyles[type.BeginFrame]=new TimelineRecordStyle(ls`Frame Start`,drawing,true);eventStyles[type.DrawFrame]=new TimelineRecordStyle(ls`Draw Frame`,drawing,true);eventStyles[type.NeedsBeginFrameChanged]=new TimelineRecordStyle(ls`NeedsBeginFrameChanged`,drawing,true);eventStyles[type.ThreadControllerImplRunTask]=new TimelineRecordStyle(ls`ThreadControllerImpl::RunTask`,other);UIDevtoolsUtils._eventStylesMap=eventStyles;return eventStyles;}
static categories(){if(UIDevtoolsUtils._categories){return UIDevtoolsUtils._categories;}
UIDevtoolsUtils._categories={layout:new TimelineCategory('layout',ls`Layout`,true,'hsl(214, 67%, 74%)','hsl(214, 67%, 66%)'),rasterizing:new TimelineCategory('rasterizing',ls`Rasterizing`,true,'hsl(43, 83%, 72%)','hsl(43, 83%, 64%) '),drawing:new TimelineCategory('drawing',ls`Drawing`,true,'hsl(256, 67%, 76%)','hsl(256, 67%, 70%)'),painting:new TimelineCategory('painting',ls`Painting`,true,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),other:new TimelineCategory('other',ls`System`,false,'hsl(0, 0%, 87%)','hsl(0, 0%, 79%)'),idle:new TimelineCategory('idle',ls`Idle`,false,'hsl(0, 0%, 98%)','hsl(0, 0%, 98%)')};return UIDevtoolsUtils._categories;}
static getMainCategoriesList(){return['idle','drawing','painting','rasterizing','layout','other'];}}
const RecordType={ViewPaint:'View::Paint',ViewOnPaint:'View::OnPaint',ViewPaintChildren:'View::PaintChildren',ViewOnPaintBackground:'View::OnPaintBackground',ViewOnPaintBorder:'View::OnPaintBorder',ViewLayout:'View::Layout',ViewLayoutBoundsChanged:'View::Layout(bounds_changed)',LayerPaintContentsToDisplayList:'Layer::PaintContentsToDisplayList',DirectRendererDrawFrame:'DirectRenderer::DrawFrame',RasterTask:'RasterTask',RasterizerTaskImplRunOnWorkerThread:'RasterizerTaskImpl::RunOnWorkerThread',BeginFrame:'BeginFrame',DrawFrame:'DrawFrame',NeedsBeginFrameChanged:'NeedsBeginFrameChanged',ThreadControllerImplRunTask:'ThreadControllerImpl::RunTask',};var UIDevtoolsUtils$1=Object.freeze({__proto__:null,UIDevtoolsUtils:UIDevtoolsUtils,RecordType:RecordType});class UIDevtoolsController extends TimelineController{constructor(target,client){super(target,client);TimelineUIUtils.setEventStylesMap(UIDevtoolsUtils.categorizeEvents());TimelineUIUtils.setCategories(UIDevtoolsUtils.categories());TimelineUIUtils.setTimelineMainEventCategories(UIDevtoolsUtils.getMainCategoriesList());}}
var UIDevtoolsController$1=Object.freeze({__proto__:null,UIDevtoolsController:UIDevtoolsController});class TimelinePanel extends Panel.Panel{constructor(){super('timeline');this.registerRequiredCSS('timeline/timelinePanel.css');this.element.addEventListener('contextmenu',this._contextMenu.bind(this),false);this._dropTarget=new DropTarget.DropTarget(this.element,[DropTarget.Type.File,DropTarget.Type.URI],UIString.UIString('Drop timeline file or URL here'),this._handleDrop.bind(this));this._recordingOptionUIControls=[];this._state=State$1.Idle;this._recordingPageReload=false;this._millisecondsToRecordAfterLoadEvent=3000;this._toggleRecordAction=(self.UI.actionRegistry.action('timeline.toggle-recording'));this._recordReloadAction=(self.UI.actionRegistry.action('timeline.record-reload'));this._historyManager=new TimelineHistoryManager();this._performanceModel=null;this._viewModeSetting=Settings.Settings.instance().createSetting('timelineViewMode',ViewMode.FlameChart);this._disableCaptureJSProfileSetting=Settings.Settings.instance().createSetting('timelineDisableJSSampling',false);this._disableCaptureJSProfileSetting.setTitle(UIString.UIString('Disable JavaScript samples'));this._captureLayersAndPicturesSetting=Settings.Settings.instance().createSetting('timelineCaptureLayersAndPictures',false);this._captureLayersAndPicturesSetting.setTitle(UIString.UIString('Enable advanced paint instrumentation (slow)'));this._showScreenshotsSetting=Settings.Settings.instance().createSetting('timelineShowScreenshots',true);this._showScreenshotsSetting.setTitle(UIString.UIString('Screenshots'));this._showScreenshotsSetting.addChangeListener(this._updateOverviewControls,this);this._startCoverage=Settings.Settings.instance().createSetting('timelineStartCoverage',false);this._startCoverage.setTitle(ls`Coverage`);if(!Root.Runtime.experiments.isEnabled('recordCoverageWithPerformanceTracing')){this._startCoverage.set(false);}
this._showMemorySetting=Settings.Settings.instance().createSetting('timelineShowMemory',false);this._showMemorySetting.setTitle(UIString.UIString('Memory'));this._showMemorySetting.addChangeListener(this._onModeChanged,this);const timelineToolbarContainer=this.element.createChild('div','timeline-toolbar-container');this._panelToolbar=new Toolbar.Toolbar('timeline-main-toolbar',timelineToolbarContainer);this._panelRightToolbar=new Toolbar.Toolbar('',timelineToolbarContainer);this._createSettingsPane();this._updateShowSettingsToolbarButton();this._timelinePane=new Widget.VBox();this._timelinePane.show(this.element);const topPaneElement=this._timelinePane.element.createChild('div','hbox');topPaneElement.id='timeline-overview-panel';this._overviewPane=new TimelineOverviewPane.TimelineOverviewPane('timeline');this._overviewPane.addEventListener(TimelineOverviewPane.Events.WindowChanged,this._onOverviewWindowChanged.bind(this));this._overviewPane.show(topPaneElement);this._overviewControls=[];this._statusPaneContainer=this._timelinePane.element.createChild('div','status-pane-container fill');this._createFileSelector();SDKModel.TargetManager.instance().addModelListener(ResourceTreeModel.ResourceTreeModel,ResourceTreeModel.Events.Load,this._loadEventFired,this);this._flameChart=new TimelineFlameChartView(this);this._searchableView=new SearchableView.SearchableView(this._flameChart);this._searchableView.setMinimumSize(0,100);this._searchableView.element.classList.add('searchable-view');this._searchableView.show(this._timelinePane.element);this._flameChart.show(this._searchableView.element);this._flameChart.setSearchableView(this._searchableView);this._searchableView.hideWidget();this._onModeChanged();this._populateToolbar();this._showLandingPage();this._updateTimelineControls();self.Extensions.extensionServer.addEventListener(ExtensionServer.Events.TraceProviderAdded,this._appendExtensionsToToolbar,this);SDKModel.TargetManager.instance().addEventListener(SDKModel.Events.SuspendStateChanged,this._onSuspendStateChanged,this);}
static instance(){return(self.runtime.sharedInstance(TimelinePanel));}
searchableView(){return this._searchableView;}
wasShown(){self.UI.context.setFlavor(TimelinePanel,this);userMetrics.panelLoaded('timeline','DevTools.Launch.Timeline');}
willHide(){self.UI.context.setFlavor(TimelinePanel,null);this._historyManager.cancelIfShowing();}
loadFromEvents(events){if(this._state!==State$1.Idle){return;}
this._prepareToLoadTimeline();this._loader=TimelineLoader.loadFromEvents(events,this);}
_onOverviewWindowChanged(event){const left=event.data.startTime;const right=event.data.endTime;this._performanceModel.setWindow({left,right},true);}
_onModelWindowChanged(event){const window=(event.data.window);this._overviewPane.setWindowTimes(window.left,window.right);}
_setState(state){this._state=state;this._updateTimelineControls();}
_createSettingCheckbox(setting,tooltip){const checkboxItem=new Toolbar.ToolbarSettingCheckbox(setting,tooltip);this._recordingOptionUIControls.push(checkboxItem);return checkboxItem;}
_populateToolbar(){this._panelToolbar.appendToolbarItem(Toolbar.Toolbar.createActionButton(this._toggleRecordAction));this._panelToolbar.appendToolbarItem(Toolbar.Toolbar.createActionButton(this._recordReloadAction));this._clearButton=new Toolbar.ToolbarButton(UIString.UIString('Clear'),'largeicon-clear');this._clearButton.addEventListener(Toolbar.ToolbarButton.Events.Click,()=>this._onClearButton());this._panelToolbar.appendToolbarItem(this._clearButton);this._loadButton=new Toolbar.ToolbarButton(UIString.UIString('Load profile…'),'largeicon-load');this._loadButton.addEventListener(Toolbar.ToolbarButton.Events.Click,()=>this._selectFileToLoad());this._saveButton=new Toolbar.ToolbarButton(UIString.UIString('Save profile…'),'largeicon-download');this._saveButton.addEventListener(Toolbar.ToolbarButton.Events.Click,event=>{this._saveToFile();});this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._loadButton);this._panelToolbar.appendToolbarItem(this._saveButton);this._panelToolbar.appendSeparator();this._panelToolbar.appendToolbarItem(this._historyManager.button());this._panelToolbar.appendSeparator();this._panelToolbar.appendSeparator();this._showScreenshotsToolbarCheckbox=this._createSettingCheckbox(this._showScreenshotsSetting,UIString.UIString('Capture screenshots'));this._panelToolbar.appendToolbarItem(this._showScreenshotsToolbarCheckbox);this._showMemoryToolbarCheckbox=this._createSettingCheckbox(this._showMemorySetting,UIString.UIString('Show memory timeline'));this._panelToolbar.appendToolbarItem(this._showMemoryToolbarCheckbox);if(Root.Runtime.experiments.isEnabled('recordCoverageWithPerformanceTracing')){this._startCoverageCheckbox=this._createSettingCheckbox(this._startCoverage,ls`Record coverage with performance trace`);this._panelToolbar.appendToolbarItem(this._startCoverageCheckbox);}
this._panelToolbar.appendToolbarItem(Toolbar.Toolbar.createActionButtonForId('components.collect-garbage'));this._panelRightToolbar.appendSeparator();this._panelRightToolbar.appendToolbarItem(this._showSettingsPaneButton);}
_createSettingsPane(){this._showSettingsPaneSetting=Settings.Settings.instance().createSetting('timelineShowSettingsToolbar',false);this._showSettingsPaneButton=new Toolbar.ToolbarSettingToggle(this._showSettingsPaneSetting,'largeicon-settings-gear',UIString.UIString('Capture settings'));self.SDK.multitargetNetworkManager.addEventListener(NetworkManager.MultitargetNetworkManager.Events.ConditionsChanged,this._updateShowSettingsToolbarButton,this);ThrottlingManager.throttlingManager().addEventListener(ThrottlingManager.Events.RateChanged,this._updateShowSettingsToolbarButton,this);this._disableCaptureJSProfileSetting.addChangeListener(this._updateShowSettingsToolbarButton,this);this._captureLayersAndPicturesSetting.addChangeListener(this._updateShowSettingsToolbarButton,this);this._settingsPane=new Widget.HBox();this._settingsPane.element.classList.add('timeline-settings-pane');this._settingsPane.show(this.element);const captureToolbar=new Toolbar.Toolbar('',this._settingsPane.element);captureToolbar.element.classList.add('flex-auto');captureToolbar.makeVertical();captureToolbar.appendToolbarItem(this._createSettingCheckbox(this._disableCaptureJSProfileSetting,UIString.UIString('Disables JavaScript sampling, reduces overhead when running against mobile devices')));captureToolbar.appendToolbarItem(this._createSettingCheckbox(this._captureLayersAndPicturesSetting,UIString.UIString('Captures advanced paint instrumentation, introduces significant performance overhead')));const throttlingPane=new Widget.VBox();throttlingPane.element.classList.add('flex-auto');throttlingPane.show(this._settingsPane.element);const networkThrottlingToolbar=new Toolbar.Toolbar('',throttlingPane.element);networkThrottlingToolbar.appendText(UIString.UIString('Network:'));this._networkThrottlingSelect=this._createNetworkConditionsSelect();networkThrottlingToolbar.appendToolbarItem(this._networkThrottlingSelect);const cpuThrottlingToolbar=new Toolbar.Toolbar('',throttlingPane.element);cpuThrottlingToolbar.appendText(UIString.UIString('CPU:'));this._cpuThrottlingSelect=ThrottlingManager.throttlingManager().createCPUThrottlingSelector();cpuThrottlingToolbar.appendToolbarItem(this._cpuThrottlingSelect);this._showSettingsPaneSetting.addChangeListener(this._updateSettingsPaneVisibility.bind(this));this._updateSettingsPaneVisibility();}
_appendExtensionsToToolbar(event){const provider=(event.data);const setting=TimelinePanel._settingForTraceProvider(provider);const checkbox=this._createSettingCheckbox(setting,provider.longDisplayName());this._panelToolbar.appendToolbarItem(checkbox);}
static _settingForTraceProvider(traceProvider){let setting=traceProvider[traceProviderSettingSymbol];if(!setting){const providerId=traceProvider.persistentIdentifier();setting=Settings.Settings.instance().createSetting(providerId,false);setting.setTitle(traceProvider.shortDisplayName());traceProvider[traceProviderSettingSymbol]=setting;}
return setting;}
_createNetworkConditionsSelect(){const toolbarItem=new Toolbar.ToolbarComboBox(null,ls`Network conditions`);toolbarItem.setMaxWidth(140);ThrottlingManager.throttlingManager().decorateSelectWithNetworkThrottling(toolbarItem.selectElement());return toolbarItem;}
_prepareToLoadTimeline(){console.assert(this._state===State$1.Idle);this._setState(State$1.Loading);if(this._performanceModel){this._performanceModel.dispose();this._performanceModel=null;}}
_createFileSelector(){if(this._fileSelectorElement){this._fileSelectorElement.remove();}
this._fileSelectorElement=UIUtils.createFileSelectorElement(this._loadFromFile.bind(this));this._timelinePane.element.appendChild(this._fileSelectorElement);}
_contextMenu(event){const contextMenu=new ContextMenu.ContextMenu(event);contextMenu.appendItemsAtLocation('timelineMenu');contextMenu.show();}
async _saveToFile(){if(this._state!==State$1.Idle){return;}
const performanceModel=this._performanceModel;if(!performanceModel){return;}
const now=new Date();const fileName='Profile-'+now.toISO8601Compact()+'.json';const stream=new FileUtils.FileOutputStream();const accepted=await stream.open(fileName);if(!accepted){return;}
const error=await performanceModel.save(stream);if(!error){return;}
Console.Console.instance().error(UIString.UIString('Failed to save timeline: %s (%s, %s)',error.message,error.name,error.code));}
async _showHistory(){const model=await this._historyManager.showHistoryDropDown();if(model&&model!==this._performanceModel){this._setModel(model);}}
_navigateHistory(direction){const model=this._historyManager.navigate(direction);if(model&&model!==this._performanceModel){this._setModel(model);}
return true;}
_selectFileToLoad(){this._fileSelectorElement.click();}
_loadFromFile(file){if(this._state!==State$1.Idle){return;}
this._prepareToLoadTimeline();this._loader=TimelineLoader.loadFromFile(file,this);this._createFileSelector();}
_loadFromURL(url){if(this._state!==State$1.Idle){return;}
this._prepareToLoadTimeline();this._loader=TimelineLoader.loadFromURL(url,this);}
_updateOverviewControls(){this._overviewControls=[];this._overviewControls.push(new TimelineEventOverviewResponsiveness());if(Root.Runtime.experiments.isEnabled('inputEventsOnTimelineOverview')){this._overviewControls.push(new TimelineEventOverviewInput());}
this._overviewControls.push(new TimelineEventOverviewFrames());this._overviewControls.push(new TimelineEventOverviewCPUActivity());this._overviewControls.push(new TimelineEventOverviewNetwork());if(this._showScreenshotsSetting.get()&&this._performanceModel&&this._performanceModel.filmStripModel().frames().length){this._overviewControls.push(new TimelineFilmStripOverview());}
if(this._showMemorySetting.get()){this._overviewControls.push(new TimelineEventOverviewMemory());}
if(this._startCoverage.get()){this._overviewControls.push(new TimelineEventOverviewCoverage());}
for(const control of this._overviewControls){control.setModel(this._performanceModel);}
this._overviewPane.setOverviewControls(this._overviewControls);}
_onModeChanged(){this._updateOverviewControls();this.doResize();this.select(null);}
_updateSettingsPaneVisibility(){if(this._showSettingsPaneSetting.get()){this._settingsPane.showWidget();}else{this._settingsPane.hideWidget();}}
_updateShowSettingsToolbarButton(){const messages=[];if(ThrottlingManager.throttlingManager().cpuThrottlingRate()!==1){messages.push(UIString.UIString('- CPU throttling is enabled'));}
if(self.SDK.multitargetNetworkManager.isThrottling()){messages.push(UIString.UIString('- Network throttling is enabled'));}
if(this._captureLayersAndPicturesSetting.get()){messages.push(UIString.UIString('- Significant overhead due to paint instrumentation'));}
if(this._disableCaptureJSProfileSetting.get()){messages.push(UIString.UIString('- JavaScript sampling is disabled'));}
this._showSettingsPaneButton.setDefaultWithRedColor(messages.length);this._showSettingsPaneButton.setToggleWithRedColor(messages.length);if(messages.length){const tooltipElement=createElement('div');messages.forEach(message=>{tooltipElement.createChild('div').textContent=message;});this._showSettingsPaneButton.setTitle(tooltipElement);}else{this._showSettingsPaneButton.setTitle(UIString.UIString('Capture settings'));}}
_setUIControlsEnabled(enabled){this._recordingOptionUIControls.forEach(control=>control.setEnabled(enabled));}
async _startRecording(){console.assert(!this._statusPane,'Status pane is already opened.');this._setState(State$1.StartPending);const recordingOptions={enableJSSampling:!this._disableCaptureJSProfileSetting.get(),capturePictures:this._captureLayersAndPicturesSetting.get(),captureFilmStrip:this._showScreenshotsSetting.get(),startCoverage:this._startCoverage.get()};if(recordingOptions.startCoverage){await ViewManager.ViewManager.instance().showView('coverage').then(()=>ViewManager.ViewManager.instance().view('coverage').widget()).then(widget=>widget.ensureRecordingStarted());}
this._showRecordingStarted();const enabledTraceProviders=self.Extensions.extensionServer.traceProviders().filter(provider=>TimelinePanel._settingForTraceProvider(provider).get());const mainTarget=(SDKModel.TargetManager.instance().mainTarget());if(UIDevtoolsUtils.isUiDevTools()){this._controller=new UIDevtoolsController(mainTarget,this);}else{this._controller=new TimelineController(mainTarget,this);}
this._setUIControlsEnabled(false);this._hideLandingPage();const response=await this._controller.startRecording(recordingOptions,enabledTraceProviders);if(response[InspectorBackend.ProtocolError]){this._recordingFailed(response[InspectorBackend.ProtocolError]);}else{this._recordingStarted();}}
async _stopRecording(){if(this._statusPane){this._statusPane.finish();this._statusPane.updateStatus(UIString.UIString('Stopping timeline…'));this._statusPane.updateProgressBar(UIString.UIString('Received'),0);}
this._setState(State$1.StopPending);if(this._startCoverage.get()){await ViewManager.ViewManager.instance().showView('coverage').then(()=>ViewManager.ViewManager.instance().view('coverage').widget()).then(widget=>widget.stopRecording());}
const model=await this._controller.stopRecording();this._performanceModel=model;this._setUIControlsEnabled(true);this._controller.dispose();this._controller=null;}
_recordingFailed(error){if(this._statusPane){this._statusPane.hide();}
this._statusPane=new StatusPane({description:error,buttonText:ls`Close`,buttonDisabled:false},()=>this.loadingComplete(null));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(ls`Recording failed`);this._setState(State$1.RecordingFailed);this._performanceModel=null;this._setUIControlsEnabled(true);this._controller.dispose();this._controller=null;}
_onSuspendStateChanged(){this._updateTimelineControls();}
_updateTimelineControls(){const state=State$1;this._toggleRecordAction.setToggled(this._state===state.Recording);this._toggleRecordAction.setEnabled(this._state===state.Recording||this._state===state.Idle);this._recordReloadAction.setEnabled(this._state===state.Idle);this._historyManager.setEnabled(this._state===state.Idle);this._clearButton.setEnabled(this._state===state.Idle);this._panelToolbar.setEnabled(this._state!==state.Loading);this._panelRightToolbar.setEnabled(this._state!==state.Loading);this._dropTarget.setEnabled(this._state===state.Idle);this._loadButton.setEnabled(this._state===state.Idle);this._saveButton.setEnabled(this._state===state.Idle&&!!this._performanceModel);}
_toggleRecording(){if(this._state===State$1.Idle){this._recordingPageReload=false;this._startRecording();userMetrics.actionTaken(UserMetrics.Action.TimelineStarted);}else if(this._state===State$1.Recording){this._stopRecording();}}
_recordReload(){if(this._state!==State$1.Idle){return;}
this._recordingPageReload=true;this._startRecording();userMetrics.actionTaken(UserMetrics.Action.TimelinePageReloadStarted);}
_onClearButton(){this._historyManager.clear();this._clear();}
_clear(){this._showLandingPage();this._reset();}
_reset(){self.runtime.sharedInstance(LineLevelProfile.Performance).reset();this._setModel(null);}
_applyFilters(model){if(model.timelineModel().isGenericTrace()||Root.Runtime.experiments.isEnabled('timelineShowAllEvents')){return;}
model.setFilters([TimelineUIUtils.visibleEventsFilter()]);}
_setModel(model){if(this._performanceModel){this._performanceModel.removeEventListener(Events$1.WindowChanged,this._onModelWindowChanged,this);}
this._performanceModel=model;if(model){this._searchableView.showWidget();this._applyFilters(model);}else{this._searchableView.hideWidget();}
this._flameChart.setModel(model);this._updateOverviewControls();this._overviewPane.reset();if(model){this._performanceModel.addEventListener(Events$1.WindowChanged,this._onModelWindowChanged,this);this._overviewPane.setBounds(model.timelineModel().minimumRecordTime(),model.timelineModel().maximumRecordTime());const lineLevelProfile=self.runtime.sharedInstance(LineLevelProfile.Performance);lineLevelProfile.reset();for(const profile of model.timelineModel().cpuProfiles()){lineLevelProfile.appendCPUProfile(profile);}
this._setMarkers(model.timelineModel());this._flameChart.setSelection(null);this._overviewPane.setWindowTimes(model.window().left,model.window().right);}
for(const control of this._overviewControls){control.setModel(model);}
if(this._flameChart){this._flameChart.resizeToPreferredHeights();}
this._updateTimelineControls();}
_recordingStarted(){if(this._recordingPageReload){const target=this._controller.mainTarget();const resourceModel=target.model(ResourceTreeModel.ResourceTreeModel);if(resourceModel){resourceModel.reloadPage();}}
this._reset();this._setState(State$1.Recording);this._showRecordingStarted();this._statusPane.enableAndFocusButton();this._statusPane.updateStatus(UIString.UIString('Profiling…'));this._statusPane.updateProgressBar(UIString.UIString('Buffer usage'),0);this._statusPane.startTimer();this._hideLandingPage();}
recordingProgress(usage){this._statusPane.updateProgressBar(UIString.UIString('Buffer usage'),usage*100);}
_showLandingPage(){if(this._landingPage){this._landingPage.show(this._statusPaneContainer);return;}
function encloseWithTag(tagName,contents){const e=createElement(tagName);e.textContent=contents;return e;}
const learnMoreNode=XLink.XLink.create('https://developers.google.com/web/tools/chrome-devtools/evaluate-performance/',UIString.UIString('Learn\xa0more'));const recordKey=encloseWithTag('b',self.UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.toggle-recording')[0].name);const reloadKey=encloseWithTag('b',self.UI.shortcutRegistry.shortcutDescriptorsForAction('timeline.record-reload')[0].name);const navigateNode=encloseWithTag('b',UIString.UIString('WASD'));this._landingPage=new Widget.VBox();this._landingPage.contentElement.classList.add('timeline-landing-page','fill');const centered=this._landingPage.contentElement.createChild('div');const recordButton=UIUtils.createInlineButton(Toolbar.Toolbar.createActionButton(this._toggleRecordAction));const reloadButton=UIUtils.createInlineButton(Toolbar.Toolbar.createActionButtonForId('timeline.record-reload'));centered.createChild('p').appendChild(UIUtils.formatLocalized('Click the record button %s or hit %s to start a new recording.\nClick the reload button %s or hit %s to record the page load.',[recordButton,recordKey,reloadButton,reloadKey]));centered.createChild('p').appendChild(UIUtils.formatLocalized('After recording, select an area of interest in the overview by dragging.\nThen, zoom and pan the timeline with the mousewheel or %s keys.\n%s',[navigateNode,learnMoreNode]));this._landingPage.show(this._statusPaneContainer);}
_hideLandingPage(){this._landingPage.detach();}
loadingStarted(){this._hideLandingPage();if(this._statusPane){this._statusPane.hide();}
this._statusPane=new StatusPane({showProgress:true},this._cancelLoading.bind(this));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(UIString.UIString('Loading profile…'));if(!this._loader){this._statusPane.finish();}
this.loadingProgress(0);}
loadingProgress(progress){if(typeof progress==='number'){this._statusPane.updateProgressBar(UIString.UIString('Received'),progress*100);}}
processingStarted(){this._statusPane.updateStatus(UIString.UIString('Processing profile…'));}
loadingComplete(tracingModel){delete this._loader;this._setState(State$1.Idle);if(this._statusPane){this._statusPane.hide();}
delete this._statusPane;if(!tracingModel){this._clear();return;}
if(!this._performanceModel){this._performanceModel=new PerformanceModel();}
this._performanceModel.setTracingModel(tracingModel);this._setModel(this._performanceModel);this._historyManager.addRecording(this._performanceModel);if(this._startCoverage.get()){ViewManager.ViewManager.instance().showView('coverage').then(()=>ViewManager.ViewManager.instance().view('coverage').widget()).then(widget=>widget.processBacklog()).then(()=>this._updateOverviewControls());}}
_showRecordingStarted(){if(this._statusPane){return;}
this._statusPane=new StatusPane({showTimer:true,showProgress:true},this._stopRecording.bind(this));this._statusPane.showPane(this._statusPaneContainer);this._statusPane.updateStatus(UIString.UIString('Initializing profiler…'));}
_cancelLoading(){if(this._loader){this._loader.cancel();}}
_setMarkers(timelineModel){const markers=new Map();const recordTypes=TimelineModel.RecordType;const zeroTime=timelineModel.minimumRecordTime();for(const event of timelineModel.timeMarkerEvents()){if(event.name===recordTypes.TimeStamp||event.name===recordTypes.ConsoleTime){continue;}
markers.set(event.startTime,TimelineUIUtils.createEventDivider(event,zeroTime));}
this._overviewPane.setMarkers(markers);}
async _loadEventFired(event){if(this._state!==State$1.Recording||!this._recordingPageReload||this._controller.mainTarget()!==event.data.resourceTreeModel.target()){return;}
const controller=this._controller;await new Promise(r=>setTimeout(r,this._millisecondsToRecordAfterLoadEvent));if(controller!==this._controller||this._state!==State$1.Recording){return;}
this._stopRecording();}
_frameForSelection(selection){switch(selection.type()){case TimelineSelection.Type.Frame:return(selection.object());case TimelineSelection.Type.Range:return null;case TimelineSelection.Type.TraceEvent:return this._performanceModel.frameModel().frames(selection._endTime,selection._endTime)[0];default:console.assert(false,'Should never be reached');return null;}}
_jumpToFrame(offset){const currentFrame=this._selection&&this._frameForSelection(this._selection);if(!currentFrame){return;}
const frames=this._performanceModel.frames();let index=frames.indexOf(currentFrame);console.assert(index>=0,'Can\'t find current frame in the frame list');index=Platform.NumberUtilities.clamp(index+offset,0,frames.length-1);const frame=frames[index];this._revealTimeRange(frame.startTime,frame.endTime);this.select(TimelineSelection.fromFrame(frame));return true;}
select(selection){this._selection=selection;this._flameChart.setSelection(selection);}
selectEntryAtTime(events,time){if(!events){return;}
for(let index=events.upperBound(time,(time,event)=>time-event.startTime)-1;index>=0;--index){const event=events[index];const endTime=event.endTime||event.startTime;if(TracingModel.TracingModel.isTopLevelEvent(event)&&endTime<time){break;}
if(this._performanceModel.isVisible(event)&&endTime>=time){this.select(TimelineSelection.fromTraceEvent(event));return;}}
this.select(null);}
highlightEvent(event){this._flameChart.highlightEvent(event);}
_revealTimeRange(startTime,endTime){const window=this._performanceModel.window();let offset=0;if(window.right<endTime){offset=endTime-window.right;}else if(window.left>startTime){offset=startTime-window.left;}
this._performanceModel.setWindow({left:window.left+offset,right:window.right+offset},true);}
_handleDrop(dataTransfer){const items=dataTransfer.items;if(!items.length){return;}
const item=items[0];if(item.kind==='string'){const url=dataTransfer.getData('text/uri-list');if(new ParsedURL.ParsedURL(url).isValid){this._loadFromURL(url);}}else if(item.kind==='file'){const entry=items[0].webkitGetAsEntry();if(!entry.isFile){return;}
entry.file(this._loadFromFile.bind(this));}}}
const State$1={Idle:Symbol('Idle'),StartPending:Symbol('StartPending'),Recording:Symbol('Recording'),StopPending:Symbol('StopPending'),Loading:Symbol('Loading'),RecordingFailed:Symbol('RecordingFailed')};const ViewMode={FlameChart:'FlameChart',BottomUp:'BottomUp',CallTree:'CallTree',EventLog:'EventLog'};const rowHeight=18;const headerHeight=20;class TimelineSelection{constructor(type,startTime,endTime,object){this._type=type;this._startTime=startTime;this._endTime=endTime;this._object=object||null;}
static fromFrame(frame){return new TimelineSelection(TimelineSelection.Type.Frame,frame.startTime,frame.endTime,frame);}
static fromNetworkRequest(request){return new TimelineSelection(TimelineSelection.Type.NetworkRequest,request.startTime,request.endTime||request.startTime,request);}
static fromTraceEvent(event){return new TimelineSelection(TimelineSelection.Type.TraceEvent,event.startTime,event.endTime||(event.startTime+1),event);}
static fromRange(startTime,endTime){return new TimelineSelection(TimelineSelection.Type.Range,startTime,endTime);}
type(){return this._type;}
object(){return this._object;}
startTime(){return this._startTime;}
endTime(){return this._endTime;}}
TimelineSelection.Type={Frame:'Frame',NetworkRequest:'NetworkRequest',TraceEvent:'TraceEvent',Range:'Range'};class TimelineModeViewDelegate{select(selection){}
selectEntryAtTime(events,time){}
highlightEvent(event){}}
class StatusPane extends Widget.VBox{constructor(options,buttonCallback){super(true);this.registerRequiredCSS('timeline/timelineStatusDialog.css');this.contentElement.classList.add('timeline-status-dialog');const statusLine=this.contentElement.createChild('div','status-dialog-line status');statusLine.createChild('div','label').textContent=UIString.UIString('Status');this._status=statusLine.createChild('div','content');ARIAUtils.markAsStatus(this._status);if(options.showTimer){const timeLine=this.contentElement.createChild('div','status-dialog-line time');timeLine.createChild('div','label').textContent=UIString.UIString('Time');this._time=timeLine.createChild('div','content');}
if(options.showProgress){const 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');ARIAUtils.markAsProgressBar(this._progressBar);}
if(typeof options.description==='string'){const descriptionLine=this.contentElement.createChild('div','status-dialog-line description');descriptionLine.createChild('div','label').textContent=ls`Description`;this._description=descriptionLine.createChild('div','content');this._description.innerText=options.description;}
const buttonText=options.buttonText||ls`Stop`;this._button=UIUtils.createTextButton(buttonText,buttonCallback,'',true);this._button.disabled=!options.buttonDisabled===false;this.contentElement.createChild('div','stop-button').appendChild(this._button);}
finish(){this._stopTimer();this._button.disabled=true;}
hide(){this.element.parentNode.classList.remove('tinted');this.element.remove();}
showPane(parent){this.show(parent);parent.classList.add('tinted');}
enableAndFocusButton(){this._button.disabled=false;this._button.focus();}
updateStatus(text){this._status.textContent=text;}
updateProgressBar(activity,percent){this._progressLabel.textContent=activity;this._progressBar.style.width=percent.toFixed(1)+'%';ARIAUtils.setValueNow(this._progressBar,percent);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;}
const elapsed=(Date.now()-this._startTime)/1000;this._time.textContent=UIString.UIString('%s\xa0sec',elapsed.toFixed(precise?1:0));}}
class LoadTimelineHandler{handleQueryParam(value){ViewManager.ViewManager.instance().showView('timeline').then(()=>{TimelinePanel.instance()._loadFromURL(window.decodeURIComponent(value));});}}
class ActionDelegate{handleAction(context,actionId){const panel=self.UI.context.flavor(TimelinePanel);console.assert(panel&&panel instanceof TimelinePanel);switch(actionId){case'timeline.toggle-recording':panel._toggleRecording();return true;case'timeline.record-reload':panel._recordReload();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;case'timeline.show-history':panel._showHistory();return true;case'timeline.previous-recording':panel._navigateHistory(1);return true;case'timeline.next-recording':panel._navigateHistory(-1);return true;}
return false;}}
const traceProviderSettingSymbol=Symbol('traceProviderSetting');var TimelinePanel$1=Object.freeze({__proto__:null,TimelinePanel:TimelinePanel,State:State$1,ViewMode:ViewMode,rowHeight:rowHeight,headerHeight:headerHeight,TimelineSelection:TimelineSelection,TimelineModeViewDelegate:TimelineModeViewDelegate,StatusPane:StatusPane,LoadTimelineHandler:LoadTimelineHandler,ActionDelegate:ActionDelegate,traceProviderSettingSymbol:traceProviderSettingSymbol});class TimelineUIUtils{static _initEventStyles(){if(TimelineUIUtils._eventStylesMap){return TimelineUIUtils._eventStylesMap;}
const type=TimelineModel.RecordType;const categories=TimelineUIUtils.categories();const rendering=categories['rendering'];const scripting=categories['scripting'];const loading=categories['loading'];const experience=categories['experience'];const painting=categories['painting'];const other=categories['other'];const idle=categories['idle'];const eventStyles={};eventStyles[type.Task]=new TimelineRecordStyle(ls`Task`,other);eventStyles[type.Program]=new TimelineRecordStyle(ls`Other`,other);eventStyles[type.Animation]=new TimelineRecordStyle(ls`Animation`,rendering);eventStyles[type.EventDispatch]=new TimelineRecordStyle(ls`Event`,scripting);eventStyles[type.RequestMainThreadFrame]=new TimelineRecordStyle(ls`Request Main Thread Frame`,rendering,true);eventStyles[type.BeginFrame]=new TimelineRecordStyle(ls`Frame Start`,rendering,true);eventStyles[type.BeginMainThreadFrame]=new TimelineRecordStyle(ls`Frame Start (main thread)`,rendering,true);eventStyles[type.DrawFrame]=new TimelineRecordStyle(ls`Draw Frame`,rendering,true);eventStyles[type.HitTest]=new TimelineRecordStyle(ls`Hit Test`,rendering);eventStyles[type.ScheduleStyleRecalculation]=new TimelineRecordStyle(ls`Schedule Style Recalculation`,rendering);eventStyles[type.RecalculateStyles]=new TimelineRecordStyle(ls`Recalculate Style`,rendering);eventStyles[type.UpdateLayoutTree]=new TimelineRecordStyle(ls`Recalculate Style`,rendering);eventStyles[type.InvalidateLayout]=new TimelineRecordStyle(ls`Invalidate Layout`,rendering,true);eventStyles[type.Layout]=new TimelineRecordStyle(ls`Layout`,rendering);eventStyles[type.PaintSetup]=new TimelineRecordStyle(ls`Paint Setup`,painting);eventStyles[type.PaintImage]=new TimelineRecordStyle(ls`Paint Image`,painting,true);eventStyles[type.UpdateLayer]=new TimelineRecordStyle(ls`Update Layer`,painting,true);eventStyles[type.UpdateLayerTree]=new TimelineRecordStyle(ls`Update Layer Tree`,rendering);eventStyles[type.Paint]=new TimelineRecordStyle(ls`Paint`,painting);eventStyles[type.RasterTask]=new TimelineRecordStyle(ls`Rasterize Paint`,painting);eventStyles[type.ScrollLayer]=new TimelineRecordStyle(ls`Scroll`,rendering);eventStyles[type.CompositeLayers]=new TimelineRecordStyle(ls`Composite Layers`,painting);eventStyles[type.ParseHTML]=new TimelineRecordStyle(ls`Parse HTML`,loading);eventStyles[type.ParseAuthorStyleSheet]=new TimelineRecordStyle(ls`Parse Stylesheet`,loading);eventStyles[type.TimerInstall]=new TimelineRecordStyle(ls`Install Timer`,scripting);eventStyles[type.TimerRemove]=new TimelineRecordStyle(ls`Remove Timer`,scripting);eventStyles[type.TimerFire]=new TimelineRecordStyle(ls`Timer Fired`,scripting);eventStyles[type.XHRReadyStateChange]=new TimelineRecordStyle(ls`XHR Ready State Change`,scripting);eventStyles[type.XHRLoad]=new TimelineRecordStyle(ls`XHR Load`,scripting);eventStyles[type.CompileScript]=new TimelineRecordStyle(ls`Compile Script`,scripting);eventStyles[type.EvaluateScript]=new TimelineRecordStyle(ls`Evaluate Script`,scripting);eventStyles[type.CompileModule]=new TimelineRecordStyle(ls`Compile Module`,scripting);eventStyles[type.EvaluateModule]=new TimelineRecordStyle(ls`Evaluate Module`,scripting);eventStyles[type.StreamingCompileScript]=new TimelineRecordStyle(ls`Streaming Compile Task`,other);eventStyles[type.StreamingCompileScriptWaiting]=new TimelineRecordStyle(ls`Waiting for Network`,idle);eventStyles[type.StreamingCompileScriptParsing]=new TimelineRecordStyle(ls`Parse and Compile`,scripting);eventStyles[type.WasmStreamFromResponseCallback]=new TimelineRecordStyle(ls`Streaming Wasm Response`,scripting);eventStyles[type.WasmCompiledModule]=new TimelineRecordStyle(ls`Compiled Wasm Module`,scripting);eventStyles[type.WasmCachedModule]=new TimelineRecordStyle(ls`Cached Wasm Module`,scripting);eventStyles[type.WasmModuleCacheHit]=new TimelineRecordStyle(ls`Wasm Module Cache Hit`,scripting);eventStyles[type.WasmModuleCacheInvalid]=new TimelineRecordStyle(ls`Wasm Module Cache Invalid`,scripting);eventStyles[type.FrameStartedLoading]=new TimelineRecordStyle(ls`Frame Started Loading`,loading,true);eventStyles[type.MarkLoad]=new TimelineRecordStyle(ls`Onload Event`,scripting,true);eventStyles[type.MarkDOMContent]=new TimelineRecordStyle(ls`DOMContentLoaded Event`,scripting,true);eventStyles[type.MarkFirstPaint]=new TimelineRecordStyle(ls`First Paint`,painting,true);eventStyles[type.MarkFCP]=new TimelineRecordStyle(ls`First Contentful Paint`,rendering,true);eventStyles[type.MarkFMP]=new TimelineRecordStyle(ls`First Meaningful Paint`,rendering,true);eventStyles[type.MarkLCPCandidate]=new TimelineRecordStyle(ls`Largest Contentful Paint`,rendering,true);eventStyles[type.TimeStamp]=new TimelineRecordStyle(ls`Timestamp`,scripting);eventStyles[type.ConsoleTime]=new TimelineRecordStyle(ls`Console Time`,scripting);eventStyles[type.UserTiming]=new TimelineRecordStyle(ls`User Timing`,scripting);eventStyles[type.ResourceWillSendRequest]=new TimelineRecordStyle(ls`Will Send Request`,loading);eventStyles[type.ResourceSendRequest]=new TimelineRecordStyle(ls`Send Request`,loading);eventStyles[type.ResourceReceiveResponse]=new TimelineRecordStyle(ls`Receive Response`,loading);eventStyles[type.ResourceFinish]=new TimelineRecordStyle(ls`Finish Loading`,loading);eventStyles[type.ResourceReceivedData]=new TimelineRecordStyle(ls`Receive Data`,loading);eventStyles[type.RunMicrotasks]=new TimelineRecordStyle(ls`Run Microtasks`,scripting);eventStyles[type.FunctionCall]=new TimelineRecordStyle(ls`Function Call`,scripting);eventStyles[type.GCEvent]=new TimelineRecordStyle(ls`GC Event`,scripting);eventStyles[type.MajorGC]=new TimelineRecordStyle(ls`Major GC`,scripting);eventStyles[type.MinorGC]=new TimelineRecordStyle(ls`Minor GC`,scripting);eventStyles[type.JSFrame]=new TimelineRecordStyle(ls`JS Frame`,scripting);eventStyles[type.RequestAnimationFrame]=new TimelineRecordStyle(ls`Request Animation Frame`,scripting);eventStyles[type.CancelAnimationFrame]=new TimelineRecordStyle(ls`Cancel Animation Frame`,scripting);eventStyles[type.FireAnimationFrame]=new TimelineRecordStyle(ls`Animation Frame Fired`,scripting);eventStyles[type.RequestIdleCallback]=new TimelineRecordStyle(ls`Request Idle Callback`,scripting);eventStyles[type.CancelIdleCallback]=new TimelineRecordStyle(ls`Cancel Idle Callback`,scripting);eventStyles[type.FireIdleCallback]=new TimelineRecordStyle(ls`Fire Idle Callback`,scripting);eventStyles[type.WebSocketCreate]=new TimelineRecordStyle(ls`Create WebSocket`,scripting);eventStyles[type.WebSocketSendHandshakeRequest]=new TimelineRecordStyle(ls`Send WebSocket Handshake`,scripting);eventStyles[type.WebSocketReceiveHandshakeResponse]=new TimelineRecordStyle(ls`Receive WebSocket Handshake`,scripting);eventStyles[type.WebSocketDestroy]=new TimelineRecordStyle(ls`Destroy WebSocket`,scripting);eventStyles[type.EmbedderCallback]=new TimelineRecordStyle(ls`Embedder Callback`,scripting);eventStyles[type.DecodeImage]=new TimelineRecordStyle(ls`Image Decode`,painting);eventStyles[type.ResizeImage]=new TimelineRecordStyle(ls`Image Resize`,painting);eventStyles[type.GPUTask]=new TimelineRecordStyle(ls`GPU`,categories['gpu']);eventStyles[type.LatencyInfo]=new TimelineRecordStyle(ls`Input Latency`,scripting);eventStyles[type.GCCollectGarbage]=new TimelineRecordStyle(ls`DOM GC`,scripting);eventStyles[type.CryptoDoEncrypt]=new TimelineRecordStyle(ls`Encrypt`,scripting);eventStyles[type.CryptoDoEncryptReply]=new TimelineRecordStyle(ls`Encrypt Reply`,scripting);eventStyles[type.CryptoDoDecrypt]=new TimelineRecordStyle(ls`Decrypt`,scripting);eventStyles[type.CryptoDoDecryptReply]=new TimelineRecordStyle(ls`Decrypt Reply`,scripting);eventStyles[type.CryptoDoDigest]=new TimelineRecordStyle(ls`Digest`,scripting);eventStyles[type.CryptoDoDigestReply]=new TimelineRecordStyle(ls`Digest Reply`,scripting);eventStyles[type.CryptoDoSign]=new TimelineRecordStyle(ls`Sign`,scripting);eventStyles[type.CryptoDoSignReply]=new TimelineRecordStyle(ls`Sign Reply`,scripting);eventStyles[type.CryptoDoVerify]=new TimelineRecordStyle(ls`Verify`,scripting);eventStyles[type.CryptoDoVerifyReply]=new TimelineRecordStyle(ls`Verify Reply`,scripting);eventStyles[type.AsyncTask]=new TimelineRecordStyle(ls`Async Task`,categories['async']);eventStyles[type.LayoutShift]=new TimelineRecordStyle(ls`Layout Shift`,experience);TimelineUIUtils._eventStylesMap=eventStyles;return eventStyles;}
static setEventStylesMap(eventStyles){TimelineUIUtils._eventStylesMap=eventStyles;}
static inputEventDisplayName(inputEventType){if(!TimelineUIUtils._inputEventToDisplayName){const inputEvent=TimelineIRModel.InputEvents;TimelineUIUtils._inputEventToDisplayName=new Map([[inputEvent.Char,ls`Key Character`],[inputEvent.KeyDown,ls`Key Down`],[inputEvent.KeyDownRaw,ls`Key Down`],[inputEvent.KeyUp,ls`Key Up`],[inputEvent.Click,ls`Click`],[inputEvent.ContextMenu,ls`Context Menu`],[inputEvent.MouseDown,ls`Mouse Down`],[inputEvent.MouseMove,ls`Mouse Move`],[inputEvent.MouseUp,ls`Mouse Up`],[inputEvent.MouseWheel,ls`Mouse Wheel`],[inputEvent.ScrollBegin,ls`Scroll Begin`],[inputEvent.ScrollEnd,ls`Scroll End`],[inputEvent.ScrollUpdate,ls`Scroll Update`],[inputEvent.FlingStart,ls`Fling Start`],[inputEvent.FlingCancel,ls`Fling Halt`],[inputEvent.Tap,ls`Tap`],[inputEvent.TapCancel,ls`Tap Halt`],[inputEvent.ShowPress,ls`Tap Begin`],[inputEvent.TapDown,ls`Tap Down`],[inputEvent.TouchCancel,ls`Touch Cancel`],[inputEvent.TouchEnd,ls`Touch End`],[inputEvent.TouchMove,ls`Touch Move`],[inputEvent.TouchStart,ls`Touch Start`],[inputEvent.PinchBegin,ls`Pinch Begin`],[inputEvent.PinchEnd,ls`Pinch End`],[inputEvent.PinchUpdate,ls`Pinch Update`]]);}
return TimelineUIUtils._inputEventToDisplayName.get(inputEventType)||null;}
static frameDisplayName(frame){if(!TimelineJSProfile.TimelineJSProfileProcessor.isNativeRuntimeFrame(frame)){return UIUtils.beautifyFunctionName(frame.functionName);}
const nativeGroup=TimelineJSProfile.TimelineJSProfileProcessor.nativeGroup(frame.functionName);const groups=TimelineJSProfile.TimelineJSProfileProcessor.NativeGroups;switch(nativeGroup){case groups.Compile:return ls`Compile`;case groups.Parse:return ls`Parse`;}
return frame.functionName;}
static testContentMatching(traceEvent,regExp){const title=TimelineUIUtils.eventStyle(traceEvent).title;const tokens=[title];const 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(const key in object){const value=object[key];const 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 eventURL(event){const data=event.args['data']||event.args['beginData'];const url=data&&data.url;if(url){return url;}
const stackTrace=data&&data['stackTrace'];const frame=stackTrace&&stackTrace.length&&stackTrace[0]||TimelineModel.TimelineData.forEvent(event).topFrame();return frame&&frame.url||null;}
static eventStyle(event){const eventStyles=TimelineUIUtils._initEventStyles();if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.Console)||event.hasCategory(TimelineModel.TimelineModelImpl.Category.UserTiming)){return new TimelineRecordStyle(event.name,TimelineUIUtils.categories()['scripting']);}
if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.LatencyInfo)){const prefix='InputLatency::';const inputEventType=event.name.startsWith(prefix)?event.name.substr(prefix.length):event.name;const displayName=TimelineUIUtils.inputEventDisplayName((inputEventType));return new TimelineRecordStyle(displayName||inputEventType,TimelineUIUtils.categories()['scripting']);}
let result=eventStyles[event.name];if(!result){result=new TimelineRecordStyle(event.name,TimelineUIUtils.categories()['other'],true);eventStyles[event.name]=result;}
return result;}
static eventColor(event){if(event.name===TimelineModel.RecordType.JSFrame){const frame=event.args['data'];if(TimelineUIUtils.isUserFrame(frame)){return TimelineUIUtils.colorForId(frame.url);}}
const color=TimelineUIUtils.eventStyle(event).category.color;if(event.name===TimelineModel.RecordType.StreamingCompileScriptWaiting){return(Color.Color.parse(TimelineUIUtils.categories().scripting.color).setAlpha(0.3).asString(null));}
return color;}
static eventColorByProduct(model,urlToColorCache,event){const url=TimelineUIUtils.eventURL(event)||'';let color=urlToColorCache.get(url);if(color){return color;}
const defaultColor='#f2ecdc';const parsedURL=ParsedURL.ParsedURL.fromString(url);if(!parsedURL){return defaultColor;}
const name=parsedURL.host;const rootFrames=model.rootFrames();if(rootFrames.some(pageFrame=>new ParsedURL.ParsedURL(pageFrame.url).host===name)){color=defaultColor;}
if(!color){color=defaultColor;}
urlToColorCache.set(url,color);return color;}
static eventTitle(event){const recordType=TimelineModel.RecordType;const eventData=event.args['data'];if(event.name===recordType.JSFrame){return TimelineUIUtils.frameDisplayName(eventData);}
const title=TimelineUIUtils.eventStyle(event).title;if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.Console)){return title;}
if(event.name===recordType.TimeStamp){return ls`${title}: ${eventData['message']}`;}
if(event.name===recordType.Animation&&eventData&&eventData['name']){return ls`${title}: ${eventData['name']}`;}
if(event.name===recordType.EventDispatch&&eventData&&eventData['type']){return ls`${title}: ${eventData['type']}`;}
return title;}
static _interactionPhaseStyles(){let map=TimelineUIUtils._interactionPhaseStylesMap;if(!map){map=new Map([[TimelineIRModel.Phases.Idle,{color:'white',label:'Idle'}],[TimelineIRModel.Phases.Response,{color:'hsl(43, 83%, 64%)',label:ls`Response`}],[TimelineIRModel.Phases.Scroll,{color:'hsl(256, 67%, 70%)',label:ls`Scroll`}],[TimelineIRModel.Phases.Fling,{color:'hsl(256, 67%, 70%)',label:ls`Fling`}],[TimelineIRModel.Phases.Drag,{color:'hsl(256, 67%, 70%)',label:ls`Drag`}],[TimelineIRModel.Phases.Animation,{color:'hsl(256, 67%, 70%)',label:ls`Animation`}],[TimelineIRModel.Phases.Uncategorized,{color:'hsl(0, 0%, 87%)',label:ls`Uncategorized`}]]);TimelineUIUtils._interactionPhaseStylesMap=map;}
return map;}
static interactionPhaseColor(phase){return TimelineUIUtils._interactionPhaseStyles().get(phase).color;}
static interactionPhaseLabel(phase){return TimelineUIUtils._interactionPhaseStyles().get(phase).label;}
static isUserFrame(frame){return frame.scriptId!=='0'&&!(frame.url&&frame.url.startsWith('native '));}
static networkRequestCategory(request){const categories=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){const categories=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 async buildDetailsTextForTraceEvent(event,target){const recordType=TimelineModel.RecordType;let detailsText;const eventData=event.args['data'];switch(event.name){case recordType.GCEvent:case recordType.MajorGC:case recordType.MinorGC:{const delta=event.args['usedHeapSizeBefore']-event.args['usedHeapSizeAfter'];detailsText=UIString.UIString('%s collected',Number.bytesToString(delta));break;}
case recordType.FunctionCall:if(eventData){detailsText=await linkifyLocationAsText(eventData['scriptId'],eventData['lineNumber'],eventData['columnNumber']);}
break;case recordType.JSFrame:detailsText=TimelineUIUtils.frameDisplayName(eventData);break;case recordType.EventDispatch:detailsText=eventData?eventData['type']:null;break;case recordType.Paint:{const width=TimelineUIUtils.quadWidth(eventData.clip);const height=TimelineUIUtils.quadHeight(eventData.clip);if(width&&height){detailsText=UIString.UIString('%d\xA0×\xA0%d',width,height);}
break;}
case recordType.ParseHTML:{const startLine=event.args['beginData']['startLine'];const endLine=event.args['endData']&&event.args['endData']['endLine'];const url=ResourceUtils.displayNameForURL(event.args['beginData']['url']);if(endLine>=0){detailsText=UIString.UIString('%s [%s…%s]',url,startLine+1,endLine+1);}else{detailsText=UIString.UIString('%s [%s…]',url,startLine+1);}
break;}
case recordType.CompileModule:detailsText=ResourceUtils.displayNameForURL(event.args['fileName']);break;case recordType.CompileScript:case recordType.EvaluateScript:{const url=eventData&&eventData['url'];if(url){detailsText=ResourceUtils.displayNameForURL(url)+':'+(eventData['lineNumber']+1);}
break;}
case recordType.WasmCompiledModule:case recordType.WasmModuleCacheHit:{const url=event.args['url'];if(url){detailsText=ResourceUtils.displayNameForURL(url);}
break;}
case recordType.StreamingCompileScript:case recordType.XHRReadyStateChange:case recordType.XHRLoad:{const url=eventData['url'];if(url){detailsText=ResourceUtils.displayNameForURL(url);}
break;}
case recordType.TimeStamp:detailsText=eventData['message'];break;case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:case recordType.ResourceWillSendRequest:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:case recordType.PaintImage:case recordType.DecodeImage:case recordType.ResizeImage:case recordType.DecodeLazyPixelRef:{const url=TimelineModel.TimelineData.forEvent(event).url;if(url){detailsText=ResourceUtils.displayNameForURL(url);}
break;}
case recordType.EmbedderCallback:detailsText=eventData['callbackName'];break;case recordType.Animation:detailsText=eventData&&eventData['name'];break;case recordType.AsyncTask:detailsText=eventData?eventData['name']:null;break;default:if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.Console)){detailsText=null;}else{detailsText=await linkifyTopCallFrameAsText();}
break;}
return detailsText;async function linkifyLocationAsText(scriptId,lineNumber,columnNumber){const debuggerModel=target?target.model(DebuggerModel.DebuggerModel):null;if(!target||target.isDisposed()||!scriptId||!debuggerModel){return null;}
const rawLocation=debuggerModel.createRawLocationByScriptId(scriptId,lineNumber,columnNumber);if(!rawLocation){return null;}
const uiLocation=await DebuggerWorkspaceBinding.DebuggerWorkspaceBinding.instance().rawLocationToUILocation(rawLocation);return uiLocation?uiLocation.linkText():null;}
async function linkifyTopCallFrameAsText(){const frame=TimelineModel.TimelineData.forEvent(event).topFrame();if(!frame){return null;}
let text=await linkifyLocationAsText(frame.scriptId,frame.lineNumber,frame.columnNumber);if(!text){text=frame.url;if(typeof frame.lineNumber==='number'){text+=':'+(frame.lineNumber+1);}}
return text;}}
static async buildDetailsNodeForTraceEvent(event,target,linkifier){const recordType=TimelineModel.RecordType;let details=null;let detailsText;const 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.WasmStreamFromResponseCallback:case recordType.WasmCompiledModule:case recordType.WasmModuleCacheHit:case recordType.WasmCachedModule:case recordType.WasmModuleCacheInvalid:case recordType.WebSocketCreate:case recordType.WebSocketSendHandshakeRequest:case recordType.WebSocketReceiveHandshakeResponse:case recordType.WebSocketDestroy:{detailsText=await 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.ResourceWillSendRequest:case recordType.ResourceSendRequest:case recordType.ResourceReceivedData:case recordType.ResourceReceiveResponse:case recordType.ResourceFinish:{const url=TimelineModel.TimelineData.forEvent(event).url;if(url){details=Linkifier.Linkifier.linkifyURL(url,{tabStop:true});}
break;}
case recordType.FunctionCall:case recordType.JSFrame:{details=createElement('span');details.createTextChild(TimelineUIUtils.frameDisplayName(eventData));const location=linkifyLocation(eventData['scriptId'],eventData['url'],eventData['lineNumber'],eventData['columnNumber']);if(location){details.createTextChild(' @ ');details.appendChild(location);}
break;}
case recordType.CompileModule:{details=linkifyLocation('',event.args['fileName'],0,0);break;}
case recordType.CompileScript:case recordType.EvaluateScript:{const url=eventData['url'];if(url){details=linkifyLocation('',url,eventData['lineNumber'],0);}
break;}
case recordType.StreamingCompileScript:{const url=eventData['url'];if(url){details=linkifyLocation('',url,0,0);}
break;}
default:{if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.Console)){detailsText=null;}else{details=linkifyTopCallFrame();}
break;}}
if(!details&&detailsText){details=createTextNode(detailsText);}
return details;function linkifyLocation(scriptId,url,lineNumber,columnNumber){const options={columnNumber,className:'timeline-details',tabStop:true};return linkifier.linkifyScriptLocation(target,scriptId,url,lineNumber,options);}
function linkifyTopCallFrame(){const frame=TimelineModel.TimelineData.forEvent(event).topFrame();return frame?linkifier.maybeLinkifyConsoleCallFrame(target,frame,{className:'timeline-details',tabStop:true}):null;}}
static buildDetailsNodeForPerformanceEvent(event){let link='https://developers.google.com/web/fundamentals/performance/user-centric-performance-metrics#user-centric_performance_metrics';let name='page performance metrics';const recordType=TimelineModel.RecordType;switch(event.name){case recordType.MarkLCPCandidate:link='https://web.dev/largest-contentful-paint';name='largest contentful paint';break;case recordType.MarkFCP:link='https://web.dev/first-contentful-paint';name='first contentful paint';break;case recordType.MarkFMP:link='https://web.dev/first-meaningful-paint/';name='first meaningful paint';break;default:break;}
return Fragment.html`<div>${XLink.XLink.create(link, ls`Learn more`)} about ${name}.</div>`;}
static async buildTraceEventDetails(event,model,linkifier,detailed){const maybeTarget=model.targetByEvent(event);let relatedNodesMap=null;if(maybeTarget){const target=(maybeTarget);if(typeof event[previewElementSymbol]==='undefined'){let previewElement=null;const url=TimelineModel.TimelineData.forEvent(event).url;if(url){previewElement=await ImagePreview.ImagePreview.build(target,url,false,{imageAltText:ImagePreview.ImagePreview.defaultAltTextForImageURL(url)});}else if(TimelineModel.TimelineData.forEvent(event).picture){previewElement=await TimelineUIUtils.buildPicturePreviewContent(event,target);}
event[previewElementSymbol]=previewElement;}
const nodeIdsToResolve=new Set();const timelineData=TimelineModel.TimelineData.forEvent(event);if(timelineData.backendNodeId){nodeIdsToResolve.add(timelineData.backendNodeId);}
const invalidationTrackingEvents=TimelineModel.InvalidationTracker.invalidationEventsFor(event);if(invalidationTrackingEvents){TimelineUIUtils._collectInvalidationNodeIds(nodeIdsToResolve,invalidationTrackingEvents);}
if(nodeIdsToResolve.size){const domModel=target.model(DOMModel.DOMModel);if(domModel){relatedNodesMap=await domModel.pushNodesByBackendIdsToFrontend(nodeIdsToResolve);}}}
const recordTypes=TimelineModel.RecordType;if(event.name===recordTypes.LayoutShift){detailed=false;}
let relatedNodeLabel;const contentHelper=new TimelineDetailsContentHelper(model.targetByEvent(event),linkifier);const color=model.isMarkerEvent(event)?TimelineUIUtils.markerStyleForEvent(event).color:TimelineUIUtils.eventStyle(event).category.color;contentHelper.addSection(TimelineUIUtils.eventTitle(event),color);const eventData=event.args['data'];const timelineData=TimelineModel.TimelineData.forEvent(event);const initiator=timelineData.initiator();let url=null;if(timelineData.warning){contentHelper.appendWarningRow(event);}
if(event.name===recordTypes.JSFrame&&eventData['deoptReason']){contentHelper.appendWarningRow(event,TimelineModel.TimelineModelImpl.WarningType.V8Deopt);}
if(detailed&&!Number.isNaN(event.duration+0)){contentHelper.appendTextRow(ls`Total Time`,Number.millisToString(event.duration,true));contentHelper.appendTextRow(ls`Self Time`,Number.millisToString(event.selfTime,true));}
if(model.isGenericTrace()){for(const key in event.args){try{contentHelper.appendTextRow(key,JSON.stringify(event.args[key]));}catch(e){contentHelper.appendTextRow(key,`<${typeof event.args[key]}>`);}}
return contentHelper.fragment;}
switch(event.name){case recordTypes.GCEvent:case recordTypes.MajorGC:case recordTypes.MinorGC:{const delta=event.args['usedHeapSizeBefore']-event.args['usedHeapSizeAfter'];contentHelper.appendTextRow(ls`Collected`,Number.bytesToString(delta));break;}
case recordTypes.JSFrame:case recordTypes.FunctionCall:{const detailsNode=await TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode){contentHelper.appendElementRow(ls`Function`,detailsNode);}
break;}
case recordTypes.TimerFire:case recordTypes.TimerInstall:case recordTypes.TimerRemove:{contentHelper.appendTextRow(ls`Timer ID`,eventData['timerId']);if(event.name===recordTypes.TimerInstall){contentHelper.appendTextRow(ls`Timeout`,Number.millisToString(eventData['timeout']));contentHelper.appendTextRow(ls`Repeats`,!eventData['singleShot']);}
break;}
case recordTypes.FireAnimationFrame:{contentHelper.appendTextRow(ls`Callback ID`,eventData['id']);break;}
case recordTypes.ResourceWillSendRequest:case recordTypes.ResourceSendRequest:case recordTypes.ResourceReceiveResponse:case recordTypes.ResourceReceivedData:case recordTypes.ResourceFinish:{url=timelineData.url;if(url){contentHelper.appendElementRow(ls`Resource`,Linkifier.Linkifier.linkifyURL(url,{tabStop:true}));}
if(eventData['requestMethod']){contentHelper.appendTextRow(ls`Request Method`,eventData['requestMethod']);}
if(typeof eventData['statusCode']==='number'){contentHelper.appendTextRow(ls`Status Code`,eventData['statusCode']);}
if(eventData['mimeType']){contentHelper.appendTextRow(ls`MIME Type`,eventData['mimeType']);}
if('priority'in eventData){const priority=NetworkPriorities.uiLabelForNetworkPriority(eventData['priority']);contentHelper.appendTextRow(ls`Priority`,priority);}
if(eventData['encodedDataLength']){contentHelper.appendTextRow(ls`Encoded Data`,ls`${eventData['encodedDataLength']} Bytes`);}
if(eventData['decodedBodyLength']){contentHelper.appendTextRow(ls`Decoded Body`,ls`${eventData['decodedBodyLength']} Bytes`);}
break;}
case recordTypes.CompileModule:{contentHelper.appendLocationRow(ls`Module`,event.args['fileName'],0);break;}
case recordTypes.CompileScript:{url=eventData&&eventData['url'];if(url){contentHelper.appendLocationRow(ls`Script`,url,eventData['lineNumber'],eventData['columnNumber']);}
contentHelper.appendTextRow(ls`Streamed`,eventData['streamed']);const producedCacheSize=eventData&&eventData['producedCacheSize'];if(producedCacheSize){contentHelper.appendTextRow(ls`Produced Cache Size`,producedCacheSize);}
const cacheConsumeOptions=eventData&&eventData['cacheConsumeOptions'];if(cacheConsumeOptions){contentHelper.appendTextRow(ls`Cache Consume Options`,cacheConsumeOptions);contentHelper.appendTextRow(ls`Consumed Cache Size`,eventData['consumedCacheSize']);contentHelper.appendTextRow(ls`Cache Rejected`,eventData['cacheRejected']);}
break;}
case recordTypes.EvaluateScript:{url=eventData&&eventData['url'];if(url){contentHelper.appendLocationRow(ls`Script`,url,eventData['lineNumber'],eventData['columnNumber']);}
break;}
case recordTypes.WasmStreamFromResponseCallback:case recordTypes.WasmCompiledModule:case recordTypes.WasmCachedModule:case recordTypes.WasmModuleCacheHit:case recordTypes.WasmModuleCacheInvalid:{if(eventData){url=event.args['url'];if(url){contentHelper.appendTextRow(ls`Url`,url);}
const producedCachedSize=event.args['producedCachedSize'];if(producedCachedSize){contentHelper.appendTextRow(ls`Produced Cache Size`,producedCachedSize);}
const consumedCachedSize=event.args['consumedCachedSize'];if(consumedCachedSize){contentHelper.appendTextRow(ls`Consumed Cache Size`,consumedCachedSize);}}
break;}
case recordTypes.Paint:{const clip=eventData['clip'];contentHelper.appendTextRow(ls`Location`,ls`(${clip[0]}, ${clip[1]})`);const clipWidth=TimelineUIUtils.quadWidth(clip);const clipHeight=TimelineUIUtils.quadHeight(clip);contentHelper.appendTextRow(ls`Dimensions`,ls`${clipWidth} × ${clipHeight}`);}
case recordTypes.PaintSetup:case recordTypes.Rasterize:case recordTypes.ScrollLayer:{relatedNodeLabel=ls`Layer Root`;break;}
case recordTypes.PaintImage:case recordTypes.DecodeLazyPixelRef:case recordTypes.DecodeImage:case recordTypes.ResizeImage:case recordTypes.DrawLazyPixelRef:{relatedNodeLabel=ls`Owner Element`;url=timelineData.url;if(url){contentHelper.appendElementRow(ls`Image URL`,Linkifier.Linkifier.linkifyURL(url,{tabStop:true}));}
break;}
case recordTypes.ParseAuthorStyleSheet:{url=eventData['styleSheetUrl'];if(url){contentHelper.appendElementRow(ls`Stylesheet URL`,Linkifier.Linkifier.linkifyURL(url,{tabStop:true}));}
break;}
case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:{contentHelper.appendTextRow(ls`Elements Affected`,event.args['elementCount']);break;}
case recordTypes.Layout:{const beginData=event.args['beginData'];contentHelper.appendTextRow(ls`Nodes That Need Layout`,ls`${beginData['dirtyObjects']} of ${beginData['totalObjects']}`);relatedNodeLabel=ls`Layout root`;break;}
case recordTypes.ConsoleTime:{contentHelper.appendTextRow(ls`Message`,event.name);break;}
case recordTypes.WebSocketCreate:case recordTypes.WebSocketSendHandshakeRequest:case recordTypes.WebSocketReceiveHandshakeResponse:case recordTypes.WebSocketDestroy:{const initiatorData=initiator?initiator.args['data']:eventData;if(typeof initiatorData['webSocketURL']!=='undefined'){contentHelper.appendTextRow(ls`URL`,initiatorData['webSocketURL']);}
if(typeof initiatorData['webSocketProtocol']!=='undefined'){contentHelper.appendTextRow(ls`WebSocket Protocol`,initiatorData['webSocketProtocol']);}
if(typeof eventData['message']!=='undefined'){contentHelper.appendTextRow(ls`Message`,eventData['message']);}
break;}
case recordTypes.EmbedderCallback:{contentHelper.appendTextRow(ls`Callback Function`,eventData['callbackName']);break;}
case recordTypes.Animation:{if(event.phase===TracingModel.Phase.NestableAsyncInstant){contentHelper.appendTextRow(ls`State`,eventData['state']);}
break;}
case recordTypes.ParseHTML:{const beginData=event.args['beginData'];const startLine=beginData['startLine']-1;const endLine=event.args['endData']?event.args['endData']['endLine']-1:undefined;url=beginData['url'];if(url){contentHelper.appendLocationRange(ls`Range`,url,startLine,endLine);}
break;}
case recordTypes.FireIdleCallback:{contentHelper.appendTextRow(ls`Allotted Time`,Number.millisToString(eventData['allottedMilliseconds']));contentHelper.appendTextRow(ls`Invoked by Timeout`,eventData['timedOut']);}
case recordTypes.RequestIdleCallback:case recordTypes.CancelIdleCallback:{contentHelper.appendTextRow(ls`Callback ID`,eventData['id']);break;}
case recordTypes.EventDispatch:{contentHelper.appendTextRow(ls`Type`,eventData['type']);break;}
case recordTypes.MarkLCPCandidate:{contentHelper.appendTextRow(ls`Type`,String(eventData['type']));contentHelper.appendTextRow(ls`Size`,String(eventData['size']));}
case recordTypes.MarkFirstPaint:case recordTypes.MarkFCP:case recordTypes.MarkFMP:case recordTypes.MarkLoad:case recordTypes.MarkDOMContent:{contentHelper.appendTextRow(ls`Timestamp`,Number.preciseMillisToString(event.startTime-model.minimumRecordTime(),1));contentHelper.appendElementRow(ls`Details`,TimelineUIUtils.buildDetailsNodeForPerformanceEvent(event));break;}
case recordTypes.LayoutShift:{const warning=createElement('span');const clsLink=UIUtils.createWebDevLink('cls/',ls`Cumulative Layout Shifts`);warning.appendChild(UIUtils.formatLocalized('%s can result in poor user experiences.',[clsLink]));contentHelper.appendElementRow(ls`Warning`,warning,true);contentHelper.appendTextRow(ls`Score`,eventData['score'].toPrecision(4));contentHelper.appendTextRow(ls`Cumulative Score`,eventData['cumulative_score'].toPrecision(4));contentHelper.appendTextRow(ls`Had recent input`,eventData['had_recent_input']?ls`Yes`:ls`No`);break;}
default:{const detailsNode=await TimelineUIUtils.buildDetailsNodeForTraceEvent(event,model.targetByEvent(event),linkifier);if(detailsNode){contentHelper.appendElementRow(ls`Details`,detailsNode);}
break;}}
if(timelineData.timeWaitingForMainThread){contentHelper.appendTextRow(ls`Time Waiting for Main Thread`,Number.millisToString(timelineData.timeWaitingForMainThread,true));}
const relatedNode=relatedNodesMap&&relatedNodesMap.get(timelineData.backendNodeId);if(relatedNode){const nodeSpan=await Linkifier$1.Linkifier.linkify(relatedNode);contentHelper.appendElementRow(relatedNodeLabel||ls`Related Node`,nodeSpan);}
if(event[previewElementSymbol]){contentHelper.addSection(ls`Preview`);contentHelper.appendElementRow('',event[previewElementSymbol]);}
if(initiator||timelineData.stackTraceForSelfOrInitiator()||TimelineModel.InvalidationTracker.invalidationEventsFor(event)){TimelineUIUtils._generateCauses(event,model.targetByEvent(event),relatedNodesMap,contentHelper);}
const stats={};const showPieChart=detailed&&TimelineUIUtils._aggregatedStatsForTraceEvent(stats,model,event);if(showPieChart){contentHelper.addSection(ls`Aggregated Time`);const pieChart=TimelineUIUtils.generatePieChart(stats,TimelineUIUtils.eventStyle(event).category,event.selfTime);contentHelper.appendElementRow('',pieChart);}
return contentHelper.fragment;}
static statsForTimeRange(events,startTime,endTime){if(!events.length){return{'idle':endTime-startTime};}
buildRangeStatsCacheIfNeeded(events);const aggregatedStats=subtractStats(aggregatedStatsAtTime(endTime),aggregatedStatsAtTime(startTime));const aggregatedTotal=Object.values(aggregatedStats).reduce((a,b)=>a+b,0);aggregatedStats['idle']=Math.max(0,endTime-startTime-aggregatedTotal);return aggregatedStats;function aggregatedStatsAtTime(time){const stats={};const cache=events[categoryBreakdownCacheSymbol];for(const category in cache){const categoryCache=cache[category];const index=categoryCache.time.upperBound(time);let value;if(index===0){value=0;}else if(index===categoryCache.time.length){value=categoryCache.value.peekLast();}else{const t0=categoryCache.time[index-1];const t1=categoryCache.time[index];const v0=categoryCache.value[index-1];const v1=categoryCache.value[index];value=v0+(v1-v0)*(time-t0)/(t1-t0);}
stats[category]=value;}
return stats;}
function subtractStats(a,b){const result=Object.assign({},a);for(const key in b){result[key]-=b[key];}
return result;}
function buildRangeStatsCacheIfNeeded(events){if(events[categoryBreakdownCacheSymbol]){return;}
const aggregatedStats={};const categoryStack=[];let lastTime=0;TimelineModel.TimelineModelImpl.forEachEvent(events,onStartEvent,onEndEvent,undefined,undefined,undefined,filterForStats());function filterForStats(){const visibleEventsFilter=TimelineUIUtils.visibleEventsFilter();return event=>visibleEventsFilter.accept(event)||TracingModel.TracingModel.isTopLevelEvent(event);}
function updateCategory(category,time){let statsArrays=aggregatedStats[category];if(!statsArrays){statsArrays={time:[],value:[]};aggregatedStats[category]=statsArrays;}
if(statsArrays.time.length&&statsArrays.time.peekLast()===time){return;}
const lastValue=statsArrays.value.length?statsArrays.value.peekLast():0;statsArrays.value.push(lastValue+time-lastTime);statsArrays.time.push(time);}
function categoryChange(from,to,time){if(from){updateCategory(from,time);}
lastTime=time;if(to){updateCategory(to,time);}}
function onStartEvent(e){const category=TimelineUIUtils.eventStyle(e).category.name;const parentCategory=categoryStack.length?categoryStack.peekLast():null;if(category!==parentCategory){categoryChange(parentCategory,category,e.startTime);}
categoryStack.push(category);}
function onEndEvent(e){const category=categoryStack.pop();const parentCategory=categoryStack.length?categoryStack.peekLast():null;if(category!==parentCategory){categoryChange(category,parentCategory,e.endTime);}}
const obj=(events);obj[categoryBreakdownCacheSymbol]=aggregatedStats;}}
static async buildNetworkRequestDetails(request,model,linkifier){const target=model.targetByEvent(request.children[0]);const contentHelper=new TimelineDetailsContentHelper(target,linkifier);const category=TimelineUIUtils.networkRequestCategory(request);const color=TimelineUIUtils.networkCategoryColor(category);contentHelper.addSection(ls`Network request`,color);if(request.url){contentHelper.appendElementRow(ls`URL`,Linkifier.Linkifier.linkifyURL(request.url));}
const fullDuration=request.endTime-(request.getStartTime()||-Infinity);if(isFinite(fullDuration)){let textRow=Number.millisToString(fullDuration,true);const networkDuration=request.finishTime-request.getStartTime();const processingDuration=request.endTime-request.finishTime;if(isFinite(networkDuration)&&isFinite(processingDuration)){const networkDurationStr=Number.millisToString(networkDuration,true);const processingDurationStr=Number.millisToString(processingDuration,true);const cacheOrNetworkLabel=request.cached()?ls`load from cache`:ls`network transfer`;textRow+=ls` (${networkDurationStr} ${cacheOrNetworkLabel} + ${processingDurationStr} resource loading)`;}
contentHelper.appendTextRow(ls`Duration`,textRow);}
if(request.requestMethod){contentHelper.appendTextRow(ls`Request Method`,request.requestMethod);}
if(typeof request.priority==='string'){const priority=NetworkPriorities.uiLabelForNetworkPriority((request.priority));contentHelper.appendTextRow(ls`Priority`,priority);}
if(request.mimeType){contentHelper.appendTextRow(ls`Mime Type`,request.mimeType);}
let lengthText='';if(request.memoryCached()){lengthText+=ls` (from memory cache)`;}else if(request.cached()){lengthText+=ls` (from cache)`;}else if(request.timing&&request.timing.pushStart){lengthText+=ls` (from push)`;}
if(request.fromServiceWorker){lengthText+=ls` (from service worker)`;}
if(request.encodedDataLength||!lengthText){lengthText=`${Number.bytesToString(request.encodedDataLength)}${lengthText}`;}
contentHelper.appendTextRow(ls`Encoded Data`,lengthText);if(request.decodedBodyLength){contentHelper.appendTextRow(ls`Decoded Body`,Number.bytesToString(request.decodedBodyLength));}
const title=ls`Initiator`;const sendRequest=request.children[0];const topFrame=TimelineModel.TimelineData.forEvent(sendRequest).topFrame();if(topFrame){const link=linkifier.maybeLinkifyConsoleCallFrame(target,topFrame,{tabStop:true});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,{tabStop:true});if(link){contentHelper.appendElementRow(title,link);}}}}
if(!request.previewElement&&request.url&&target){request.previewElement=await ImagePreview.ImagePreview.build(target,request.url,false,{imageAltText:ImagePreview.ImagePreview.defaultAltTextForImageURL(request.url)});}
if(request.previewElement){contentHelper.appendElementRow(ls`Preview`,request.previewElement);}
return contentHelper.fragment;}
static _stackTraceFromCallFrames(callFrames){return({callFrames:callFrames});}
static _generateCauses(event,target,relatedNodesMap,contentHelper){const recordTypes=TimelineModel.RecordType;let callSiteStackLabel;let stackLabel;switch(event.name){case recordTypes.TimerFire:callSiteStackLabel=ls`Timer Installed`;break;case recordTypes.FireAnimationFrame:callSiteStackLabel=ls`Animation Frame Requested`;break;case recordTypes.FireIdleCallback:callSiteStackLabel=ls`Idle Callback Requested`;break;case recordTypes.UpdateLayoutTree:case recordTypes.RecalculateStyles:stackLabel=ls`Recalculation Forced`;break;case recordTypes.Layout:callSiteStackLabel=ls`First Layout Invalidation`;stackLabel=ls`Layout Forced`;break;}
const timelineData=TimelineModel.TimelineData.forEvent(event);if(timelineData.stackTrace&&timelineData.stackTrace.length){contentHelper.addSection(ls`Call Stacks`);contentHelper.appendStackTrace(stackLabel||ls`Stack Trace`,TimelineUIUtils._stackTraceFromCallFrames(timelineData.stackTrace));}
const initiator=TimelineModel.TimelineData.forEvent(event).initiator();if(TimelineModel.InvalidationTracker.invalidationEventsFor(event)&&target){contentHelper.addSection(ls`Invalidations`);TimelineUIUtils._generateInvalidations(event,target,relatedNodesMap,contentHelper);}else if(initiator){const delay=event.startTime-initiator.startTime;contentHelper.appendTextRow(ls`Pending for`,Number.preciseMillisToString(delay,1));const link=createElementWithClass('span','devtools-link');ARIAUtils.markAsLink(link);link.tabIndex=0;link.textContent=ls`Reveal`;link.addEventListener('click',()=>{TimelinePanel.instance().select(TimelineSelection.fromTraceEvent((initiator)));});link.addEventListener('keydown',event=>{if(isEnterKey(event)){TimelinePanel.instance().select(TimelineSelection.fromTraceEvent((initiator)));event.consume(true);}});contentHelper.appendElementRow(ls`Initiator`,link);const initiatorStackTrace=TimelineModel.TimelineData.forEvent(initiator).stackTrace;if(initiatorStackTrace){contentHelper.appendStackTrace(callSiteStackLabel||ls`First Invalidated`,TimelineUIUtils._stackTraceFromCallFrames(initiatorStackTrace));}}}
static _generateInvalidations(event,target,relatedNodesMap,contentHelper){const invalidationTrackingEvents=TimelineModel.InvalidationTracker.invalidationEventsFor(event);const 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){TimelineUIUtils._generateInvalidationsForType(type,target,invalidations[type],relatedNodesMap,contentHelper);});}
static _generateInvalidationsForType(type,target,invalidations,relatedNodesMap,contentHelper){let title;switch(type){case TimelineModel.RecordType.StyleRecalcInvalidationTracking:title=ls`Style Invalidations`;break;case TimelineModel.RecordType.LayoutInvalidationTracking:title=ls`Layout Invalidations`;break;default:title=ls`Other Invalidations`;break;}
const invalidationsTreeOutline=new TreeOutline.TreeOutlineInShadow();invalidationsTreeOutline.registerRequiredCSS('timeline/invalidationsTree.css');invalidationsTreeOutline.element.classList.add('invalidations-tree');const invalidationGroups=groupInvalidationsByCause(invalidations);invalidationGroups.forEach(function(group){const groupElement=new InvalidationsGroupElement(target,relatedNodesMap,contentHelper,group);invalidationsTreeOutline.appendChild(groupElement);});contentHelper.appendElementRow(title,invalidationsTreeOutline.element,false,true);function groupInvalidationsByCause(invalidations){const causeToInvalidationMap=new Map();for(let index=0;index<invalidations.length;index++){const invalidation=invalidations[index];let 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.values()];}}
static _collectInvalidationNodeIds(nodeIds,invalidations){nodeIds.addAll(invalidations.map(invalidation=>invalidation.nodeId).filter(id=>id));}
static _aggregatedStatsForTraceEvent(total,model,event){const events=model.inspectedTargetEvents();function eventComparator(startTime,e){return startTime-e.startTime;}
const index=events.binaryIndexOf(event.startTime,eventComparator);if(index<0){return false;}
let hasChildren=false;const endTime=event.endTime;if(endTime){for(let i=index;i<events.length;i++){const nextEvent=events[i];if(nextEvent.startTime>=endTime){break;}
if(!nextEvent.selfTime){continue;}
if(nextEvent.thread!==event.thread){continue;}
if(i>index){hasChildren=true;}
const categoryName=TimelineUIUtils.eventStyle(nextEvent).category.name;total[categoryName]=(total[categoryName]||0)+nextEvent.selfTime;}}
if(TracingModel.TracingModel.isAsyncPhase(event.phase)){if(event.endTime){let aggregatedTotal=0;for(const 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){const snapshotWithRect=await new TimelineFrameModel.LayerPaintEvent(event,target).snapshotPromise();if(!snapshotWithRect){return null;}
const imageURLPromise=snapshotWithRect.snapshot.replay();snapshotWithRect.snapshot.release();const imageURL=await imageURLPromise;if(!imageURL){return null;}
const container=createElement('div');Utils.appendStyle(container,'components/imagePreview.css');container.classList.add('image-preview-container','vbox','link');const img=container.createChild('img');img.src=imageURL;img.alt=ImagePreview.ImagePreview.defaultAltTextForImageURL(imageURL);const paintProfilerButton=container.createChild('a');paintProfilerButton.textContent=ls`Paint Profiler`;ARIAUtils.markAsLink(container);container.tabIndex=0;container.addEventListener('click',()=>TimelinePanel.instance().select(TimelineSelection.fromTraceEvent(event)),false);container.addEventListener('keydown',keyEvent=>{if(isEnterKey(keyEvent)){TimelinePanel.instance().select(TimelineSelection.fromTraceEvent(event));keyEvent.consume(true);}});return container;}
static createEventDivider(event,zeroTime){const eventDivider=createElementWithClass('div','resources-event-divider');const startTime=Number.millisToString(event.startTime-zeroTime);eventDivider.title=UIString.UIString('%s at %s',TimelineUIUtils.eventTitle(event),startTime);const style=TimelineUIUtils.markerStyleForEvent(event);if(style.tall){eventDivider.style.backgroundColor=style.color;}
return eventDivider;}
static _visibleTypes(){const eventStyles=TimelineUIUtils._initEventStyles();const result=[];for(const name in eventStyles){if(!eventStyles[name].hidden){result.push(name);}}
return result;}
static visibleEventsFilter(){return new TimelineModelFilter.TimelineVisibleEventsFilter(TimelineUIUtils._visibleTypes());}
static categories(){if(TimelineUIUtils._categories){return TimelineUIUtils._categories;}
TimelineUIUtils._categories={loading:new TimelineCategory('loading',ls`Loading`,true,'hsl(214, 67%, 74%)','hsl(214, 67%, 66%)'),experience:new TimelineCategory('experience',ls`Experience`,true,'hsl(5, 80%, 74%)','hsl(5, 80%, 66%)'),scripting:new TimelineCategory('scripting',ls`Scripting`,true,'hsl(43, 83%, 72%)','hsl(43, 83%, 64%) '),rendering:new TimelineCategory('rendering',ls`Rendering`,true,'hsl(256, 67%, 76%)','hsl(256, 67%, 70%)'),painting:new TimelineCategory('painting',ls`Painting`,true,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),gpu:new TimelineCategory('gpu',ls`GPU`,false,'hsl(109, 33%, 64%)','hsl(109, 33%, 55%)'),async:new TimelineCategory('async',ls`Async`,false,'hsl(0, 100%, 50%)','hsl(0, 100%, 40%)'),other:new TimelineCategory('other',ls`System`,false,'hsl(0, 0%, 87%)','hsl(0, 0%, 79%)'),idle:new TimelineCategory('idle',ls`Idle`,false,'hsl(0, 0%, 98%)','hsl(0, 0%, 98%)')};return TimelineUIUtils._categories;}
static setCategories(categories){TimelineUIUtils._categories=categories;}
static getTimelineMainEventCategories(){if(TimelineUIUtils._eventCategories){return TimelineUIUtils._eventCategories;}
TimelineUIUtils._eventCategories=['idle','loading','painting','rendering','scripting','other'];return TimelineUIUtils._eventCategories;}
static setTimelineMainEventCategories(categories){TimelineUIUtils._eventCategories=categories;}
static generatePieChart(aggregatedStats,selfCategory,selfTime){let total=0;for(const categoryName in aggregatedStats){total+=aggregatedStats[categoryName];}
const element=createElementWithClass('div','timeline-details-view-pie-chart-wrapper hbox');const pieChart=new PieChart.PieChart({chartName:ls`Time spent in rendering`,size:110,formatter:value=>Number.preciseMillisToString(value),showLegend:true,});pieChart.element.classList.add('timeline-details-view-pie-chart');pieChart.initializeWithTotal(total);const pieChartContainer=element.createChild('div','vbox');pieChartContainer.appendChild(pieChart.element);function appendLegendRow(name,title,value,color){if(!value){return;}
pieChart.addSlice(value,color,title);}
if(selfCategory){if(selfTime){appendLegendRow(selfCategory.name,UIString.UIString('%s (self)',selfCategory.title),selfTime,selfCategory.color);}
const categoryTime=aggregatedStats[selfCategory.name];const value=categoryTime-selfTime;if(value>0){appendLegendRow(selfCategory.name,UIString.UIString('%s (children)',selfCategory.title),value,selfCategory.childColor);}}
for(const categoryName in TimelineUIUtils.categories()){const category=TimelineUIUtils.categories()[categoryName];if(category===selfCategory){continue;}
appendLegendRow(category.name,category.title,aggregatedStats[category.name],category.childColor);}
return element;}
static generateDetailsContentForFrame(frame,filmStripFrame){const contentHelper=new TimelineDetailsContentHelper(null,null);contentHelper.addSection(ls`Frame`);const duration=TimelineUIUtils.frameDuration(frame);contentHelper.appendElementRow(ls`Duration`,duration,frame.hasWarnings());const durationInMillis=frame.endTime-frame.startTime;contentHelper.appendTextRow(ls`FPS`,Math.floor(1000/durationInMillis));contentHelper.appendTextRow(ls`CPU time`,Number.millisToString(frame.cpuTime,true));if(filmStripFrame){const filmStripPreview=createElementWithClass('div','timeline-filmstrip-preview');filmStripFrame.imageDataPromise().then(data=>UIUtils.loadImageFromData(data)).then(image=>image&&filmStripPreview.appendChild(image));contentHelper.appendElementRow('',filmStripPreview);filmStripPreview.addEventListener('click',frameClicked.bind(null,filmStripFrame),false);}
if(frame.layerTree){contentHelper.appendElementRow(ls`Layer tree`,Linkifier.Linkifier.linkifyRevealable(frame.layerTree,ls`Show`));}
function frameClicked(filmStripFrame){new FilmStripView.Dialog(filmStripFrame,0);}
return contentHelper.fragment;}
static frameDuration(frame){const durationText=UIString.UIString('%s (at %s)',Number.millisToString(frame.endTime-frame.startTime,true),Number.millisToString(frame.startTimeOffset,true));if(!frame.hasWarnings()){return UIUtils.formatLocalized('%s',[durationText]);}
const link=XLink.XLink.create('https://developers.google.com/web/fundamentals/performance/rendering/',ls`jank`);return UIUtils.formatLocalized('%s. Long frame times are an indication of %s',[durationText,link]);}
static createFillStyle(context,width,height,color0,color1,color2){const 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(TimelineUIUtils._eventDispatchDesciptors){return TimelineUIUtils._eventDispatchDesciptors;}
const lightOrange='hsl(40,100%,80%)';const orange='hsl(40,100%,50%)';const green='hsl(90,100%,40%)';const purple='hsl(256,100%,75%)';TimelineUIUtils._eventDispatchDesciptors=[new EventDispatchTypeDescriptor(1,lightOrange,['mousemove','mouseenter','mouseleave','mouseout','mouseover']),new EventDispatchTypeDescriptor(1,lightOrange,['pointerover','pointerout','pointerenter','pointerleave','pointermove']),new EventDispatchTypeDescriptor(2,green,['wheel']),new EventDispatchTypeDescriptor(3,orange,['click','mousedown','mouseup']),new EventDispatchTypeDescriptor(3,orange,['touchstart','touchend','touchmove','touchcancel']),new EventDispatchTypeDescriptor(3,orange,['pointerdown','pointerup','pointercancel','gotpointercapture','lostpointercapture']),new EventDispatchTypeDescriptor(3,purple,['keydown','keyup','keypress'])];return TimelineUIUtils._eventDispatchDesciptors;}
static markerShortTitle(event){const recordTypes=TimelineModel.RecordType;switch(event.name){case recordTypes.MarkDOMContent:return ls`DCL`;case recordTypes.MarkLoad:return ls`L`;case recordTypes.MarkFirstPaint:return ls`FP`;case recordTypes.MarkFCP:return ls`FCP`;case recordTypes.MarkFMP:return ls`FMP`;case recordTypes.MarkLCPCandidate:return ls`LCP`;}
return null;}
static markerStyleForEvent(event){const tallMarkerDashStyle=[6,4];const title=TimelineUIUtils.eventTitle(event);if(event.hasCategory(TimelineModel.TimelineModelImpl.Category.Console)||event.hasCategory(TimelineModel.TimelineModelImpl.Category.UserTiming)){return{title:title,dashStyle:tallMarkerDashStyle,lineWidth:0.5,color:event.hasCategory(TimelineModel.TimelineModelImpl.Category.UserTiming)?'purple':'orange',tall:false,lowPriority:false,};}
const recordTypes=TimelineModel.RecordType;let tall=false;let color='grey';switch(event.name){case recordTypes.FrameStartedLoading:color='green';tall=true;break;case recordTypes.MarkDOMContent:color='#0867CB';tall=true;break;case recordTypes.MarkLoad:color='#B31412';tall=true;break;case recordTypes.MarkFirstPaint:color='#228847';tall=true;break;case recordTypes.MarkFCP:color='#1A6937';tall=true;break;case recordTypes.MarkFMP:color='#134A26';tall=true;break;case recordTypes.MarkLCPCandidate:color='#1A3422';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:ls`Frame`,color:'rgba(100, 100, 100, 0.4)',lineWidth:3,dashStyle:[3],tall:true,lowPriority:true};}
static colorForId(id){if(!TimelineUIUtils.colorForId._colorGenerator){TimelineUIUtils.colorForId._colorGenerator=new Color.Generator({min:30,max:330},{min:50,max:80,count:3},85);TimelineUIUtils.colorForId._colorGenerator.setColorForID('','#f2ecdc');}
return TimelineUIUtils.colorForId._colorGenerator.colorForID(id);}
static eventWarning(event,warningType){const timelineData=TimelineModel.TimelineData.forEvent(event);const warning=warningType||timelineData.warning;if(!warning){return null;}
const warnings=TimelineModel.TimelineModelImpl.WarningType;const span=createElement('span');const eventData=event.args['data'];switch(warning){case warnings.ForcedStyle:case warnings.ForcedLayout:{const forcedReflowLink=UIUtils.createDocumentationLink('../../fundamentals/performance/rendering/avoid-large-complex-layouts-and-layout-thrashing#avoid-forced-synchronous-layouts',ls`Forced reflow`);span.appendChild(UIUtils.formatLocalized('%s is a likely performance bottleneck.',[forcedReflowLink]));break;}
case warnings.IdleDeadlineExceeded:{const exceededMs=Number.millisToString(event.duration-eventData['allottedMilliseconds'],true);span.textContent=ls`Idle callback execution extended beyond deadline by ${exceededMs}`;break;}
case warnings.LongHandler:{span.textContent=UIString.UIString('Handler took %s',Number.millisToString(event.duration,true));break;}
case warnings.LongRecurringHandler:{span.textContent=UIString.UIString('Recurring handler took %s',Number.millisToString(event.duration,true));break;}
case warnings.LongTask:{const longTaskLink=UIUtils.createDocumentationLink('../../fundamentals/performance/rail#goals-and-guidelines',ls`Long task`);span.appendChild(UIUtils.formatLocalized('%s took %s.',[longTaskLink,Number.millisToString(event.duration,true)]));break;}
case warnings.V8Deopt:{span.appendChild(XLink.XLink.create('https://github.com/GoogleChrome/devtools-docs/issues/53',UIString.UIString('Not optimized')));span.createTextChild(UIString.UIString(': %s',eventData['deoptReason']));break;}
default:{console.assert(false,'Unhandled TimelineModel.WarningType');}}
return span;}
static displayNameForFrame(frame,trimAt){const url=frame.url;if(!trimAt){trimAt=30;}
return url.startsWith('about:')?`"${frame.name.trimMiddle(trimAt)}"`:frame.url.trimEnd(trimAt);}}
class TimelineRecordStyle{constructor(title,category,hidden=false){this.title=title;this.category=category;this.hidden=hidden;}}
const NetworkCategory={HTML:Symbol('HTML'),Script:Symbol('Script'),Style:Symbol('Style'),Media:Symbol('Media'),Other:Symbol('Other')};const aggregatedStatsKey=Symbol('aggregatedStats');class InvalidationsGroupElement extends TreeOutline.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){const first=this._invalidations[0];const reason=first.cause.reason||ls`Unknown cause`;const topFrame=first.cause.stackTrace&&first.cause.stackTrace[0];const truncatedNodesElement=this._getTruncatedNodesElement(this._invalidations);if(truncatedNodesElement===null){return UIUtils.formatLocalized(reason,[]);}
const title=UIUtils.formatLocalized('%s for %s',[reason,truncatedNodesElement]);if(topFrame&&this._contentHelper.linkifier()){const stack=createElementWithClass('span','monospace');const completeTitle=UIUtils.formatLocalized('%s. %s',[title,stack]);stack.createChild('span').textContent=TimelineUIUtils.frameDisplayName(topFrame);const link=this._contentHelper.linkifier().maybeLinkifyConsoleCallFrame(target,topFrame);if(link){stack.createChild('span').textContent=' @ ';stack.createChild('span').appendChild(link);}
return completeTitle;}
return title;}
async onpopulate(){const content=createElementWithClass('div','content');const first=this._invalidations[0];if(first.cause.stackTrace){const stack=content.createChild('div');stack.createTextChild(ls`Stack trace:`);this._contentHelper.createChildStackTraceElement(stack,TimelineUIUtils._stackTraceFromCallFrames(first.cause.stackTrace));}
content.createTextChild(this._invalidations.length!==1?ls`Nodes:`:ls`Node:`);const nodeList=content.createChild('div','node-list');let firstNode=true;for(let i=0;i<this._invalidations.length;i++){const invalidation=this._invalidations[i];const invalidationNode=this._createInvalidationNode(invalidation,true);if(invalidationNode){if(!firstNode){nodeList.createTextChild(ls`, `);}
firstNode=false;nodeList.appendChild(invalidationNode);const extraData=invalidation.extraData?', '+invalidation.extraData:'';if(invalidation.changedId){nodeList.createTextChild(UIString.UIString('(changed id to "%s"%s)',invalidation.changedId,extraData));}else if(invalidation.changedClass){nodeList.createTextChild(UIString.UIString('(changed class to "%s"%s)',invalidation.changedClass,extraData));}else if(invalidation.changedAttribute){nodeList.createTextChild(UIString.UIString('(changed attribute to "%s"%s)',invalidation.changedAttribute,extraData));}else if(invalidation.changedPseudo){nodeList.createTextChild(UIString.UIString('(changed pesudo to "%s"%s)',invalidation.changedPseudo,extraData));}else if(invalidation.selectorPart){nodeList.createTextChild(UIString.UIString('(changed "%s"%s)',invalidation.selectorPart,extraData));}}}
const contentTreeElement=new TreeOutline.TreeElement(content,false);contentTreeElement.selectable=false;this.appendChild(contentTreeElement);}
_getTruncatedNodesElement(invalidations){const invalidationNodes=[];const invalidationNodeIdMap={};for(let i=0;i<invalidations.length;i++){const invalidation=invalidations[i];const 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){return invalidationNodes[0];}
if(invalidationNodes.length===2){return UIUtils.formatLocalized('%s and %s',invalidationNodes);}
if(invalidationNodes.length===3){return UIUtils.formatLocalized('%s, %s, and 1 other',invalidationNodes.slice(0,2));}
if(invalidationNodes.length>=4){return UIUtils.formatLocalized('%s, %s, and %s others',[...invalidationNodes.slice(0,2),(invalidationNodes.length-2).toString()]);}
return null;}
_createInvalidationNode(invalidation,showUnknownNodes){const node=(invalidation.nodeId&&this._relatedNodesMap)?this._relatedNodesMap.get(invalidation.nodeId):null;if(node){const nodeSpan=createElement('span');Linkifier$1.Linkifier.linkify(node).then(link=>nodeSpan.appendChild(link));return nodeSpan;}
if(invalidation.nodeName){const nodeSpan=createElement('span');nodeSpan.textContent=UIString.UIString('[ %s ]',invalidation.nodeName);return nodeSpan;}
if(showUnknownNodes){const nodeSpan=createElement('span');return nodeSpan.createTextChild(UIString.UIString('[ unknown node ]'));}}}
const previewElementSymbol=Symbol('previewElement');class EventDispatchTypeDescriptor{constructor(priority,color,eventTypes){this.priority=priority;this.color=color;this.eventTypes=eventTypes;}}
class TimelineCategory extends ObjectWrapper.ObjectWrapper{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(TimelineCategory.Events.VisibilityChanged,this);}}
TimelineCategory.Events={VisibilityChanged:Symbol('VisibilityChanged')};class TimelinePopupContentHelper{constructor(title){this._contentTable=createElement('table');const titleCell=this._createCell(UIString.UIString('%s - Details',title),'timeline-details-title');titleCell.colSpan=2;const titleRow=createElement('tr');titleRow.appendChild(titleCell);this._contentTable.appendChild(titleRow);}
contentTable(){return this._contentTable;}
_createCell(content,styleName){const text=createElement('label');text.createTextChild(String(content));const cell=createElement('td');cell.className='timeline-details';if(styleName){cell.className+=' '+styleName;}
cell.textContent=content;return cell;}
appendTextRow(title,content){const 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){const row=createElement('tr');const titleCell=this._createCell(title,'timeline-details-row-title');row.appendChild(titleCell);const cell=createElement('td');cell.className='details';if(content instanceof Node){cell.appendChild(content);}else{cell.createTextChild(content||'');}
row.appendChild(cell);this._contentTable.appendChild(row);}}
class TimelineDetailsContentHelper{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){const 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){const 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){const 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');}
const titleElement=rowElement.createChild('div','timeline-details-view-row-title');titleElement.textContent=title;const 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;}
const link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine,{columnNumber:startColumn,tabStop:true});if(!link){return;}
this.appendElementRow(title,link);}
appendLocationRange(title,url,startLine,endLine){if(!this._linkifier||!this._target){return;}
const locationContent=createElement('span');const link=this._linkifier.maybeLinkifyScriptLocation(this._target,null,url,startLine,{tabStop:true});if(!link){return;}
locationContent.appendChild(link);locationContent.createTextChild(StringUtilities.sprintf(' [%s…%s]',startLine+1,endLine+1||''));this.appendElementRow(title,locationContent);}
appendStackTrace(title,stackTrace){if(!this._linkifier||!this._target){return;}
const 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');const stackTraceElement=parentElement.createChild('div','timeline-details-view-row-value timeline-details-view-row-stack-trace');const callFrameContents=JSPresentationUtils.buildStackTracePreviewContents(this._target,this._linkifier,{stackTrace,tabStops:true});stackTraceElement.appendChild(callFrameContents.element);}
appendWarningRow(event,warningType){const warning=TimelineUIUtils.eventWarning(event,warningType);if(warning){this.appendElementRow(ls`Warning`,warning,true);}}}
const categoryBreakdownCacheSymbol=Symbol('categoryBreakdownCache');let TimelineMarkerStyle;var TimelineUIUtils$1=Object.freeze({__proto__:null,TimelineUIUtils:TimelineUIUtils,TimelineRecordStyle:TimelineRecordStyle,NetworkCategory:NetworkCategory,aggregatedStatsKey:aggregatedStatsKey,InvalidationsGroupElement:InvalidationsGroupElement,previewElementSymbol:previewElementSymbol,EventDispatchTypeDescriptor:EventDispatchTypeDescriptor,TimelineCategory:TimelineCategory,TimelinePopupContentHelper:TimelinePopupContentHelper,TimelineDetailsContentHelper:TimelineDetailsContentHelper,categoryBreakdownCacheSymbol:categoryBreakdownCacheSymbol,TimelineMarkerStyle:TimelineMarkerStyle});class PerformanceModel extends ObjectWrapper.ObjectWrapper{constructor(){super();this._mainTarget=null;this._tracingModel=null;this._filters=[];this._timelineModel=new TimelineModel.TimelineModelImpl();this._frameModel=new TimelineFrameModel.TimelineFrameModel(event=>TimelineUIUtils.eventStyle(event).category.name);this._filmStripModel=null;this._irModel=new TimelineIRModel.TimelineIRModel();this._window={left:0,right:Infinity};this._extensionTracingModels=[];this._recordStartTime=undefined;}
setMainTarget(target){this._mainTarget=target;}
mainTarget(){return this._mainTarget;}
setRecordStartTime(time){this._recordStartTime=time;}
recordStartTime(){return this._recordStartTime;}
setFilters(filters){this._filters=filters;}
filters(){return this._filters;}
isVisible(event){return this._filters.every(f=>f.accept(event));}
setTracingModel(model){this._tracingModel=model;this._timelineModel.setEvents(model);let inputEvents=null;let animationEvents=null;for(const track of this._timelineModel.tracks()){if(track.type===TimelineModel.TrackType.Input){inputEvents=track.asyncEvents;}
if(track.type===TimelineModel.TrackType.Animation){animationEvents=track.asyncEvents;}}
if(inputEvents||animationEvents){this._irModel.populate(inputEvents||[],animationEvents||[]);}
const mainTracks=this._timelineModel.tracks().filter(track=>track.type===TimelineModel.TrackType.MainThread&&track.forMainFrame&&track.events.length);const threadData=mainTracks.map(track=>{const event=track.events[0];return{thread:event.thread,time:event.startTime};});this._frameModel.addTraceEvents(this._mainTarget,this._timelineModel.inspectedTargetEvents(),threadData);for(const entry of this._extensionTracingModels){entry.model.adjustTime(this._tracingModel.minimumRecordTime()+(entry.timeOffset/1000)-this._recordStartTime);}
this._autoWindowTimes();}
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(Events$1.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 FilmStripModel.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.dispose();}
for(const extensionEntry of this._extensionTracingModels){extensionEntry.model.dispose();}}
filmStripModelFrame(frame){const screenshotTime=frame.idle?frame.startTime:frame.endTime;const filmStripFrame=this._filmStripModel.frameByTimestamp(screenshotTime);return filmStripFrame&&filmStripFrame.timestamp-frame.endTime<10?filmStripFrame:null;}
save(stream){const backingStorage=(this._tracingModel.backingStorage());return backingStorage.writeToStream(stream);}
setWindow(window,animate){this._window=window;this.dispatchEventToListeners(Events$1.WindowChanged,{window,animate});}
window(){return this._window;}
_autoWindowTimes(){const timelineModel=this._timelineModel;let tasks=[];for(const track of timelineModel.tracks()){if(track.type===TimelineModel.TrackType.MainThread&&track.forMainFrame){tasks=track.tasks;}}
if(!tasks.length){this.setWindow({left:timelineModel.minimumRecordTime(),right:timelineModel.maximumRecordTime()});return;}
function findLowUtilizationRegion(startIndex,stopIndex){const threshold=0.1;let cutIndex=startIndex;let cutTime=(tasks[cutIndex].startTime+tasks[cutIndex].endTime)/2;let usedTime=0;const step=Math.sign(stopIndex-startIndex);for(let i=startIndex;i!==stopIndex;i+=step){const task=tasks[i];const taskTime=(task.startTime+task.endTime)/2;const interval=Math.abs(cutTime-taskTime);if(usedTime<threshold*interval){cutIndex=i;cutTime=taskTime;usedTime=0;}
usedTime+=task.duration;}
return cutIndex;}
const rightIndex=findLowUtilizationRegion(tasks.length-1,0);const leftIndex=findLowUtilizationRegion(0,rightIndex);let leftTime=tasks[leftIndex].startTime;let rightTime=tasks[rightIndex].endTime;const span=rightTime-leftTime;const 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.setWindow({left:leftTime,right:rightTime});}}
const Events$1={ExtensionDataAdded:Symbol('ExtensionDataAdded'),WindowChanged:Symbol('WindowChanged')};let Window;var PerformanceModel$1=Object.freeze({__proto__:null,PerformanceModel:PerformanceModel,Events:Events$1,Window:Window});class CountersGraph extends Widget.VBox{constructor(delegate){super();this.element.id='memory-graphs-container';this._delegate=delegate;this._calculator=new Calculator();this._header=new Widget.HBox();this._header.element.classList.add('timeline-memory-header');this._header.show(this.element);this._toolbar=new Toolbar.Toolbar('timeline-memory-toolbar');this._header.element.appendChild(this._toolbar.element);this._graphsContainer=new Widget.VBox();this._graphsContainer.show(this.element);const canvasWidget=new Widget.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 TimelineGrid.TimelineGrid();this._canvasContainer.appendChild(this._timelineGrid.dividersElement);this._counters=[];this._counterUI=[];this._countersByName={};this._countersByName['jsHeapSizeUsed']=this._createCounter(UIString.UIString('JS Heap'),UIString.UIString('JS Heap: %s'),'hsl(220, 90%, 43%)',Number.bytesToString);this._countersByName['documents']=this._createCounter(UIString.UIString('Documents'),UIString.UIString('Documents: %s'),'hsl(0, 90%, 43%)');this._countersByName['nodes']=this._createCounter(UIString.UIString('Nodes'),UIString.UIString('Nodes: %s'),'hsl(120, 90%, 43%)');this._countersByName['jsEventListeners']=this._createCounter(UIString.UIString('Listeners'),UIString.UIString('Listeners: %s'),'hsl(38, 90%, 43%)');this._gpuMemoryCounter=this._createCounter(UIString.UIString('GPU Memory'),UIString.UIString('GPU Memory [KB]: %s'),'hsl(300, 90%, 43%)',Number.bytesToString);this._countersByName['gpuMemoryUsedKB']=this._gpuMemoryCounter;}
setModel(model,track){if(this._model!==model){if(this._model){this._model.removeEventListener(Events$1.WindowChanged,this._onWindowChanged,this);}
this._model=model;if(this._model){this._model.addEventListener(Events$1.WindowChanged,this._onWindowChanged,this);}}
this._calculator.setZeroTime(model?model.timelineModel().minimumRecordTime():0);for(let i=0;i<this._counters.length;++i){this._counters[i].reset();this._counterUI[i].reset();}
this.scheduleRefresh();this._track=track;if(!track){return;}
const events=track.syncEvents();for(let i=0;i<events.length;++i){const event=events[i];if(event.name!==TimelineModel.RecordType.UpdateCounters){continue;}
const counters=event.args.data;if(!counters){return;}
for(const name in counters){const counter=this._countersByName[name];if(counter){counter.appendSample(event.startTime,counters[name]);}}
const 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){const counter=new Counter();this._counters.push(counter);this._counterUI.push(new CounterUI(this,uiName,uiValueTemplate,color,counter,formatter));return counter;}
resizerElement(){return this._header.element;}
_resize(){const 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();}
_onWindowChanged(event){const window=(event.data.window);this._calculator.setWindow(window.left,window.right);this.scheduleRefresh();}
scheduleRefresh(){UIUtils.invokeOnceAfterBatchUpdate(this,this.refresh);}
draw(){this._clear();for(const counter of this._counters){counter._calculateVisibleIndexes(this._calculator);counter._calculateXValues(this._canvas.width);}
for(const counterUI of this._counterUI){counterUI._drawGraph(this._canvas);}}
_onClick(event){const x=event.x-this._canvasContainer.totalOffsetLeft();let minDistance=Infinity;let bestTime;for(const counterUI of this._counterUI){if(!counterUI.counter.times.length){continue;}
const index=counterUI._recordIndexAt(x);const 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(this._track.events.length?this._track.events:this._track.asyncEvents,bestTime);}}
_onMouseLeave(event){delete this._markerXPosition;this._clearCurrentValueAndMarker();}
_clearCurrentValueAndMarker(){for(let i=0;i<this._counterUI.length;i++){this._counterUI[i]._clearCurrentValueAndMarker();}}
_onMouseMove(event){const x=event.x-this._canvasContainer.totalOffsetLeft();this._markerXPosition=x;this._refreshCurrentValues();}
_refreshCurrentValues(){if(this._markerXPosition===undefined){return;}
for(let i=0;i<this._counterUI.length;++i){this._counterUI[i].updateCurrentValue(this._markerXPosition);}}
refresh(){this._timelineGrid.updateDividers(this._calculator);this.draw();this._refreshCurrentValues();}
_clear(){const ctx=this._canvas.getContext('2d');ctx.clearRect(0,0,ctx.canvas.width,ctx.canvas.height);}}
class Counter{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(){let maxValue;let minValue;for(let i=this._minimumIndex;i<=this._maximumIndex;i++){const 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){const start=calculator.minimumBoundary();const end=calculator.maximumBoundary();this._minimumIndex=NumberUtilities.clamp(this.times.upperBound(start)-1,0,this.times.length-1);this._maximumIndex=NumberUtilities.clamp(this.times.lowerBound(end),0,this.times.length-1);this._minTime=start;this._maxTime=end;}
_calculateXValues(width){if(!this.values.length){return;}
const xFactor=width/(this._maxTime-this._minTime);this.x=new Array(this.values.length);for(let i=this._minimumIndex+1;i<=this._maximumIndex;i++){this.x[i]=xFactor*(this.times[i]-this._minTime);}}}
class CounterUI{constructor(countersPane,title,currentValueLabel,graphColor,counter,formatter){this._countersPane=countersPane;this.counter=counter;this._formatter=formatter||Number.withThousandsSeparator;this._setting=Settings.Settings.instance().createSetting('timelineCountersGraph-'+title,true);this._setting.setTitle(title);this._filter=new Toolbar.ToolbarSettingCheckbox(this._setting,title);this._filter.inputElement.classList.add('-theme-preserve');const color=Color.Color.parse(graphColor).setAlpha(0.5).asString(Color.Format.RGBA);if(color){this._filter.element.backgroundColor=color;this._filter.element.borderColor='transparent';}
this._filter.inputElement.addEventListener('click',this._toggleCounterGraph.bind(this));countersPane._toolbar.appendToolbarItem(this._filter);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=Color.Color.parse(graphColor).setAlpha(0.3).asString(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){const min=this._formatter(minValue);const max=this._formatter(maxValue);this._range.textContent=UIString.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;}
const index=this._recordIndexAt(x);const value=Number.withThousandsSeparator(this.counter.values[index]);this._value.textContent=UIString.UIString(this._currentValueLabel,value);const 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){const ctx=canvas.getContext('2d');const width=canvas.width;const height=canvas.height-2*this._verticalPadding;if(height<=0){this.graphYValues=[];return;}
const originY=this._verticalPadding;const counter=this.counter;const values=counter.values;if(!values.length){return;}
const bounds=counter._calculateBounds();const minValue=bounds.min;const maxValue=bounds.max;this.setRange(minValue,maxValue);if(!this.visible()){return;}
const yValues=this.graphYValues;const maxYRange=maxValue-minValue;const yFactor=maxYRange?height/(maxYRange):1;ctx.save();ctx.lineWidth=window.devicePixelRatio;if(ctx.lineWidth%2){ctx.translate(0.5,0.5);}
ctx.beginPath();let value=values[counter._minimumIndex];let currentY=Math.round(originY+height-(value-minValue)*yFactor);ctx.moveTo(0,currentY);let i=counter._minimumIndex;for(;i<=counter._maximumIndex;i++){const x=Math.round(counter.x[i]);ctx.lineTo(x,currentY);const 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){const 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();}}
class Calculator{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;}}
var CountersGraph$1=Object.freeze({__proto__:null,CountersGraph:CountersGraph,Counter:Counter,CounterUI:CounterUI,Calculator:Calculator});export{CountersGraph$1 as CountersGraph,EventsTimelineTreeView$1 as EventsTimelineTreeView,ExtensionTracingSession$1 as ExtensionTracingSession,PerformanceModel$1 as PerformanceModel,TimelineController$1 as TimelineController,TimelineDetailsView$1 as TimelineDetailsView,TimelineEventOverview$1 as TimelineEventOverview,TimelineFilters,TimelineFlameChartDataProvider$1 as TimelineFlameChartDataProvider,TimelineFlameChartNetworkDataProvider$1 as TimelineFlameChartNetworkDataProvider,TimelineFlameChartView$1 as TimelineFlameChartView,TimelineHistoryManager$1 as TimelineHistoryManager,TimelineLayersView$1 as TimelineLayersView,TimelineLoader$1 as TimelineLoader,TimelinePaintProfilerView$1 as TimelinePaintProfilerView,TimelinePanel$1 as TimelinePanel,TimelineTreeView$1 as TimelineTreeView,TimelineUIUtils$1 as TimelineUIUtils,UIDevtoolsController$1 as UIDevtoolsController,UIDevtoolsUtils$1 as UIDevtoolsUtils};