205 lines
12 KiB
JavaScript
205 lines
12 KiB
JavaScript
// The Cryo window's "Hot" tab: the program run with memory metrics changed while it runs, nothing lost (engine/src/Cryo/HotPatch.php):
|
||
// - Hot patch: the method / function under the editor's cursor replaces the running one (Cryo\Engine), a constant changed,
|
||
// every change in a journal, undone one by one or all;
|
||
// - Console: PHP typed and run inside the program between two frames ($engine, $scene, variables kept), Monaco's PHP colours and
|
||
// completions from the running program itself (the real objects' methods and properties, classes, functions), history with ↑ ↓.
|
||
// The PHP side: ide/src/Cryo/CryoCommands.php cryo.patch.* / cryo.console.* (a request file the program answers).
|
||
import { backend } from './backend.js';
|
||
import { el, clear, icon, notify, prefs, t } from './ui.js';
|
||
import { monaco } from './editor.js';
|
||
|
||
const LANG = 'php-console';
|
||
let langReady = null;
|
||
|
||
/** a PHP language for code without "<?php": Monaco's own PHP rules, started in PHP instead of HTML */
|
||
async function consoleLanguage() {
|
||
if (langReady) return langReady;
|
||
langReady = (async () => {
|
||
const php = monaco.languages.getLanguages().find((l) => l.id === 'php');
|
||
monaco.languages.register({ id: LANG });
|
||
try {
|
||
const mod = await php.loader();
|
||
const start = Object.keys(mod.language.tokenizer).find((s) => /^phpInSimpleState$/.test(s)) || 'phpInSimpleState';
|
||
monaco.languages.setMonarchTokensProvider(LANG, { ...mod.language, start });
|
||
monaco.languages.setLanguageConfiguration(LANG, mod.conf);
|
||
} catch (e) { /* no colours: plain text */ }
|
||
const kinds = { method: monaco.languages.CompletionItemKind.Method, property: monaco.languages.CompletionItemKind.Property, variable: monaco.languages.CompletionItemKind.Variable,
|
||
constant: monaco.languages.CompletionItemKind.Constant, function: monaco.languages.CompletionItemKind.Function, class: monaco.languages.CompletionItemKind.Class };
|
||
monaco.languages.registerCompletionItemProvider(LANG, {
|
||
triggerCharacters: ['>', ':', '$', '\\'],
|
||
async provideCompletionItems(model, position) {
|
||
const text = model.getValueInRange({ startLineNumber: 1, startColumn: 1, endLineNumber: position.lineNumber, endColumn: position.column });
|
||
let items = [];
|
||
try { items = (await backend.invoke('cryo.console.complete', { text })).items || []; } catch (e) { return { suggestions: [] }; }
|
||
const word = model.getWordUntilPosition(position);
|
||
const range = { startLineNumber: position.lineNumber, endLineNumber: position.lineNumber, startColumn: word.startColumn, endColumn: word.endColumn };
|
||
return { suggestions: items.map((i) => {
|
||
// "$var" and "\Class": the typed "$" / "\" stays, Monaco's word does not hold it
|
||
const before = model.getLineContent(position.lineNumber).slice(0, word.startColumn - 1);
|
||
let insert = i.label;
|
||
if (insert.startsWith('$') && before.endsWith('$')) insert = insert.slice(1);
|
||
if (insert.startsWith('\\') && /[\\\w]$/.test(before)) insert = insert.replace(/^.*\\/, '');
|
||
if (i.kind === 'method' || i.kind === 'function') insert += i.detail === '()' || /^\(\)/.test(i.detail) ? '()' : '($0)';
|
||
return { label: i.label, kind: kinds[i.kind] ?? monaco.languages.CompletionItemKind.Text, detail: i.detail, insertText: insert,
|
||
insertTextRules: monaco.languages.CompletionItemInsertTextRule.InsertAsSnippet, range };
|
||
}) };
|
||
},
|
||
});
|
||
})();
|
||
return langReady;
|
||
}
|
||
|
||
export class HotTab {
|
||
constructor(panel) {
|
||
this.panel = panel;
|
||
this.app = panel.app;
|
||
this.journal = [];
|
||
this.lines = []; // the console's log: {code, output, result, error}
|
||
this.history = prefs.get('cryoConsoleHistory', []);
|
||
this.at = this.history.length;
|
||
this.constant = { name: '', value: '' };
|
||
this.input = null;
|
||
}
|
||
|
||
render(body) {
|
||
this.body = body;
|
||
body.append(el('p.pub-faint', {}, t('Run the game with "Run with memory metrics" (Live tab). Then change it while it runs, nothing lost: the method under the cursor replaces the running one, the console runs PHP inside the game.')));
|
||
// hot patch
|
||
const journal = el('div.cryo-detail');
|
||
this.journalNode = journal;
|
||
body.append(el('h5', {}, t('Hot patch')),
|
||
el('div.cryo-row', {},
|
||
el('button.btn.primary', { onclick: () => this.patchAtCursor() }, icon('zap'), t('Patch the method at the cursor')),
|
||
el('button.btn', { onclick: () => this.revert(null) }, icon('undo'), t('Undo every patch')),
|
||
el('button.btn', { onclick: () => this.loadJournal() }, icon('refresh'), t('Journal'))),
|
||
el('div.cryo-row', {},
|
||
el('input.input', { placeholder: 'App\\Scene\\PlayScene::SPEED', value: this.constant.name, oninput: (e) => { this.constant.name = e.target.value; } }),
|
||
el('input.input.cryo-num', { placeholder: '120', value: this.constant.value, oninput: (e) => { this.constant.value = e.target.value; } }),
|
||
el('button.btn', { onclick: () => this.patchConstant() }, t('Set the constant'))),
|
||
journal);
|
||
this.showJournal();
|
||
// console
|
||
const log = el('div.cryo-console-log');
|
||
this.logNode = log;
|
||
const host = el('div.cryo-console-input');
|
||
body.append(el('h5', {}, t('Console')),
|
||
el('p.pub-faint', {}, t('PHP run inside the running game, between two frames: $engine and $scene are there, your variables stay. Enter runs it, Shift+Enter a new line, ↑ ↓ the history, Ctrl+Space completions.')),
|
||
log, host,
|
||
el('div.cryo-row', {}, el('button.btn.primary', { onclick: () => this.run() }, icon('play'), t('Run')),
|
||
el('button.btn', { onclick: () => { this.lines = []; this.showLog(); } }, t('Clear'))));
|
||
this.showLog();
|
||
this.mountInput(host);
|
||
}
|
||
|
||
async mountInput(host) {
|
||
if (!monaco) { host.append(el('p.cryo-error', {}, t('The editor is not loaded yet.'))); return; }
|
||
await consoleLanguage();
|
||
if (!host.isConnected) return;
|
||
const model = monaco.editor.createModel(this.input?.getValue() || '', LANG);
|
||
this.input?.dispose();
|
||
const editor = monaco.editor.create(host, {
|
||
model, minimap: { enabled: false }, lineNumbers: 'off', glyphMargin: false, folding: false, scrollBeyondLastLine: false,
|
||
automaticLayout: true, fontSize: 13, wordWrap: 'on', renderLineHighlight: 'none', overviewRulerLanes: 0, scrollbar: { vertical: 'auto', horizontal: 'hidden' },
|
||
theme: document.documentElement.dataset.theme === 'light' ? 'vs' : 'jumphp-dark', suggestOnTriggerCharacters: true, quickSuggestions: { other: true, strings: false },
|
||
});
|
||
this.input = editor;
|
||
const fit = () => { host.style.height = Math.min(200, Math.max(28, editor.getContentHeight())) + 'px'; editor.layout(); };
|
||
editor.onDidContentSizeChange(fit); fit();
|
||
const suggesting = () => document.querySelector('.cryo-console-input .suggest-widget.visible');
|
||
editor.onKeyDown((e) => {
|
||
const K = monaco.KeyCode;
|
||
if (e.keyCode === K.Enter && !e.shiftKey && !suggesting()) { e.preventDefault(); e.stopPropagation(); this.run(); }
|
||
else if ((e.keyCode === K.UpArrow || e.keyCode === K.DownArrow) && !suggesting()) {
|
||
const line = editor.getPosition().lineNumber;
|
||
const up = e.keyCode === K.UpArrow;
|
||
if ((up && line === 1) || (!up && line === model.getLineCount())) {
|
||
e.preventDefault();
|
||
this.at = Math.max(0, Math.min(this.history.length, this.at + (up ? -1 : 1)));
|
||
model.setValue(this.history[this.at] ?? '');
|
||
editor.setPosition({ lineNumber: model.getLineCount(), column: model.getLineMaxColumn(model.getLineCount()) });
|
||
}
|
||
}
|
||
});
|
||
editor.focus();
|
||
}
|
||
|
||
async run() {
|
||
const code = this.input?.getValue().trim();
|
||
if (!code) return;
|
||
this.history = [...this.history.filter((h) => h !== code), code].slice(-200);
|
||
prefs.set('cryoConsoleHistory', this.history);
|
||
this.at = this.history.length;
|
||
this.input.setValue('');
|
||
const line = { code, busy: true };
|
||
this.lines.push(line); this.showLog();
|
||
try { Object.assign(line, await backend.invoke('cryo.console.eval', { code })); } catch (e) { line.error = String(e.message || e); }
|
||
line.busy = false;
|
||
this.showLog();
|
||
}
|
||
|
||
showLog() {
|
||
if (!this.logNode) return;
|
||
clear(this.logNode);
|
||
for (const l of this.lines.slice(-100)) {
|
||
const input = el('pre.cryo-console-code', {}, l.code);
|
||
if (monaco && langReady) monaco.editor.colorize(l.code, LANG, {}).then((html) => { input.innerHTML = html; }).catch(() => null);
|
||
this.logNode.append(el('div.cryo-console-entry', {}, el('span.cryo-console-prompt', {}, '›'), input,
|
||
l.busy ? el('div.pub-faint', {}, t('Running…')) : null,
|
||
l.output ? el('pre.cryo-out', {}, l.output) : null,
|
||
l.result ? el('pre.cryo-console-result', {}, (l.type ? l.type + ' ' : '') + l.result) : null,
|
||
l.error ? el('pre.cryo-error', {}, l.error) : null));
|
||
}
|
||
this.logNode.scrollTop = this.logNode.scrollHeight;
|
||
}
|
||
|
||
async patchAtCursor() {
|
||
const tab = this.app.editors?.activeTab();
|
||
const ed = this.app.editors?.focused?.editor;
|
||
if (!tab || !ed) { notify(t('Open the file and put the cursor in the method first.'), 'error', { title: t('Hot patch') }); return; }
|
||
try {
|
||
const r = await backend.invoke('cryo.patch.method', { path: tab.path, line: ed.getPosition().lineNumber, code: ed.getModel().getValue() });
|
||
const target = r.target.class ? `${r.target.class}::${r.target.method}()` : `${r.target.function}()`;
|
||
notify(t('{target} replaced in the running game.', { target }), 'info', { title: t('Hot patch') });
|
||
this.journal = r.journal || []; this.showJournal();
|
||
} catch (e) { notify(String(e.message || e), 'error', { title: t('Hot patch') }); }
|
||
}
|
||
|
||
async patchConstant() {
|
||
let value = this.constant.value.trim();
|
||
try { value = JSON.parse(value); } catch (e) { /* a plain string */ }
|
||
try {
|
||
const r = await backend.invoke('cryo.patch.constant', { name: this.constant.name.trim(), value });
|
||
this.journal = r.journal || []; this.showJournal();
|
||
} catch (e) { notify(String(e.message || e), 'error', { title: t('Hot patch') }); }
|
||
}
|
||
|
||
async revert(change) {
|
||
try { const r = await backend.invoke('cryo.patch.revert', change == null ? {} : { change }); this.journal = r.journal || []; this.showJournal(); }
|
||
catch (e) { notify(String(e.message || e), 'error', { title: t('Hot patch') }); }
|
||
}
|
||
|
||
async loadJournal() {
|
||
try { this.journal = (await backend.invoke('cryo.patch.journal', {})).journal || []; this.showJournal(); }
|
||
catch (e) { notify(String(e.message || e), 'error', { title: t('Hot patch') }); }
|
||
}
|
||
|
||
showJournal() {
|
||
if (!this.journalNode) return;
|
||
clear(this.journalNode);
|
||
if (!this.journal.length) { this.journalNode.append(el('p.pub-faint', {}, t('No change in the running game.'))); return; }
|
||
this.journalNode.append(this.panel.table(['#', 'Change', 'Target', ''], this.journal.map((j) => [String(j.id), j.kind, j.target,
|
||
el('button.btn.small', { onclick: () => this.revert(j.id) }, t('Undo'))])));
|
||
}
|
||
}
|
||
|
||
// Claude's tools (agent.js)
|
||
export const hotAgentTools = {
|
||
async tool_cryo_patch(args) {
|
||
const path = args.path;
|
||
const r = await backend.invoke('cryo.patch.method', { path, line: args.line || 1 });
|
||
return { target: r.target, change: r.change, journal: r.journal };
|
||
},
|
||
async tool_cryo_patch_constant(args) { return backend.invoke('cryo.patch.constant', { name: args.name, value: args.value }); },
|
||
async tool_cryo_patch_revert(args) { return backend.invoke('cryo.patch.revert', args.change == null ? {} : { change: args.change }); },
|
||
async tool_cryo_console(args) { return backend.invoke('cryo.console.eval', { code: args.code }); },
|
||
};
|