/** Debug tool window: toolbar, Threads & Variables (frames + variables), Console. */ import { writeClipboardText } from "@/platform/clipboard"; import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import clsx from "clsx"; import { executeAction } from "@/platform/actions"; import { editorPrefs } from "@/platform/editorSettings"; import { monoFontFamily } from "@/platform/fonts"; import { isImeKey } from "@/platform/ime"; import { formatBinding, hostBinding } from "@/platform/keymap"; import { basename, useProject } from "@/platform/project"; import { call, commands, isTauri, type Scope, type Variable } from "@/platform/ipc"; import { Button, EmptyState, Icon, IconButton, Kbd, Menu, MenuList, Popup, Select, SplitGroup, SplitHandle, SplitPanel, Tabs, Toolbar, showContextMenu, type MenuItem, type TabItem, T, } from "@/ui"; import type { SelectOption } from "@/ui/Select"; import { revealVertically } from "@/ui/Tabs"; import { setMuted, useBreakpoints } from "../breakpoints/store"; import { frameLabel, groupFrames } from "../frames"; import { blurDebugView, focusDebugView } from "./focusedView"; import { useActionEnabled } from "./useActionEnabled"; import { addWatch, closeSessionTab, evaluate, isLive, isThreadSuspended, selectFrame, selectSession, selectThread, revealFrame, rootOf, sessionSupports, useDebug, type DebugSession, } from "../state"; import { remoteWaitingNote } from "../remote"; import { sessionTabs } from "./sessionTabs"; import { debugTabMenu } from "../tabActions"; import { stopNote } from "../js/eventBreakpoints"; import { NetworkView } from "../js/NetworkView"; import { liveWatchesApply, useLiveWatches } from "../js/liveWatches"; import { pageProfileItems, useJsProfile } from "../js/profile"; import { MemoryView } from "../memory/MemoryView"; import { DebugConsole } from "./DebugConsole"; import { VariablesView, type VarRoot } from "./VariablesView"; import { useExpressionCompletion } from "./ExpressionCompletion"; import { pushHistory, readHistory } from "./expressionHistory"; import { sortVariables } from "../values"; import { workflowSettings } from "@/platform/workflowSettings"; import { useToolWindowShown } from "@/workbench/contributions"; import { useToolWindowLayout } from "@/workbench/toolwindows/store"; import styles from "./DebugToolWindow.module.css"; import { tx, useTx } from "@/platform/i18n"; function ToolButton({ action, icon, tone }: { action: string; icon: string; tone?: "danger" }) { const enabled = useActionEnabled(action); return ( ); } /** IDEA's `XDebugger.ToolWindow.TopToolbar3.Extra` ("More" in the debugger toolbar). */ const MORE_ITEMS: MenuItem[] = [ { kind: "action", action: "debug.forceStepOver", icon: "force-step-over" }, { kind: "action", action: "debug.forceStepInto", icon: "force-step-into" }, { kind: "action", action: "debug.smartStepInto", icon: "smart-step-into" }, { kind: "separator" }, { kind: "action", action: "debug.runToCursor", icon: "run-to-cursor" }, { kind: "action", action: "debug.forceRunToCursor", icon: "force-run-to-cursor" }, { kind: "separator" }, { kind: "action", action: "debug.showExecutionPoint", icon: "show-execution-point" }, { kind: "separator" }, { kind: "action", action: "debug.evaluate", icon: "evaluate-expression" }, { kind: "action", action: "debug.resetFrame", icon: "reset-frame" }, { kind: "separator" }, { kind: "action", action: "debug.dumpThreads", icon: "thread-dump" }, ]; function MoreActions() { const ref = useRef(null); const [open, setOpen] = useState(false); const page = useDebug((s) => { const a = s.active == null ? undefined : s.sessions[s.active]; return a && isLive(a) && a.caps?.jsPage ? a.id : null; }); const recording = useJsProfile((s) => page != null && !!s.recording[page]); const items = useMemo(() => [...MORE_ITEMS, ...pageProfileItems(page != null, recording)], [page, recording]); return ( <> setOpen((v) => !v)} /> setOpen(false)} /> ); } type Tab = "variables" | "console" | "memory" | "network"; /** The view the user last picked; the tool window opens on it again (Console until one is picked). */ let chosenTab: Tab = "console"; /** Threads & Variables › Focus On Breakpoint: whether a breakpoint hit selects that tab. */ async function setVariablesOnBreakpoint(on: boolean) { if (!isTauri()) return; useProject.setState({ settings: await call(commands.settingsSet("global", "debugger.variablesOnBreakpoint", JSON.stringify(on))), }); } function statusText(s: DebugSession): string { if (s.status === "terminated") return s.exitCode != null ? `Finished · exit code ${s.exitCode}` : "Finished"; if (s.status === "starting") return "Starting…"; return s.status === "paused" ? "Suspended" : "Running"; } /** Tool window header: one tab per debug session (`main ×`), like IDEA's content tabs. */ export function DebugTabs() { const sessions = useDebug((s) => s.sessions); const active = useDebug((s) => s.active); const list = Object.values(sessions); if (!list.length) return null; const tabs = sessionTabs(list); const ownerOf = (id: string) => tabs.find((t) => t.session.id === +id)?.owner ?? +id; const items: TabItem[] = tabs.map(({ session: s, child, owner }) => ({ id: String(s.id), label: child ? tx`${s.name} (child)` : s.name, text: s.name, icon: "debug", italic: s.status === "terminated", closable: true, pinned: !child && !!sessions[owner]?.pinned, tooltip: statusText(s), })); // A browser launch's own session has no tab: its page's tab stands for it. const shown = tabs.find((t) => t.session.id === active) ?? tabs.find((t) => t.owner === active); return ( selectSession(+id)} onClose={(id) => void closeSessionTab(ownerOf(id))} onTogglePin={(id) => void executeAction("debug.pinTab", ownerOf(id))} onContextMenu={(id, e) => { e.preventDefault(); showContextMenu(e, debugTabMenu(ownerOf(id)), { owner: e.currentTarget }); }} panelIdPrefix="openidea-debug" /> ); } /** * Services › a configuration being debugged: the same debugger as the Debug tool window, for * that session (#4773). `console` replaces the Console tab, e.g. with the console of the run the * debugger is attached to. */ export function DebugServiceView({ sessionId, console: consolePane }: { sessionId: number; console?: ReactNode }) { const shown = useDebug((s) => { const active = s.active != null ? s.sessions[s.active] : undefined; return !!active && rootOf(active).id === sessionId; }); useEffect(() => { if (useDebug.getState().sessions[sessionId]) selectSession(sessionId); }, [sessionId]); // The toolbar acts on the active session: using this view makes its session the active one again. const reselect = () => { if (!shown && useDebug.getState().sessions[sessionId]) selectSession(sessionId); }; return (
{shown && }
); } export function DebugToolWindow() { const sideDocked = useToolWindowLayout((s) => (s.placements.debug?.anchor ?? "bottom") !== "bottom"); return ; } function DebugView({ consolePane, sideDocked = false }: { consolePane?: ReactNode; sideDocked?: boolean }) { const tx = useTx(); const active = useDebug((s) => (s.active != null ? s.sessions[s.active] : undefined)); const muted = useBreakpoints((s) => s.muted); const [view, setView] = useState<{ session: number | undefined; status: DebugSession["status"] | undefined; tab: Tab; }>({ session: undefined, status: undefined, tab: chosenTab }); if (active && (view.session !== active.startedAt || view.status !== active.status)) setView({ session: active.startedAt, status: active.status, // A breakpoint or exception brings Threads & Variables to the front unless its Focus On Breakpoint // is off; finishing a step keeps the tab the user is on (e.g. Console, to watch the output while // stepping), and so does Memory. tab: active.status === "starting" ? "console" : active.status === "paused" && view.tab !== "memory" && active.stopReason !== "step" && workflowSettings().debugger.variablesOnBreakpoint ? "variables" : view.tab, }); // A JVM session shows the Memory tab from the start, before the debugger has reported what it supports. const memoryPending = !!active && !active.caps && JVM_ADAPTERS.has(rootOf(active).adapter); const hasMemory = !!active && (sessionSupports("jvmMemory", active) || memoryPending); const hasNetwork = !!active && sessionSupports("jsPage", active); // The selected session may be one without the Memory or the Network tab. const tab: Tab = (view.tab === "memory" && !hasMemory) || (view.tab === "network" && !hasNetwork) ? "variables" : view.tab; if (!active) { return (
Start a debug configuration with {" "} or click a line number to set a breakpoint.
); } return (
{rootOf(active).adapter === "dart" && ( <> {rootOf(active).vmServiceUri && } )} setMuted(!muted)} />
{( [ ["variables", "Threads & Variables"], ["console", "Console"], ...(hasMemory ? [["memory", "Memory"] as const] : []), ...(hasNetwork ? [["network", "Network"] as const] : []), ] as const ).map(([id, label]) => ( ))}
{tab === "variables" ? ( ) : tab === "memory" ? ( memoryPending ? (
The Memory view is available once the program has started.
) : ( ) ) : tab === "network" ? ( ) : ( (consolePane ?? ) )}
); } /** Debug adapters whose sessions have the Memory view (`ide-dap`'s `JVM_MEMORY_ADAPTERS`). */ const JVM_ADAPTERS = new Set(["java-debug", "kotlin-debug-adapter", "kotlin-lsp"]); // --- threads & frames ---------------------------------------------------------- const DEFAULT_THREADS_VARIABLES_LAYOUT = { frames: 34, variables: 66 }; function ThreadsAndVariables({ session, sideDocked }: { session: DebugSession; sideDocked: boolean }) { return ( ); } function ThreadSelector({ session }: { session: DebugSession }) { const tr = useTx(); const value = session.selectedThread == null ? null : String(session.selectedThread); const options = session.threads.map(({ id, name }) => { const option = { value: String(id), label: name, verbatim: true }; if (!isLive(session)) return option; if (!isThreadSuspended(session, id)) return { ...option, icon: "thread-running", detail: "Running" }; const reason = id === session.stoppedThread ? session.stopReason : session.suspendedThreads?.find((t) => t.id === id)?.reason; return reason === "breakpoint" || reason?.endsWith(" breakpoint") ? { ...option, icon: "thread-breakpoint", detail: "At breakpoint" } : { ...option, icon: "thread-suspended", detail: "Suspended" }; }); const selected = options.find((option) => option.value === value); const summary = selected?.detail ? `${selected.label} (${tr(selected.detail)})` : selected?.label; return (
{ setExpression(e.target.value); completion.onInput(); }} onBlur={completion.close} onKeyDown={(e) => { if (isImeKey(e.nativeEvent) || completion.onKeyDown(e)) return; if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && e.shiftKey) { e.preventDefault(); addExpressionWatch(); } else if (e.key === "Enter") { e.preventDefault(); void run(); } }} placeholder={tx("Evaluate expression")} aria-label={tx("Evaluate expression")} spellCheck={false} autoComplete="off" disabled={frame == null} /> {completion.popup} setHistory( historyOpen ? null : { sessionId: session.id, stopSeq, entries: readHistory("evaluate") .filter((entry) => !/[\r\n]/.test(entry)) .slice(0, 20), }, ) } />
setHistory(null)} anchor={evalRow} placement="bottom-start" matchWidth role="presentation" autoFocus={false} className={styles.evalHistory} > setHistory(null)} items={ history?.entries.length ? history.entries.map((entry) => ({ label: entry, verbatim: true, run: () => recall(entry) })) : [{ label: "No history", disabled: true }] } /> {frame == null && !watches.length && !lastEval ? (
{session.status === "terminated" ? tx("The session has finished.") : tx("Variables are available while suspended.")}
) : ( )} ); }