504 lines
27 KiB
JavaScript
504 lines
27 KiB
JavaScript
// The debugger (Xdebug): breakpoints in the editors' gutter, Debug runs (a run configuration with JUMPHP_XDEBUG: the
|
||
// program connects to the IDE, ide/src/Debug/Debugger.php), and the Debug tool window: where it stopped (the
|
||
// frames), its variables (a tree read lazily, F2 / double click gives one a new value), watches, the steps (F9 resume,
|
||
// F8 over, F7 into, Shift+F8 out, Alt+F9 run to the caret) and the exceptions that stop it (Stop at Exceptions…).
|
||
// Claude drives the same debugger through its tools (agent.js): the user sees what it does here.
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, basename, menu, prompt, notify, prefs, debounce, t, dialog, copyText } from './ui.js';
|
||
import { monaco, pathOf, uriOf } from './editor.js';
|
||
import { VarTree } from './var-tree.js';
|
||
import { HoverInspector } from './hover-inspect.js';
|
||
|
||
/** The debugging engines (the programs connect to the IDE with DBGp either way; Xdebug is the default). */
|
||
const DEBUG_ENGINES = { xdebug: 'Xdebug', 'php-debugger': 'PHP Debugger (php-debugger.dev)' };
|
||
const ENGINE_BADGE = { xdebug: 'X', 'php-debugger': 'PD' };
|
||
const DEBUG_DOCS = 'https://jumphp.net/docs/ide-debugger';
|
||
const MCP_COMMANDS = ['claude mcp add dbgp -- dbgp mcp', 'claude mcp add jumphp-debug -- bin/jumphp debug'];
|
||
|
||
export class DebugPanel {
|
||
constructor(app) {
|
||
this.app = app;
|
||
this.key = 'breakpoints:' + app.projectKey;
|
||
/** path => [{line, condition}] */
|
||
this.breakpoints = new Map(Object.entries(prefs.get(this.key, {}) || {}));
|
||
this.watches = prefs.get('watches:' + app.projectKey, []) || [];
|
||
/** exception classes that stop the program where thrown ('*': all) */
|
||
this.exceptions = prefs.get('exceptions:' + app.projectKey, []) || [];
|
||
this.decorations = new Map(); // model uri => decoration ids (breakpoints)
|
||
this.current = new Map(); // model uri => decoration ids (where it stopped)
|
||
this.paused = null; // {session, path, line, stack}
|
||
this.frame = 0;
|
||
this.listening = false;
|
||
this.node = el('div.debug-view');
|
||
this.tree = new VarTree(this.treeContext());
|
||
this.inspector = new HoverInspector(this);
|
||
this.updateBadge();
|
||
this.render();
|
||
this.syncLater = debounce((model) => this.readBack(model), 300);
|
||
|
||
for (const group of app.editors.groups) this.attach(group.editor);
|
||
monaco.editor.onDidCreateEditor((editor) => this.attach(editor));
|
||
monaco.editor.onDidCreateModel((model) => { this.decorate(model); this.watchModel(model); });
|
||
for (const model of monaco.editor.getModels()) { this.decorate(model); this.watchModel(model); }
|
||
for (const [path, list] of this.breakpoints) backend.invoke('debug.breakpoints', { path, lines: list }).catch(() => null);
|
||
if (this.exceptions.length) backend.invoke('debug.exceptions', { classes: this.exceptions }).catch(() => null);
|
||
|
||
backend.on('debug.paused', (p) => this.onPaused(p));
|
||
backend.on('debug.running', (p) => { if (this.paused?.session === p.session) this.cleared(); });
|
||
backend.on('debug.ended', (p) => { if (!this.paused || this.paused.session === p.session) this.cleared(); this.app.badge('debug', null); });
|
||
backend.on('debug.state', (s) => { this.listening = s.listening; this.sessions = s.sessions || []; this.app.refreshToolHeader('debug'); });
|
||
}
|
||
|
||
title() { return 'Debug'; }
|
||
|
||
actions() {
|
||
const stopped = !!this.paused;
|
||
const b = (title, ico, how, enabled = stopped) => el('button', { title, disabled: !enabled, onclick: () => this.step(how) }, icon(ico));
|
||
return [
|
||
b(t('Resume Program') + ' (F9)', 'play', 'run'),
|
||
b(t('Step Over') + ' (F8)', 'stepOver', 'step_over'),
|
||
b(t('Step Into') + ' (F7)', 'stepInto', 'step_into'),
|
||
b(t('Step Out') + ' (Shift+F8)', 'stepOut', 'step_out'),
|
||
b(t('Stop (ends the program)'), 'stop', 'stop', stopped || (this.sessions || []).length > 0),
|
||
el('button' + (this.exceptions.length ? '.on' : ''), { title: this.exceptions.length ? t('Stops at exceptions: {list}', { list: this.exceptions.join(', ') }) : t('Stop at Exceptions…'), onclick: () => this.editExceptions() }, icon('warning')),
|
||
el('button', { title: t('Remove All Breakpoints'), onclick: () => this.clearAll() }, icon('close')),
|
||
];
|
||
}
|
||
|
||
// breakpoints --------------------------------------------------------------------------------------------------
|
||
|
||
attach(editor) {
|
||
if (editor.__debug) return;
|
||
editor.__debug = true;
|
||
this.inspector?.attach(editor);
|
||
editor.updateOptions({ glyphMargin: true });
|
||
editor.onMouseDown((e) => {
|
||
const type = e.target.type;
|
||
if (type !== monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN && type !== monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS) return;
|
||
const model = editor.getModel();
|
||
const line = e.target.position?.lineNumber;
|
||
if (!model || !line || !this.debuggable(model)) return;
|
||
if (type === monaco.editor.MouseTargetType.GUTTER_LINE_DECORATIONS && editor.__gutterRunAt?.(line)) return; // the Run / Debug icon of a command (gutter-run.js)
|
||
if (e.event.rightButton) {
|
||
const bp = this.list(pathOf(model.uri)).find((b) => b.line === line);
|
||
menu([
|
||
bp ? { label: 'Edit Condition…', action: () => this.editCondition(pathOf(model.uri), line) } : { label: 'Add Breakpoint', action: () => this.toggle(pathOf(model.uri), line) },
|
||
bp ? { label: 'Remove Breakpoint', action: () => this.toggle(pathOf(model.uri), line) } : null,
|
||
{ label: 'Remove All Breakpoints', action: () => this.clearAll() },
|
||
].filter(Boolean), { x: e.event.posx, y: e.event.posy });
|
||
return;
|
||
}
|
||
this.toggle(pathOf(model.uri), line);
|
||
});
|
||
}
|
||
|
||
debuggable(model) { return model.getLanguageId() === 'php'; }
|
||
|
||
list(path) { return this.breakpoints.get(path) || []; }
|
||
|
||
/** A breakpoint on / off at a line (Ctrl+F8 at the caret, a click in the gutter). */
|
||
toggle(path, line, condition = null) {
|
||
const list = this.list(path);
|
||
const next = list.some((b) => b.line === line) ? list.filter((b) => b.line !== line) : [...list, { line, condition }].sort((a, b) => a.line - b.line);
|
||
return this.set(path, next);
|
||
}
|
||
|
||
async editCondition(path, line) {
|
||
const bp = this.list(path).find((b) => b.line === line);
|
||
const condition = await prompt(t('Breakpoint condition'), { value: bp?.condition || '', label: t('{where}: stops only when this PHP expression is true (empty: always)', { where: `${basename(path)}:${line}` }), placeholder: '$this->score > 100' });
|
||
if (condition === null) return;
|
||
this.set(path, [...this.list(path).filter((b) => b.line !== line), { line, condition: condition.trim() || null }].sort((a, b) => a.line - b.line));
|
||
}
|
||
|
||
/** All the breakpoints of a file: kept (per project), drawn, given to the debugger (and the running programs). */
|
||
set(path, list) {
|
||
if (list.length) this.breakpoints.set(path, list); else this.breakpoints.delete(path);
|
||
prefs.set(this.key, Object.fromEntries(this.breakpoints));
|
||
const model = monaco.editor.getModel(uriOf(path));
|
||
if (model) this.decorate(model);
|
||
this.render();
|
||
return backend.invoke('debug.breakpoints', { path, lines: list }).catch(() => null);
|
||
}
|
||
|
||
clearAll() {
|
||
for (const path of [...this.breakpoints.keys()]) this.set(path, []);
|
||
}
|
||
|
||
/** The exceptions that stop the program where they are thrown (caught or not). */
|
||
async editExceptions() {
|
||
const value = await prompt(t('Stop at exceptions'), { value: this.exceptions.join(', '), placeholder: '* (every exception), or Error, TypeError, App\\GameOver',
|
||
label: t('The program stops where one of these is thrown, even when it is caught. * stops at every exception; empty: at none.') });
|
||
if (value === null) return;
|
||
this.setExceptions(value.split(/[\s,]+/).filter(Boolean));
|
||
}
|
||
|
||
setExceptions(classes) {
|
||
this.exceptions = [...new Set(classes.map((c) => c.replace(/^\\/, '')))];
|
||
prefs.set('exceptions:' + this.app.projectKey, this.exceptions);
|
||
this.render();
|
||
this.app.refreshToolHeader('debug');
|
||
return backend.invoke('debug.exceptions', { classes: this.exceptions }).catch(() => null);
|
||
}
|
||
|
||
decorate(model) {
|
||
const key = model.uri.toString();
|
||
const list = this.list(pathOf(model.uri));
|
||
const decorations = list.map((b) => ({
|
||
range: new monaco.Range(b.line, 1, b.line, 1),
|
||
options: { glyphMarginClassName: b.condition ? 'dbg-breakpoint conditional' : 'dbg-breakpoint', stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
|
||
glyphMarginHoverMessage: { value: b.condition ? t('Breakpoint when `{condition}`', { condition: b.condition }) : t('Breakpoint (click to remove, right click for a condition)') },
|
||
className: 'dbg-breakpoint-line', isWholeLine: true },
|
||
}));
|
||
this.decorations.set(key, model.deltaDecorations(this.decorations.get(key) || [], decorations));
|
||
}
|
||
|
||
watchModel(model) {
|
||
model.onDidChangeContent(() => { if (this.list(pathOf(model.uri)).length) this.syncLater(model); });
|
||
model.onWillDispose(() => { this.decorations.delete(model.uri.toString()); this.current.delete(model.uri.toString()); });
|
||
}
|
||
|
||
/** Lines moved by an edit: the breakpoints follow their lines (Monaco moves the decorations). */
|
||
readBack(model) {
|
||
if (model.isDisposed()) return;
|
||
const path = pathOf(model.uri);
|
||
const ids = this.decorations.get(model.uri.toString()) || [];
|
||
const old = this.list(path);
|
||
const moved = ids.map((id, i) => ({ line: model.getDecorationRange(id)?.startLineNumber, condition: old[i]?.condition || null }))
|
||
.filter((b) => b.line).filter((b, i, all) => all.findIndex((x) => x.line === b.line) === i);
|
||
if (JSON.stringify(moved) !== JSON.stringify(old)) this.set(path, moved);
|
||
}
|
||
|
||
// running ------------------------------------------------------------------------------------------------------
|
||
|
||
/** Debugs a run configuration (the selected one by default): JUMPHP_XDEBUG=<port> makes bin/jumphp start PHP with Xdebug. */
|
||
async debug(config = this.app.runner.config(), extraEnv = {}, engine = this.engine()) {
|
||
if (!config) return null;
|
||
let port;
|
||
try { ({ port } = await backend.invoke('debug.listen')); } catch (e) { notify(e.message, 'error', { title: t('The debugger cannot start') }); return null; }
|
||
// a project made before the debugger: its bin/jumphp does not start Xdebug yet (the IDE updates JumPHP in it)
|
||
const supports = () => backend.invoke('jumphp.supports', { feature: 'JUMPHP_XDEBUG' }).then((r) => r.ok, () => true);
|
||
if (!(await supports())) {
|
||
await this.app.updateJumphp({ ask: true, why: t('The debugger needs a newer JumPHP in this project: its bin/jumphp does not start Xdebug yet.') });
|
||
if (!(await supports())) {
|
||
notify(t('This project\'s bin/jumphp does not start Xdebug (JUMPHP_XDEBUG): update JumPHP in it, then Debug again.'), 'error', { title: t('Debug') + ' ' + config.label });
|
||
return null;
|
||
}
|
||
}
|
||
if (!this.breakpoints.size) notify(t('No breakpoint yet: click in the gutter left of a line of PHP to stop there.'), 'info', { title: t('Debug') + ' ' + config.label });
|
||
this.app.showTool('debug', true);
|
||
// the engine: Xdebug (default) or PHP Debugger (https://php-debugger.dev), both speak DBGp to this debugger
|
||
const env = { ...extraEnv, JUMPHP_XDEBUG: String(port) };
|
||
if (engine === 'php-debugger') {
|
||
env.JUMPHP_DEBUGGER = 'php-debugger';
|
||
// its Docker image is built by bin/jumphp at the first run (the IDE cannot see Docker's images): say so once
|
||
if (!prefs.get('phpDebuggerImageSeen', false)) {
|
||
prefs.set('phpDebuggerImageSeen', true);
|
||
notify(t('The PHP Debugger image is built once, about a minute: the first Debug waits for it.'), 'info', { title: t('Debugger') });
|
||
}
|
||
}
|
||
const id = await this.app.runner.start(config, env);
|
||
if (id !== null && id !== undefined) this.watchConnection(id, config, DEBUG_ENGINES[engine] || 'Xdebug');
|
||
return id;
|
||
}
|
||
|
||
/** The engine Debug uses: the choice saved for this project (else the last one made), Xdebug until the user picks another one. */
|
||
engine() {
|
||
const e = prefs.get('debugEngine:' + this.app.projectKey, null) ?? prefs.get('debugEngine', 'xdebug');
|
||
return DEBUG_ENGINES[e] ? e : 'xdebug';
|
||
}
|
||
|
||
setEngine(id) {
|
||
if (!DEBUG_ENGINES[id]) return;
|
||
prefs.set('debugEngine:' + this.app.projectKey, id);
|
||
prefs.set('debugEngine', id);
|
||
this.updateBadge();
|
||
notify(t('Debug now uses {name} by default.', { name: DEBUG_ENGINES[id] }), 'info', { title: t('Debugger') });
|
||
}
|
||
|
||
/** The tiny X / PD badge on the header's Debug button: which engine will run. */
|
||
updateBadge() {
|
||
const id = this.engine();
|
||
const badge = document.getElementById('debugEngineBadge');
|
||
if (badge) badge.textContent = ENGINE_BADGE[id];
|
||
const btn = document.getElementById('debugBtn');
|
||
if (btn) {
|
||
btn.title = t('Debug (Shift+F9): {name}. Click for the debugger menu.', { name: DEBUG_ENGINES[id] });
|
||
btn.setAttribute('aria-haspopup', 'menu');
|
||
}
|
||
}
|
||
|
||
/** The Debug button's menu (a click or a right click): start, the engine (remembered), documentation, MCP for an AI. */
|
||
debugMenu(at) {
|
||
const current = this.engine();
|
||
const pd = current === 'php-debugger';
|
||
const btn = document.getElementById('debugBtn');
|
||
btn?.setAttribute('aria-expanded', 'true');
|
||
const close = menu([
|
||
{ label: t('Debug') + ' — ' + (pd ? 'PHP Debugger' : 'Xdebug'), icon: 'debug', kbd: 'Shift+F9', action: () => this.debug() },
|
||
'-',
|
||
{ head: t('Debugger engine') },
|
||
{ label: t('Xdebug (default: full DBGp, the widest tooling)'), checked: !pd, action: () => this.setEngine('xdebug') },
|
||
{ label: t('PHP Debugger (near-zero overhead, built for AI debugging via MCP, PHP 8.2–8.5; not in the async runtime)'), checked: pd, action: () => this.setEngine('php-debugger') },
|
||
'-',
|
||
{ label: t('Documentation'), icon: 'globe', action: () => this.app.openUrl(DEBUG_DOCS) },
|
||
pd ? { label: t('Debug with an AI (MCP)…'), action: () => this.mcpDialog() } : null,
|
||
].filter(Boolean), at);
|
||
return close;
|
||
}
|
||
|
||
/** The two commands that give an AI (Claude Code) PHP Debugger's tools, to copy or to run in the Terminal. */
|
||
mcpDialog() {
|
||
const row = (command) => el('div', { style: { margin: '10px 0' } },
|
||
el('code', { style: { display: 'block', padding: '6px 8px', background: 'var(--panel-2)', border: '1px solid var(--border-2)', borderRadius: '4px', userSelect: 'all', overflowX: 'auto', whiteSpace: 'nowrap' } }, command),
|
||
el('div', { style: { marginTop: '4px', display: 'flex', gap: '6px' } },
|
||
el('button.btn', { onclick: async () => { await copyText(command); notify(t('Copied'), 'success', { title: t('Debugger') }); } }, t('Copy')),
|
||
this.app.terminal ? el('button.btn', { onclick: () => { this.app.terminal.run(command, 'Debug MCP'); this.app.showTool('terminal', true); } }, t('Run it for me')) : null));
|
||
dialog({ title: t('Debug with an AI (MCP)'), wide: true,
|
||
body: el('div', {}, el('p', {}, t('Add these to Claude Code once, then it sets breakpoints, runs the program and inspects variables through the same debugger.')), ...MCP_COMMANDS.map(row)),
|
||
buttons: [{ label: t('Close'), primary: true }] });
|
||
}
|
||
|
||
/** Debug with... : a menu to pick the engine for this run (the checked one is the default; "Make default" below). */
|
||
debugWith(at) {
|
||
const current = this.engine();
|
||
menu([
|
||
{ head: t('Debug with') },
|
||
...Object.entries(DEBUG_ENGINES).map(([id, label]) => ({ label, checked: id === current, action: () => this.debug(undefined, {}, id) })),
|
||
'-',
|
||
{ head: t('Default engine') },
|
||
...Object.entries(DEBUG_ENGINES).map(([id, label]) => ({ label, checked: id === current, action: () => this.setEngine(id) })),
|
||
], at);
|
||
}
|
||
|
||
/** Says so when the program never connects to the debugger (instead of nothing happening). */
|
||
watchConnection(runId, config, name = 'Xdebug') {
|
||
let connected = false;
|
||
const offs = [];
|
||
const stop = () => { offs.forEach((off) => off?.()); clearTimeout(timer); };
|
||
const warn = (why) => notify(t('{label}: {name} did not connect to the IDE ({why}). The run\'s output (Run window) may say why; the first Debug builds the desktop image with {name} (about a minute).',
|
||
{ label: config.label, name, why: t(why) }), 'error', { title: t('Debugger') });
|
||
offs.push(backend.on('debug.state', (s) => { if ((s.sessions || []).length) { connected = true; stop(); } }));
|
||
offs.push(backend.on('run.exit', (p) => { if (p.id === runId) { stop(); if (!connected) warn('the program ended first'); } }));
|
||
const timer = setTimeout(() => { stop(); if (!connected) warn('nothing after 3 minutes'); }, 180000);
|
||
}
|
||
|
||
async step(how) {
|
||
const session = this.paused?.session || this.sessions?.[0]?.id;
|
||
if (!session) return;
|
||
if (how !== 'stop') this.cleared();
|
||
try {
|
||
await backend.invoke('debug.resume', { session, how });
|
||
} catch (e) {
|
||
notify(e.message, 'error', { title: t('Debugger') });
|
||
}
|
||
if (how === 'stop') this.cleared();
|
||
}
|
||
|
||
/** Runs to a line (Alt+F9): it stops there once, or earlier at a breakpoint. */
|
||
async runTo(path, line) {
|
||
const session = this.paused?.session;
|
||
if (!session) return;
|
||
this.cleared();
|
||
try {
|
||
await backend.invoke('debug.runTo', { session, path, line });
|
||
} catch (e) {
|
||
notify(e.message, 'error', { title: t('Run to Cursor') });
|
||
}
|
||
}
|
||
|
||
/** A new value for a variable of the stopped frame (a PHP expression, evaluated there). */
|
||
async setValue(v) {
|
||
if (!this.paused || !v.fullname) return;
|
||
const current = v.type === 'string' ? JSON.stringify(v.value) : ['array', 'object'].includes(v.type) ? '' : String(v.value ?? '');
|
||
const expression = await prompt(t('Set {name}', { name: v.fullname }), { value: current, label: t('A PHP expression, evaluated where the program is stopped: 9, "Ada", [1, 2], null, $other * 2…') });
|
||
if (expression === null || !expression.trim()) return;
|
||
try {
|
||
await backend.invoke('debug.set', { session: this.paused.session, fullname: v.fullname, expression, depth: this.frame });
|
||
await this.showFrame();
|
||
} catch (e) {
|
||
notify(e.message, 'error', { title: t('Set Value') });
|
||
}
|
||
}
|
||
|
||
onPaused(p) {
|
||
this.inspector?.stopped(true);
|
||
this.paused = p;
|
||
this.frame = 0;
|
||
this.variables = null;
|
||
this.tree.resetOpen();
|
||
this.app.badge('debug', 'on');
|
||
this.app.showTool('debug', true);
|
||
this.showFrame();
|
||
this.app.refreshToolHeader('debug');
|
||
}
|
||
|
||
cleared() {
|
||
this.inspector?.stopped(false);
|
||
this.paused = null;
|
||
this.variables = null;
|
||
for (const [key, ids] of this.current) {
|
||
const model = monaco.editor.getModel(monaco.Uri.parse(key));
|
||
if (model && !model.isDisposed()) model.deltaDecorations(ids, []);
|
||
}
|
||
this.current.clear();
|
||
this.render();
|
||
this.app.refreshToolHeader('debug');
|
||
}
|
||
|
||
/** Opens where the selected frame is, marks the line, reads its variables. */
|
||
async showFrame() {
|
||
const frame = this.paused?.stack?.[this.frame];
|
||
if (this.variables === null || !this.paused) this.render();
|
||
if (!frame) return;
|
||
if (frame.path) {
|
||
await this.app.editors.open(frame.path, { line: frame.line, select: false, focus: false });
|
||
const model = monaco.editor.getModel(uriOf(frame.path));
|
||
for (const [key, ids] of this.current) {
|
||
const m = monaco.editor.getModel(monaco.Uri.parse(key));
|
||
if (m && !m.isDisposed()) m.deltaDecorations(ids, []);
|
||
}
|
||
this.current.clear();
|
||
if (model) {
|
||
this.current.set(model.uri.toString(), model.deltaDecorations([], [{ range: new monaco.Range(frame.line, 1, frame.line, 1),
|
||
options: { isWholeLine: true, className: 'dbg-current-line', glyphMarginClassName: 'dbg-current' } }]));
|
||
}
|
||
}
|
||
const session = this.paused.session;
|
||
try {
|
||
this.variables = await backend.invoke('debug.variables', { session, depth: this.frame });
|
||
} catch (e) {
|
||
this.variables = [];
|
||
}
|
||
await this.evaluateWatches();
|
||
if (this.paused?.session === session) this.render();
|
||
}
|
||
|
||
async evaluateWatches() {
|
||
this.watchValues = [];
|
||
for (const expression of this.watches) {
|
||
try {
|
||
this.watchValues.push({ ...(await backend.invoke('debug.eval', { session: this.paused?.session, expression })), name: expression, expression });
|
||
} catch (e) {
|
||
this.watchValues.push({ name: expression, expression, value: e.message, type: 'error' });
|
||
}
|
||
}
|
||
}
|
||
|
||
addWatch(expression) {
|
||
expression = expression.trim();
|
||
if (!expression || this.watches.includes(expression)) return;
|
||
this.watches = [...this.watches, expression];
|
||
prefs.set('watches:' + this.app.projectKey, this.watches);
|
||
if (this.paused) this.evaluateWatches().then(() => this.render()); else this.render();
|
||
}
|
||
|
||
removeWatch(expression) {
|
||
this.watches = this.watches.filter((w) => w !== expression);
|
||
prefs.set('watches:' + this.app.projectKey, this.watches);
|
||
this.watchValues = (this.watchValues || []).filter((w) => w.expression !== expression);
|
||
this.render();
|
||
}
|
||
|
||
// the tool window -----------------------------------------------------------------------------------------------
|
||
|
||
/** Draws the window again, keeping what the user did in it: the scroll and the rows opened (VarTree.openKeys). Never leaves it empty. */
|
||
render() {
|
||
const scroll = this.node.querySelector('.debug-vars')?.scrollTop || 0;
|
||
try {
|
||
this.draw();
|
||
} catch (e) {
|
||
clear(this.node);
|
||
this.node.append(el('div.placeholder', {}, `error: ${e?.message || e}`));
|
||
}
|
||
const vars = this.node.querySelector('.debug-vars');
|
||
if (vars && scroll) vars.scrollTop = scroll;
|
||
}
|
||
|
||
draw() {
|
||
clear(this.node);
|
||
const frames = el('div.debug-frames');
|
||
const vars = el('div.debug-vars');
|
||
this.node.append(frames, vars);
|
||
if (!this.paused) {
|
||
const listening = (this.sessions || []).length ? t('A program is running with the debugger: it stops at the next breakpoint.') : t('Not debugging. Debug (Shift+F9) runs the selected configuration with Xdebug.');
|
||
frames.append(el('div.placeholder', {}, listening));
|
||
} else {
|
||
if (this.paused.exception) {
|
||
const x = this.paused.exception;
|
||
frames.append(el('div.debug-exception', { title: t('Stopped where it is thrown (Stop at Exceptions…)') }, icon('warning'), el('b', {}, x.class), x.message ? el('div.debug-exception-message', {}, x.message) : null));
|
||
}
|
||
this.paused.stack.forEach((f, i) => frames.append(el('div.row' + (i === this.frame ? '.sel' : ''), {
|
||
title: f.path ? `${f.path}:${f.line}` : t('outside the project'),
|
||
onclick: () => { this.frame = i; this.variables = null; this.tree.resetOpen(); this.showFrame(); },
|
||
}, el('span.label', {}, f.where || '{main}'), el('span.hint', {}, f.path ? `${basename(f.path)}:${f.line}` : t('line {n}', { n: f.line })))));
|
||
}
|
||
const input = el('input.debug-eval', { placeholder: this.paused ? t('Evaluate an expression (Enter), or add a watch (Ctrl+Enter)') : t('Add a watch (Enter)'), spellcheck: false,
|
||
onkeydown: async (e) => {
|
||
if (e.key !== 'Enter' || !input.value.trim()) return;
|
||
const expression = input.value;
|
||
if (!this.paused || e.ctrlKey || e.metaKey) { this.addWatch(expression); input.value = ''; return; }
|
||
try {
|
||
this.evaluated = { ...(await backend.invoke('debug.eval', { session: this.paused.session, expression })), name: expression, expression };
|
||
} catch (err) {
|
||
this.evaluated = { name: expression, value: err.message, type: 'error' };
|
||
}
|
||
this.render();
|
||
this.node.querySelector('input.debug-eval')?.focus();
|
||
} });
|
||
vars.append(input);
|
||
if (this.evaluated && this.paused) vars.append(this.row(this.evaluated, 0, { result: true }));
|
||
for (const w of (this.paused ? this.watchValues : null) || this.watches.map((expression) => ({ name: expression, expression, value: '', type: 'watch' }))) {
|
||
vars.append(this.row(w, 0, { watch: true }));
|
||
}
|
||
if (this.paused && this.variables) {
|
||
if (!this.variables.length) vars.append(el('div.placeholder', {}, t('No variables here.')));
|
||
for (const v of this.variables) vars.append(this.row(v, 0));
|
||
} else if (this.paused) {
|
||
vars.append(el('div.placeholder', {}, t('Reading the variables…')));
|
||
}
|
||
const count = [...this.breakpoints.values()].reduce((n, l) => n + l.length, 0);
|
||
if (!this.paused && this.exceptions.length) {
|
||
vars.append(el('div.debug-section', {}, t('Exceptions')),
|
||
el('div.row', { onclick: () => this.editExceptions(), title: t('Change them') }, icon('warning'), el('span.label', {}, this.exceptions.includes('*') ? t('Every exception') : this.exceptions.join(', ')),
|
||
el('span.hint', {}, t('stops where thrown')),
|
||
el('button.row-action', { title: t('Stop at none'), onclick: (e) => { e.stopPropagation(); this.setExceptions([]); } }, icon('close'))));
|
||
}
|
||
if (!this.paused && count) {
|
||
vars.append(el('div.debug-section', {}, t('Breakpoints ({n})', { n: count })));
|
||
for (const [path, list] of this.breakpoints) {
|
||
for (const b of list) {
|
||
vars.append(el('div.row', { onclick: () => this.app.editors.open(path, { line: b.line }) },
|
||
el('span.dbg-dot' + (b.condition ? '.conditional' : '')), el('span.label', {}, `${basename(path)}:${b.line}`),
|
||
el('span.hint', {}, b.condition ? t('when {condition}', { condition: b.condition }) : path),
|
||
el('button.row-action', { title: t('Remove'), onclick: (e) => { e.stopPropagation(); this.toggle(path, b.line); } }, icon('close'))));
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
/** One variable (and its children once opened, read from Xdebug then): the tree shared with the hover inspector (var-tree.js). */
|
||
row(v, level, { watch = false, result = false } = {}) {
|
||
return this.tree.row(v, level, { watch, result, onRemove: watch ? (w) => this.removeWatch(w.expression) : null });
|
||
}
|
||
|
||
/** What the variable tree and the hover inspector ask of the debugger (the frame shown, the program stopped). */
|
||
treeContext() {
|
||
return {
|
||
canSet: () => !!this.paused,
|
||
fetchChildren: async (v, page = 0) => {
|
||
if (!this.paused) return { items: [] };
|
||
this.inspector?.guard.busy(1);
|
||
try {
|
||
const r = await backend.invoke('debug.children', { session: this.paused.session, fullname: v.fullname || v.expression, depth: this.frame, page });
|
||
return { items: r?.items || [], size: r?.size, pagesize: r?.pagesize };
|
||
} finally {
|
||
this.inspector?.guard.busy(-1);
|
||
}
|
||
},
|
||
apply: (v, expression) => backend.invoke('debug.set', { session: this.paused.session, fullname: v.fullname || v.expression, expression, depth: this.frame }),
|
||
promptSet: (v) => this.setValue(v),
|
||
watch: (expression) => this.addWatch(expression),
|
||
changed: () => { this.showFrame(); this.inspector?.refresh(); },
|
||
};
|
||
}
|
||
}
|