/** Memory tab of the Debug tool window: live instance counts per class of the debugged JVM, and heap capture. */ import { useEffect, useMemo } from "react"; import clsx from "clsx"; import { Checkbox, Icon, IconButton, Input, List, T } from "@/ui"; import { executeAction } from "@/platform/actions"; import { useTx } from "@/platform/i18n"; import type { JvmClassRow, JvmMemorySnapshot } from "@/platform/ipc"; import { sessionSupports, type DebugSession } from "../state"; import { useActionEnabled } from "../ui/useActionEnabled"; import { retainedForSession, useHeap } from "../heap/heapState"; import { DEFAULT_QUERY, isOutdated, isOvertaken, refreshMemory, selectMemoryClass, setMemoryQuery, useMemory, } from "./memoryState"; import { HeapCaptureButton, HeapCaptureStatus } from "./HeapCapture"; import { InstancesPane } from "./InstancesPane"; import { backendText } from "./instancesTree"; import { keepKeysOnButton } from "./rowButtonKeys"; import { columnsOf, formatBytes, formatCount, formatDelta, queryFor, visibleRows, type SortKey } from "./rows"; import { unavailableText } from "./unavailableText"; import styles from "./MemoryView.module.css"; import { useRowHeight } from "@/ui/density"; const COLUMNS: ReadonlyArray<{ key: SortKey; label: string; numeric: boolean }> = [ { key: "name", label: "Class", numeric: false }, { key: "instances", label: "Count", numeric: true }, { key: "deltaInstances", label: "Diff", numeric: true }, { key: "bytes", label: "Shallow Size", numeric: true }, { key: "retained", label: "Retained Size", numeric: true }, ]; const showInstancesOf = (name: string) => void executeAction("debug.memory.showInstances", name); /** * `listsInstances`: the session can list the class's instances, which it reads only while paused. * `retained`: retained bytes by class name from a snapshot of this table's stop, or `null` for no such column. */ function ClassRow({ row, sizes, retained, listsInstances, paused, }: { row: JvmClassRow; sizes: boolean; retained: ReadonlyMap | null; listsInstances: boolean; paused: boolean; }) { const tx = useTx(); const delta = formatDelta(row.deltaInstances); const retainedBytes = retained?.get(row.name); const opens = listsInstances && paused; return (
showInstancesOf(row.name) : undefined}> {row.name} {row.ambiguous && ( )} {row.module && {row.module}} {listsInstances && ( )} {formatCount(row.instances)} {delta} {sizes && ( {formatBytes(row.bytes)} )} {retained && ( {retainedBytes === undefined ? "—" : formatBytes(retainedBytes)} )}
); } export function MemoryView({ session }: { session: DebugSession }) { const rowHeight = useRowHeight(22); // Also re-renders the reason text, which reads the catalog when called. const tx = useTx(); const id = session.id; const entry = useMemory((s) => s.bySession[id]); const query = entry?.query ?? DEFAULT_QUERY; const result = entry?.result ?? null; const snapshot = entry?.snapshot ?? null; const source = snapshot?.source ?? "histogram"; const heapSnapshots = useHeap((s) => s.snapshots); const tableStop = snapshot ? (entry?.takenAtStop ?? null) : null; // `retainedForSession` alone decides whether the sizes fit this table (Z2), so other callers cannot skip a check. const retained = useMemo( () => (tableStop === null ? null : retainedForSession(id, tableStop)), // eslint-disable-next-line react-hooks/exhaustive-deps -- the heap snapshots and the session's stop and status are the inputs of retainedForSession() [id, tableStop, session.stops, session.status, heapSnapshots], ); const sorted = useMemo(() => queryFor(query, source, retained !== null), [query, source, retained]); const listsInstances = sessionSupports("jvmInstances", session); const paused = session.status === "paused"; const canRefresh = useActionEnabled("debug.memory.refresh"); const backend = backendText(session.jvmBackend, tx); // Only the first visit loads: later stops mark the table outdated instead of re-running a heap walk. useEffect(() => { const e = useMemory.getState().bySession[id]; if (!e?.result && !e?.loading) void refreshMemory(id); }, [id]); const overtaken = entry ? isOvertaken(entry, session) : false; useEffect(() => { if (overtaken) void refreshMemory(id); }, [id, overtaken]); const rows = useMemo( () => (snapshot ? visibleRows(snapshot.rows, sorted, retained ?? undefined) : []), [snapshot, sorted, retained], ); const columns = COLUMNS.filter((c) => columnsOf(source, retained !== null).includes(c.key)); const selected = entry?.selected ?? null; const sortBy = (key: SortKey) => setMemoryQuery(id, sorted.sort === key ? { sort: key, desc: !sorted.desc } : { sort: key, desc: key !== "name" }); return (
setMemoryQuery(id, { filter: e.target.value })} placeholder="Filter classes" aria-label="Filter classes" /> setMemoryQuery(id, { changedOnly })} label="Changed only" />
{backend && (
{backend}
)} {entry?.loading && listsInstances && paused && (
Counting objects through the debugger. This can take several seconds on a large heap.
)} {entry?.error && (
{entry.error}
)} {snapshot && entry && isOutdated(entry, session.stops) && (
Taken before the last stop. Refresh to update.
)} {result?.status === "unavailable" && (
{unavailableText(result.reason)} {result.canCountWhenPaused && ( <> {" "} Pause the program to count objects through the debugger. )}
)} {snapshot && (
{columns.map((c) => (
))}
`${i}:${r.name}`} renderItem={(r) => ( )} activeIndex={selected == null ? -1 : rows.findIndex((r) => r.name === selected)} onActiveChange={(i) => selectMemoryClass(id, rows[i]?.name ?? null)} // A click only selects; Enter opens (double-click is handled by the row). onActivate={(r, _i, e) => { if (e.type === "keydown" && listsInstances && paused) showInstancesOf(r.name); }} rowHeight={rowHeight} tableBody={{ headerRows: 1 }} empty={{tx("No matches")}} />
)}
); } function FooterTotals({ snapshot }: { snapshot: JvmMemorySnapshot }) { const tx = useTx(); const n = formatCount(snapshot.rows.length); const m = formatCount(snapshot.totalInstances); const size = formatBytes(snapshot.totalBytes); const counted = snapshot.source === "debugger"; return (
{counted ? tx`${n} classes · ${m} objects` : tx`${n} classes · ${m} objects · ${size}`} {counted ? ( Counted by the debugger: reachable objects only, no sizes. ) : ( Counts include objects that are unreachable but not yet collected. )}
); }