var W=Object.defineProperty;var K=(o,e)=>{for(var t in e)W(o,t,{get:e[t],enumerable:!0})};var A={};K(A,{ControlPane:()=>D,PerformanceMonitorImpl:()=>z,format:()=>Z,formatNumber:()=>B});import*as M from"./../../core/common/common.js";import*as $ from"./../../core/host/host.js";import*as T from"./../../core/i18n/i18n.js";import*as I from"./../../core/platform/platform.js";import*as v from"./../../core/sdk/sdk.js";import*as U from"./../../ui/legacy/legacy.js";import*as c from"./../../ui/legacy/theme_support/theme_support.js";import{Directives as _,html as V,render as q}from"./../../ui/lit/lit.js";import*as H from"./../../ui/visual_logging/visual_logging.js";var j=`:host{overflow:hidden;--override-color-perf-monitor-cpu:var(--ref-palette-yellow40);--override-color-perf-monitor-cpu-task-duration:var(--sys-color-neutral-bright);--override-color-perf-monitor-cpu-script-duration:var(--sys-color-yellow-bright);--override-color-perf-monitor-cpu-layout-duration:var(--sys-color-purple);--override-color-perf-monitor-cpu-recalc-style-duration:var(--sys-color-purple-bright);--override-color-perf-monitor-jsheap:var(--sys-color-purple-bright);--override-color-perf-monitor-jsheap-total-size:var(--ref-palette-purple70);--override-color-perf-monitor-jsheap-used-size:var(--sys-color-purple-bright);--override-color-perf-monitor-dom-nodes:var(--sys-color-green);--override-color-perf-monitor-js-event-listeners:var(--ref-palette-green50);--override-color-perf-monitor-documents:var(--sys-color-blue);--override-color-perf-monitor-document-frames:var(--sys-color-cyan-bright);--override-color-perf-monitor-layout-count:var(--ref-palette-pink50);--override-color-perf-monitor-recalc-style-count:var(--sys-color-pink)}:host-context(.theme-with-dark-background){--override-color-perf-monitor-cpu:var(--sys-color-yellow-bright);--override-color-perf-monitor-js-event-listeners:var(--ref-palette-green70);--override-color-perf-monitor-jsheap-total-size:var(--ref-palette-purple50);--override-color-perf-monitor-layout-count:var(--sys-color-pink-bright)}.suspended{opacity:40%;pointer-events:none}.perfmon-chart-suspend-overlay{display:flex;font-size:26px;align-items:center;justify-content:center}.perfmon-control-pane{display:flex;flex:initial;flex-direction:column;padding:6px 0;overflow:hidden auto}.perfmon-chart-container{display:flex;flex:1 1;border-left:1px solid var(--sys-color-divider);overflow-y:auto}.perfmon-chart-container canvas{width:100%}.perfmon-indicator{padding:3px 9px;margin:-1px 0;display:flex;flex-shrink:0;width:210px}.perfmon-indicator span{flex:0 0 135px}.perfmon-indicator-value{flex:0 0 55px;text-align:right;overflow:visible;align-self:center;margin-left:auto}.perfmon-indicator:not(.active) .perfmon-indicator-value{opacity:0%}
/*# sourceURL=${import.meta.resolve("./performanceMonitor.css")} */`;var u={graphsDisplayingARealtimeViewOf:"Graphs displaying a real-time view of performance metrics",paused:"Paused",cpuUsage:"CPU usage",jsHeapSize:"JS heap size",domNodes:"DOM Nodes",jsEventListeners:"JS event listeners",documents:"Documents",documentFrames:"Document Frames",layoutsSec:"Layouts / sec",styleRecalcsSec:"Style recalcs / sec"},G=T.i18n.registerUIStrings("panels/performance_monitor/PerformanceMonitor.ts",u),f=T.i18n.getLocalizedString.bind(void 0,G),{widget:J}=U.Widget,{classMap:E,ref:O}=_,Y=(o,e,t)=>{q(V`
    <devtools-widget ${J(D,{onMetricChanged:o.onMetricChanged,chartsInfo:o.chartsInfo,metrics:o.metrics})} class=${E({suspended:o.suspended})}></devtools-widget>
    <div class="perfmon-chart-container ${E({suspended:o.suspended})}">
      <canvas tabindex="-1" aria-label=${f(u.graphsDisplayingARealtimeViewOf)}
          .width=${Math.round(o.width*window.devicePixelRatio)} .height=${o.height}
          style="height:${o.height/window.devicePixelRatio}px" ${O(r=>{if(r){let i=r;e.graphRenderingContext=i.getContext("2d"),e.width=i.offsetWidth}})}>
      </canvas>
    </div>
    ${o.suspended?V`
      <div class="perfmon-chart-suspend-overlay fill">
        <div>${f(u.paused)}</div>
      </div>`:""}`,t,{container:{attributes:{jslog:`${H.pane("performance.monitor").track({resize:!0})}`}}})},z=class extends U.Widget.HBox{view;chartInfos=[];activeCharts=new Set;metricsBuffer;pixelsPerMs;pollIntervalMs;scaleHeight;graphHeight;gridColor;animationId;width;height;model;pollTimer;metrics;suspended=!1;graphRenderingContext=null;constructor(e=500,t=Y){super({useShadowDom:"pure"}),this.view=t,this.registerRequiredCSS(j),this.metricsBuffer=[],this.pixelsPerMs=10/1e3,this.pollIntervalMs=e,this.scaleHeight=16,this.graphHeight=90,this.gridColor=c.ThemeSupport.instance().getComputedValue("--divider-line"),v.TargetManager.TargetManager.instance().observeModels(v.PerformanceMetricsModel.PerformanceMetricsModel,this)}onMetricStateChanged(e,t){t?this.activeCharts.add(e):this.activeCharts.delete(e),this.recalcChartHeight()}wasShown(){if(super.wasShown(),!this.model)return;this.chartInfos=this.createChartInfos(),c.ThemeSupport.instance().addEventListener(c.ThemeChangeEvent.eventName,()=>{this.chartInfos=this.createChartInfos(),this.requestUpdate()}),v.TargetManager.TargetManager.instance().addEventListener("SuspendStateChanged",this.suspendStateChanged,this),this.model.enable(),this.suspendStateChanged(),this.requestUpdate()}willHide(){super.willHide(),this.model&&(v.TargetManager.TargetManager.instance().removeEventListener("SuspendStateChanged",this.suspendStateChanged,this),this.stopPolling(),this.model.disable())}performUpdate(){let e={onMetricChanged:this.onMetricStateChanged.bind(this),chartsInfo:this.chartInfos,metrics:this.metrics,width:this.width,height:this.height,suspended:this.suspended},t={graphRenderingContext:null,width:0};this.view(e,t,this.contentElement),this.graphRenderingContext=t.graphRenderingContext,this.width=t.width,this.draw()}modelAdded(e){e.target()===v.TargetManager.TargetManager.instance().primaryPageTarget()&&(this.model=e,this.isShowing()&&this.wasShown())}modelRemoved(e){this.model===e&&(this.isShowing()&&this.willHide(),this.model=null)}suspendStateChanged(){let e=v.TargetManager.TargetManager.instance().allTargetsSuspended();e?this.stopPolling():this.startPolling(),this.suspended=e,this.requestUpdate()}startPolling(){this.pollTimer=window.setInterval(()=>this.poll(),this.pollIntervalMs),this.onResize();let e=()=>{this.draw(),this.animationId=this.contentElement.window().requestAnimationFrame(()=>{e()})};e()}stopPolling(){window.clearInterval(this.pollTimer),this.contentElement.window().cancelAnimationFrame(this.animationId),this.metricsBuffer=[]}async poll(){if(!this.model)return;let e=await this.model.requestMetrics(),t=e.timestamp,r=e.metrics;this.metricsBuffer.push({timestamp:t,metrics:r});let i=this.width/this.pixelsPerMs,s=Math.ceil(i/this.pollIntervalMs*2);this.metricsBuffer.length>s*2&&this.metricsBuffer.splice(0,this.metricsBuffer.length-s),this.metrics=r,this.requestUpdate()}draw(){if(!this.graphRenderingContext)return;let e=this.graphRenderingContext;e.save(),e.scale(window.devicePixelRatio,window.devicePixelRatio),e.clearRect(0,0,this.width,this.height),e.save(),e.translate(0,this.scaleHeight);for(let t of this.chartInfos)this.activeCharts.has(t.metrics[0].name)&&(this.drawChart(e,t,this.graphHeight),e.translate(0,this.graphHeight));e.restore(),this.drawHorizontalGrid(e),e.restore()}drawHorizontalGrid(e){let r=c.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-2");e.font="10px "+$.Platform.fontFamily(),e.fillStyle=c.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-50");let i=Date.now()/1e3;for(let s=Math.ceil(i);;--s){let n=this.width-((i-s)*1e3-this.pollIntervalMs)*this.pixelsPerMs;if(n<-50)break;e.beginPath(),e.moveTo(n,0),e.lineTo(n,this.height),s>=0&&s%10===0&&e.fillText(new Date(s*1e3).toLocaleTimeString(),n+4,12),e.strokeStyle=s%10?r:this.gridColor,e.stroke()}}drawChart(e,t,r){e.save(),e.rect(0,0,this.width,r),e.clip();let i=8,n=this.calcMax(t)*1.05,h=t.stacked?new Map:null,d=[];for(let a=t.metrics.length-1;a>=0;--a){let l=t.metrics[a];d.push({path:this.buildMetricPath(t,l,r-i,n,a?h:null),color:l.color})}let g=M.Color.parse(c.ThemeSupport.instance().getComputedValue("--sys-color-cdt-base-container"))?.asLegacyColor();if(g)for(let a of d.reverse()){let l=a.color;e.save();let m=M.Color.parse(l);m&&(e.fillStyle=g.blendWith(m.setAlpha(.2).asLegacyColor()).asString()||"",e.fill(a.path),e.strokeStyle=l,e.lineWidth=.5,e.stroke(a.path),e.restore())}e.fillStyle=c.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-50"),e.font=`10px  ${$.Platform.fontFamily()}`,e.fillText(t.title,8,10),this.drawVerticalGrid(e,r-i,n,t),e.restore()}calcMax(e){if(e.max)return e.max;let t=this.width,r=performance.now()-this.pollIntervalMs-t/this.pixelsPerMs,i=-1/0;for(let h of e.metrics)for(let d=this.metricsBuffer.length-1;d>=0;--d){let g=this.metricsBuffer[d],a=g.metrics.get(h.name);if(a!==void 0&&(i=Math.max(i,a)),g.timestamp<r)break}if(!this.metricsBuffer.length)return 10;let s=Math.pow(10,Math.floor(Math.log10(i)));i=Math.ceil(i/s/2)*s*2;let n=.2;return e.currentMax=i*n+(e.currentMax||i)*(1-n),e.currentMax}drawVerticalGrid(e,t,r,i){let s=Math.pow(10,Math.floor(Math.log10(r))),n=Math.floor(r/s);n!==1&&n%2===1&&(s*=2);let h=Math.floor(r/s)*s,d=r,a=t-18;e.fillStyle=c.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-50"),e.strokeStyle=this.gridColor,e.beginPath();for(let m=0;m<2;++m){let S=l(h),p=B(h,i);e.moveTo(0,S),e.lineTo(4,S),e.moveTo(e.measureText(p).width+12,S),e.lineTo(this.width,S),e.fillText(p,8,l(h)+3),h/=2}e.stroke(),e.beginPath(),e.moveTo(0,t+.5),e.lineTo(this.width,t+.5),e.strokeStyle=c.ThemeSupport.instance().getComputedValue("--color-background-inverted-opacity-2"),e.stroke();function l(m){return Math.round(t-a*m/d)+.5}}buildMetricPath(e,t,r,i,s){let n=new Path2D,d=r-18;if(d<1)return n;let g=i,a=t.name,l=this.pixelsPerMs,m=performance.now()-this.pollIntervalMs-this.width/l,S=e.smooth,p=0,w=0,b=0;this.metricsBuffer.length&&(p=(this.metricsBuffer[0].timestamp-m)*l,n.moveTo(p,x(0)),n.lineTo(this.width+5,x(0)),w=x(this.metricsBuffer[this.metricsBuffer.length-1].metrics.get(a)||0),b=this.width+5,n.lineTo(b,w));for(let C=this.metricsBuffer.length-1;C>=0;--C){let F=this.metricsBuffer[C],P=F.timestamp,y=F.metrics.get(a)||0;s&&(y+=s.get(P)||0,y=I.NumberUtilities.clamp(y,0,1),s.set(P,y));let k=x(y);if(p=(P-m)*l,S){let L=(b+p)/2;n.bezierCurveTo(L,w,L,k,p,k)}else n.lineTo(p,w),n.lineTo(p,k);if(b=p,w=k,P<m)break}return n;function x(C){return Math.round(r-d*C/g)+.5}}onResize(){super.onResize(),this.recalcChartHeight()}recalcChartHeight(){let e=this.scaleHeight;for(let t of this.chartInfos)this.activeCharts.has(t.metrics[0].name)&&(e+=this.graphHeight);this.height=Math.ceil(e*window.devicePixelRatio),this.requestUpdate()}createChartInfos(){let e=c.ThemeSupport.instance(),t=this.contentElement.firstElementChild,r={};return[{...r,title:f(u.cpuUsage),metrics:[{name:"TaskDuration",color:e.getComputedValue("--override-color-perf-monitor-cpu-task-duration",t)},{name:"ScriptDuration",color:e.getComputedValue("--override-color-perf-monitor-cpu-script-duration",t)},{name:"LayoutDuration",color:e.getComputedValue("--override-color-perf-monitor-cpu-layout-duration",t)},{name:"RecalcStyleDuration",color:e.getComputedValue("--override-color-perf-monitor-cpu-recalc-style-duration",t)}],format:"Percent",smooth:!0,stacked:!0,color:e.getComputedValue("--override-color-perf-monitor-cpu",t),max:1},{...r,title:f(u.jsHeapSize),metrics:[{name:"JSHeapTotalSize",color:e.getComputedValue("--override-color-perf-monitor-jsheap-total-size",t)},{name:"JSHeapUsedSize",color:e.getComputedValue("--override-color-perf-monitor-jsheap-used-size",t)}],format:"Bytes",color:e.getComputedValue("--override-color-perf-monitor-jsheap",t)},{...r,title:f(u.domNodes),metrics:[{name:"Nodes",color:e.getComputedValue("--override-color-perf-monitor-dom-nodes",t)}]},{...r,title:f(u.jsEventListeners),metrics:[{name:"JSEventListeners",color:e.getComputedValue("--override-color-perf-monitor-js-event-listeners",t)}]},{...r,title:f(u.documents),metrics:[{name:"Documents",color:e.getComputedValue("--override-color-perf-monitor-documents",t)}]},{...r,title:f(u.documentFrames),metrics:[{name:"Frames",color:e.getComputedValue("--override-color-perf-monitor-document-frames",t)}]},{...r,title:f(u.layoutsSec),metrics:[{name:"LayoutCount",color:e.getComputedValue("--override-color-perf-monitor-layout-count",t)}]},{...r,title:f(u.styleRecalcsSec),metrics:[{name:"RecalcStyleCount",color:e.getComputedValue("--override-color-perf-monitor-recalc-style-count",t)}]}]}},X=(o,e,t)=>{q(V`
    ${o.chartsInfo.map(r=>{let i=r.metrics[0].name,s=o.enabledCharts.has(i),n=o.metricValues.get(i)||0;return Q(r,s,n,h=>o.onCheckboxChange(i,h))})}
    `,t,{container:{classes:["perfmon-control-pane"]}})},D=class extends U.Widget.VBox{#t;#e;#r=null;#o=[];#i=new Map;#s;constructor(e,t=X){super(e,{useShadowDom:!1}),this.#s=t,this.#t=M.Settings.Settings.instance().createSetting("perfmon-active-indicators2",["TaskDuration","JSHeapTotalSize","Nodes"]),this.#e=new Set(this.#t.get())}set chartsInfo(e){this.#o=e,this.requestUpdate()}set onMetricChanged(e){this.#r=e;for(let t of this.#e)e(t,!0)}performUpdate(){let e={chartsInfo:this.#o,enabledCharts:this.#e,metricValues:this.#i,onCheckboxChange:this.#n.bind(this)};this.#s(e,{},this.element)}#n(e,t){this.#a(e,t.target.checked),this.requestUpdate()}#a(e,t){t?this.#e.add(e):this.#e.delete(e),this.#t.set(Array.from(this.#e)),this.#r&&this.#r(e,t)}set metrics(e){if(e){for(let[t,r]of e.entries())this.#i.set(t,r);this.requestUpdate()}}},R,N;function B(o,e){switch(R||(R=new Intl.NumberFormat("en-US",{maximumFractionDigits:1}),N=new Intl.NumberFormat("en-US",{maximumFractionDigits:1,style:"percent"})),e.format){case"Percent":return N.format(o);case"Bytes":return T.ByteUtilities.bytesToString(o);default:return R.format(o)}}function Q(o,e,t,r){let i=o.color||o.metrics[0].color,s=o.metrics[0].name;return V`
      <div class="perfmon-indicator ${e?"active":""}" jslog=${H.toggle().track({click:!0,keydown:"Enter"}).context(I.StringUtilities.toKebabCase(s))}>
        <devtools-checkbox .checked=${e}
            @change=${r} .jslogContext=${s}>${o.title}</devtools-checkbox>
        <div class="perfmon-indicator-value" style="color:${i}">${B(t,o)}</div>
      </div>
    `}var Z=new Intl.NumberFormat("en-US",{maximumFractionDigits:1});export{A as PerformanceMonitor};
//# sourceMappingURL=performance_monitor.js.map
