/** * Profiler tool window: one tab per snapshot, and per snapshot a flame graph * (click to zoom, search highlights), the call tree (top-down) and the method * list (self / total). Double-click opens a frame's source when known. */ import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react"; import clsx from "clsx"; import type { Profile } from "@/platform/ipc"; import { Button, EmptyState, Icon, IconButton, Input, Tabs, Tree, T } from "@/ui"; import { editorService } from "@/workbench/contributions"; import { executeAction } from "@/platform/actions"; import { callSites, colorSlot, flameLayout, flameStep, formatCalls, formatWeight, frameLocation, matchingFrames, share, type CallSite, } from "./model"; import { activeSnapshot, closeSnapshot, useProfiler, type ProfilerTab } from "./store"; import styles from "./Profiler.module.css"; import { useTx } from "@/platform/i18n"; const ROW = 18; /** Names the allocation modes for the snapshot tabs; CPU profiles keep the plain run name. */ function useModeLabel(): (profile: Profile) => string | null { const tx = useTx(); return (profile) => profile.mode === "allocations" ? tx("Allocations") : profile.mode === "liveObjects" ? tx("Live Objects") : null; } /** Faint mark after the name of a frame that is an allocated type rather than code. */ function TypeMark({ profile, frame }: { profile: Profile; frame: number }) { if (profile.frames[frame]!.kind !== "allocatedType") return null; return ( allocated ); } /** `async-profiler · 612.4 MB allocated`; what the weight counts depends on the mode. */ function profileSummary(profile: Profile, tx: ReturnType): string { const total = profile.total ?? 0; if (profile.mode === "allocations") { const size = formatWeight(total, profile.unit); return `${profile.profiler} · ${tx`${size} allocated`}`; } if (profile.mode === "liveObjects") { const count = Math.round(total); const live = count === 1 ? tx("1 live sample (≈ 512 KB)") : tx`${count} live samples (≈ 512 KB each)`; return `${profile.profiler} · ${live}`; } return `${profile.profiler} · ${formatWeight(total, profile.unit)}`; } function openFrame(profile: Profile, frame: number) { const f = profile.frames[frame]; if (!f?.file) return; void editorService().openFile( f.file, f.line !== null ? { selection: { line: f.line, col: 0 }, focus: true } : { focus: true }, ); } export function ProfilerHeaderActions() { return ; } export function ProfilerTabs() { const snapshots = useProfiler((s) => s.snapshots); const activeId = useProfiler((s) => s.activeId); const modeLabel = useModeLabel(); if (!snapshots.length) return null; return ( useProfiler.setState({ activeId: id })} onClose={closeSnapshot} items={snapshots.map((s) => { const mode = modeLabel(s.profile); return { id: s.id, label: mode ? `${s.name} · ${mode}` : s.name, verbatim: true, closable: true, tooltip: `${s.profile.profiler}, ${mode ? `${mode}, ` : ""}${new Date(s.createdAt).toLocaleTimeString()}`, }; })} /> ); } function FlameGraph({ profile, query }: { profile: Profile; query: string }) { const tx = useTx(); const ref = useRef(null); const [width, setWidth] = useState(0); const [focus, setFocus] = useState(0); useLayoutEffect(() => { const el = ref.current; if (!el) return; const ro = new ResizeObserver(() => setWidth(el.clientWidth)); ro.observe(el); setWidth(el.clientWidth); return () => ro.disconnect(); }, []); const layout = useMemo(() => flameLayout(profile, focus, width > 0 ? 1 / width : 0.002), [profile, focus, width]); // The frame the keyboard is on: arrows move it, Enter zooms into it, F4 opens its source. const [current, setCurrent] = useState(0); const shown = layout.rects.some((r) => r.node === current) ? current : focus; const onKeyDown = (e: KeyboardEvent) => { const moves: Record[2]> = { ArrowUp: "deeper", ArrowDown: "shallower", ArrowLeft: "previous", ArrowRight: "next", }; const move = moves[e.key]; if (move) setCurrent(flameStep(layout.rects, shown, move)); else if (e.key === "Enter") setFocus(shown); else if (e.key === "Escape" && focus !== 0) setFocus(0); else if (e.key === "F4") openFrame(profile, profile.nodes[shown]!.frame); else return; e.preventDefault(); e.stopPropagation(); }; useEffect(() => { ref.current?.querySelector(`[data-node="${shown}"]`)?.scrollIntoView?.({ block: "nearest" }); }, [shown]); const matches = useMemo(() => matchingFrames(profile, query), [profile, query]); const unit = profile.unit; const total = profile.total ?? 0; return (
{focus !== 0 && (
setFocus(0)} /> {tx`Zoomed into ${profile.frames[profile.nodes[focus]!.frame]!.name}`}
)}
{width > 0 && layout.rects.map((r) => { const node = profile.nodes[r.node]!; const frame = profile.frames[node.frame]!; const w = r.width * width; const location = frameLocation(profile, node.frame); const label = r.node === 0 ? `all (${formatWeight(total, unit)})` : frame.name; return (
{ setCurrent(r.node); setFocus(r.node); }} onDoubleClick={() => openFrame(profile, node.frame)} > {w > 28 && {label}}
); })}
); } function CallTree({ profile }: { profile: Profile }) { const total = profile.total ?? 0; const roots = useMemo(() => profile.nodes[0]?.children ?? [], [profile]); const [expanded, setExpanded] = useState | null>(null); // The heaviest path starts expanded (IDEA expands the hottest call chain). const initial = useMemo(() => { const set = new Set(); let cur = roots[0]; for (let i = 0; cur !== undefined && i < 30; i++) { set.add(String(cur)); cur = profile.nodes[cur]!.children[0]; } return set; }, [profile, roots]); return ( aria-label="Call tree" className={styles.tree} roots={roots} getKey={(n) => String(n)} getLabel={(n) => profile.frames[profile.nodes[n]!.frame]!.name} getChildren={(n) => (profile.nodes[n]!.children.length ? profile.nodes[n]!.children : undefined)} isExpandable={(n) => profile.nodes[n]!.children.length > 0} expanded={expanded ?? initial} onExpandedChange={(next) => setExpanded(next)} activateExpandable onActivate={(n) => openFrame(profile, profile.nodes[n]!.frame)} renderNode={(n) => { const node = profile.nodes[n]!; const location = frameLocation(profile, node.frame); return ( {share(node.total ?? 0, total)} {profile.frames[node.frame]!.name} {location && {location}} {formatWeight(node.total ?? 0, profile.unit)} {(node.selfWeight ?? 0) > 0 && ` · self ${formatWeight(node.selfWeight ?? 0, profile.unit)}`} ); }} /> ); } type MethodSort = "self" | "total" | "name" | "calls"; const MAX_METHODS = 2000; function MethodList({ profile, query }: { profile: Profile; query: string }) { const tx = useTx(); const [sort, setSort] = useState("self"); const [selected, setSelected] = useState(null); const total = profile.total ?? 0; const counted = profile.methods.some((m) => m.calls !== null); const rows = useMemo(() => { const matches = matchingFrames(profile, query); const list = profile.methods.filter((m) => !matches || matches.has(m.frame)); const name = (f: number) => profile.frames[f]!.name; if (sort === "name") list.sort((a, b) => name(a.frame).localeCompare(name(b.frame))); else if (sort === "total") list.sort((a, b) => (b.total ?? 0) - (a.total ?? 0)); else if (sort === "calls") list.sort((a, b) => (b.calls ?? 0) - (a.calls ?? 0)); return list.slice(0, MAX_METHODS); }, [profile, query, sort]); const sites = useMemo(() => (selected === null ? null : callSites(profile, selected)), [profile, selected]); // Picking a caller or callee selects it in the list, even when the search hides it. const select = (frame: number) => { setSelected(frame); if (!rows.some((m) => m.frame === frame)) useProfiler.setState({ query: "" }); }; useEffect(() => { if (selected !== null) document.getElementById(`method-${selected}`)?.scrollIntoView?.({ block: "nearest" }); }, [selected]); const header = (key: MethodSort, label: string) => ( ); return (
{header("name", "Method")} {header("self", "Self")} {header("total", "Total")} {counted && header("calls", "Calls")} {rows.map((m) => { const location = frameLocation(profile, m.frame); return ( setSelected(m.frame)} onDoubleClick={() => openFrame(profile, m.frame)} > {counted && ( )} ); })}
{profile.frames[m.frame]!.name} {location && {location}} {formatWeight(m.selfWeight ?? 0, profile.unit)}{" "} {share(m.selfWeight ?? 0, total)} {formatWeight(m.total ?? 0, profile.unit)}{" "} {share(m.total ?? 0, total)} {m.calls !== null ? formatCalls(m.calls, m.primitiveCalls) : ""}
{sites && selected !== null && (
)}
); } /** The callers or callees of the selected method: click selects one, double-click opens its source. */ function CallSiteList({ title, profile, sites, onSelect, }: { title: string; profile: Profile; sites: CallSite[]; onSelect: (frame: number) => void; }) { const tx = useTx(); const total = profile.total ?? 0; return (
{sites.some((x) => x.calls !== null) && ( )} {sites.map((x) => { const location = frameLocation(profile, x.frame); return ( onSelect(x.frame)} onDoubleClick={() => openFrame(profile, x.frame)}> {x.calls !== null && } ); })} {!sites.length && ( )}
{tx(title)} {tx("Total")} {tx("Calls")}
{profile.frames[x.frame]!.name} {location && {location}} {formatWeight(x.total, profile.unit)} {share(x.total, total)} {formatCalls(x.calls, x.primitiveCalls)}
None
); } export function ProfilerView() { const tx = useTx(); const snapshot = useProfiler((s) => activeSnapshot(s)); const tab = useProfiler((s) => s.tab); const query = useProfiler((s) => s.query); if (!snapshot) { return ( void executeAction("profiler.openSnapshot")}> Open Snapshot… } > Profile a run configuration to see where it spends its time. ); } const profile = snapshot.profile; return (
useProfiler.setState({ tab: id as ProfilerTab })} items={[ { id: "flame", label: "Flame Graph" }, { id: "tree", label: "Call Tree" }, { id: "methods", label: "Method List" }, ]} /> {profileSummary(profile, tx)} {tab !== "tree" && ( useProfiler.setState({ query: e.target.value })} /> )}
{snapshot.notice && (
{tx(snapshot.notice)}
)}
{tab === "flame" && } {tab === "tree" && } {tab === "methods" && }
); }