Add Python REPL widget for WebGL build

Features:
- JSFiddle-style code editor panel alongside game canvas
- Run button (or Ctrl+Enter) executes Python code
- Reset button reloads game.py
- Tab key inserts 4 spaces for proper indentation
- Shows >>> prompt with code preview
- Displays repr of last expression (like Python REPL)
- Error highlighting in red, success in green
- Canvas focus handling with visual indicator

C++ exports (callable from JavaScript):
- run_python_string(code) - simple execution
- run_python_string_with_output(code) - captures stdout/stderr + expr repr
- reset_python_environment() - reloads game.py

JavaScript API available in console:
- runPython(code) - execute Python and get output
- resetGame() - reset to initial state
- FS.readFile/writeFile - access virtual filesystem

Also fixes canvas focus issues on page load.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
John McCardle 2026-01-31 15:31:18 -05:00
commit 1be2714240
3 changed files with 453 additions and 22 deletions

View file

@ -7,6 +7,9 @@
#include <sys/resource.h>
#include <wchar.h>
#include <errno.h>
#include <emscripten.h>
#include <Python.h>
#include <string>
extern "C" {
@ -33,6 +36,134 @@ size_t wcsftime(wchar_t *wcs, size_t maxsize, const wchar_t *format, const struc
return 0;
}
// =============================================================================
// JavaScript-callable Python execution functions
// =============================================================================
// Run a Python string and return the result code (0 = success, -1 = error)
EMSCRIPTEN_KEEPALIVE
int run_python_string(const char* code) {
if (!Py_IsInitialized()) {
return -1;
}
return PyRun_SimpleString(code);
}
// Run Python code and capture stdout/stderr as a string
// Returns a pointer to a static buffer (caller should copy immediately)
static std::string python_output_buffer;
EMSCRIPTEN_KEEPALIVE
const char* run_python_string_with_output(const char* code) {
if (!Py_IsInitialized()) {
python_output_buffer = "Error: Python not initialized";
return python_output_buffer.c_str();
}
// Redirect stdout and stderr to a StringIO, run code, capture output
// Also capture repr of last expression (like Python REPL)
const char* capture_code = R"(
import sys
import io
_mcrf_stdout_capture = io.StringIO()
_mcrf_stderr_capture = io.StringIO()
_mcrf_old_stdout = sys.stdout
_mcrf_old_stderr = sys.stderr
sys.stdout = _mcrf_stdout_capture
sys.stderr = _mcrf_stderr_capture
_mcrf_exec_error = None
_mcrf_last_repr = None
try:
# Try to compile as eval (expression) first
_mcrf_code_obj = compile(_mcrf_user_code, '<repl>', 'eval')
_mcrf_result = eval(_mcrf_code_obj, globals())
if _mcrf_result is not None:
_mcrf_last_repr = repr(_mcrf_result)
except SyntaxError:
# Not a simple expression, try exec
try:
exec(_mcrf_user_code, globals())
except Exception as e:
import traceback
_mcrf_exec_error = traceback.format_exc()
except Exception as e:
import traceback
_mcrf_exec_error = traceback.format_exc()
sys.stdout = _mcrf_old_stdout
sys.stderr = _mcrf_old_stderr
_mcrf_captured_output = _mcrf_stdout_capture.getvalue()
if _mcrf_stderr_capture.getvalue():
_mcrf_captured_output += _mcrf_stderr_capture.getvalue()
if _mcrf_exec_error:
_mcrf_captured_output += _mcrf_exec_error
elif _mcrf_last_repr:
_mcrf_captured_output += _mcrf_last_repr
)";
// Set the user code as a Python variable
PyObject* main_module = PyImport_AddModule("__main__");
PyObject* main_dict = PyModule_GetDict(main_module);
PyObject* py_code = PyUnicode_FromString(code);
PyDict_SetItemString(main_dict, "_mcrf_user_code", py_code);
Py_DECREF(py_code);
// Run the capture code
PyRun_SimpleString(capture_code);
// Get the captured output
PyObject* output = PyDict_GetItemString(main_dict, "_mcrf_captured_output");
if (output && PyUnicode_Check(output)) {
const char* output_str = PyUnicode_AsUTF8(output);
python_output_buffer = output_str ? output_str : "";
} else {
python_output_buffer = "";
}
// Clean up temporary variables
PyDict_DelItemString(main_dict, "_mcrf_user_code");
PyDict_DelItemString(main_dict, "_mcrf_stdout_capture");
PyDict_DelItemString(main_dict, "_mcrf_stderr_capture");
PyDict_DelItemString(main_dict, "_mcrf_old_stdout");
PyDict_DelItemString(main_dict, "_mcrf_old_stderr");
PyDict_DelItemString(main_dict, "_mcrf_exec_error");
PyDict_DelItemString(main_dict, "_mcrf_captured_output");
return python_output_buffer.c_str();
}
// Reset the Python environment (re-run game.py)
EMSCRIPTEN_KEEPALIVE
int reset_python_environment() {
if (!Py_IsInitialized()) {
return -1;
}
// Clear all scenes and reload game.py
const char* reset_code = R"(
import mcrfpy
import sys
# Try to reload the game module
if 'game' in sys.modules:
del sys.modules['game']
# Re-execute game.py
try:
with open('/scripts/game.py', 'r') as f:
exec(f.read(), globals())
print("Environment reset successfully")
except Exception as e:
print(f"Reset error: {e}")
)";
return PyRun_SimpleString(reset_code);
}
} // extern "C"
#endif // __EMSCRIPTEN__

View file

@ -5,42 +5,165 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>McRogueFace - WebGL</title>
<style>
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 20px;
background: #1a1a2e;
display: flex;
flex-direction: column;
align-items: center;
font-family: 'Segoe UI', system-ui, sans-serif;
color: #eee;
min-height: 100vh;
}
.container {
max-width: 1400px;
margin: 0 auto;
}
header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 10px;
}
h1 {
margin-bottom: 10px;
margin: 0;
color: #e94560;
}
#status {
margin-bottom: 10px;
color: #888;
}
.emscripten {
display: block;
margin: 0 auto;
.main-content {
display: flex;
gap: 20px;
flex-wrap: wrap;
}
.game-panel {
flex: 1;
min-width: 300px;
}
#canvas {
border: 2px solid #e94560;
background: #000;
display: block;
max-width: 100%;
height: auto;
/* Crisp pixel rendering - no smoothing/interpolation */
image-rendering: pixelated;
image-rendering: crisp-edges;
-ms-interpolation-mode: nearest-neighbor;
/* Ensure canvas can receive focus */
outline: none;
}
#canvas:focus {
border-color: #4ecca3;
box-shadow: 0 0 10px rgba(78, 204, 163, 0.5);
}
.repl-panel {
width: 400px;
min-width: 300px;
display: flex;
flex-direction: column;
background: #16213e;
border-radius: 8px;
overflow: hidden;
}
.repl-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 15px;
background: #0f3460;
border-bottom: 1px solid #e94560;
}
.repl-header h3 {
margin: 0;
font-size: 14px;
color: #e94560;
}
.repl-buttons {
display: flex;
gap: 8px;
}
.repl-buttons button {
padding: 6px 12px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 12px;
font-weight: 600;
transition: all 0.2s;
}
#runBtn {
background: #4ecca3;
color: #1a1a2e;
}
#runBtn:hover {
background: #3db892;
}
#resetBtn {
background: #e94560;
color: white;
}
#resetBtn:hover {
background: #d63050;
}
#clearBtn {
background: #666;
color: white;
}
#clearBtn:hover {
background: #555;
}
.repl-buttons button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
#codeEditor {
width: 100%;
height: 250px;
padding: 12px;
border: none;
background: #0f0f23;
color: #4ecca3;
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
font-size: 13px;
line-height: 1.5;
resize: vertical;
outline: none;
}
#codeEditor::placeholder {
color: #555;
}
.repl-output-header {
padding: 8px 15px;
background: #0f3460;
font-size: 12px;
color: #888;
border-top: 1px solid #333;
}
#replOutput {
flex: 1;
min-height: 150px;
max-height: 250px;
overflow-y: auto;
padding: 12px;
background: #0a0a15;
font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', monospace;
font-size: 12px;
white-space: pre-wrap;
color: #ccc;
}
#replOutput .error {
color: #e94560;
}
#replOutput .success {
color: #4ecca3;
}
#output {
margin-top: 20px;
max-width: 1024px;
width: 100%;
max-height: 200px;
max-height: 150px;
overflow-y: auto;
background: #0f0f23;
padding: 10px;
@ -48,9 +171,10 @@
font-size: 12px;
white-space: pre-wrap;
border: 1px solid #333;
border-radius: 4px;
}
.spinner {
margin: 20px;
margin: 20px auto;
width: 50px;
height: 50px;
border: 5px solid #333;
@ -61,20 +185,82 @@
@keyframes spin {
to { transform: rotate(360deg); }
}
.toggle-repl {
display: none;
margin-top: 10px;
padding: 8px 16px;
background: #0f3460;
border: 1px solid #e94560;
color: #e94560;
border-radius: 4px;
cursor: pointer;
}
@media (max-width: 900px) {
.main-content {
flex-direction: column;
}
.repl-panel {
width: 100%;
}
}
/* Keyboard shortcut hint */
.shortcut-hint {
font-size: 11px;
color: #666;
margin-left: 8px;
}
</style>
</head>
<body>
<h1>McRogueFace</h1>
<div id="status">Downloading...</div>
<div id="spinner" class="spinner"></div>
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex="-1"></canvas>
<div id="output"></div>
<div class="container">
<header>
<h1>McRogueFace</h1>
<div id="status">Downloading...</div>
</header>
<div id="spinner" class="spinner"></div>
<div class="main-content">
<div class="game-panel">
<canvas class="emscripten" id="canvas" oncontextmenu="event.preventDefault()" tabindex="-1"></canvas>
</div>
<div class="repl-panel" id="replPanel">
<div class="repl-header">
<h3>Python REPL</h3>
<div class="repl-buttons">
<button id="runBtn" disabled>Run</button>
<button id="resetBtn" disabled>Reset</button>
<button id="clearBtn">Clear</button>
<span class="shortcut-hint">Ctrl+Enter to run</span>
</div>
</div>
<textarea id="codeEditor" placeholder="Write Python code here...
import mcrfpy
scene = mcrfpy.Scene('test')
frame = mcrfpy.Frame(100, 100, 200, 150)
scene.ui.append(frame)
mcrfpy.setScene('test')
"></textarea>
<div class="repl-output-header">Output</div>
<div id="replOutput"></div>
</div>
</div>
<div id="output"></div>
</div>
<script type='text/javascript'>
var statusElement = document.getElementById('status');
var spinnerElement = document.getElementById('spinner');
var outputElement = document.getElementById('output');
var canvasElement = document.getElementById('canvas');
var codeEditor = document.getElementById('codeEditor');
var replOutput = document.getElementById('replOutput');
var runBtn = document.getElementById('runBtn');
var resetBtn = document.getElementById('resetBtn');
var clearBtn = document.getElementById('clearBtn');
// Pre-set canvas size
canvasElement.width = 1024;
@ -117,6 +303,30 @@
onRuntimeInitialized: function() {
console.log('Emscripten runtime initialized');
spinnerElement.style.display = 'none';
// Enable REPL buttons
runBtn.disabled = false;
resetBtn.disabled = false;
// Make FS available globally for console access
window.FS = Module.FS;
// Create convenient Python execution functions
window.runPython = function(code) {
return Module.ccall('run_python_string_with_output', 'string', ['string'], [code]);
};
window.resetGame = function() {
return Module.ccall('reset_python_environment', 'number', [], []);
};
replOutput.innerHTML = '<span class="success">Python REPL ready. Enter code and click Run (or Ctrl+Enter).</span>\n';
// Focus canvas after a short delay to ensure SDL is ready
setTimeout(function() {
canvasElement.focus();
// Trigger a synthetic resize to ensure SDL is properly initialized
window.dispatchEvent(new Event('resize'));
}, 100);
}
};
@ -127,7 +337,7 @@
spinnerElement.style.display = 'none';
};
// Stub for resolveGlobalSymbol - needed by Emscripten's promising main feature
// Stub for resolveGlobalSymbol
if (typeof resolveGlobalSymbol === 'undefined') {
window.resolveGlobalSymbol = function(name, direct) {
return {
@ -137,9 +347,7 @@
};
}
// Prevent browser zoom on canvas (Ctrl+scroll causes Emscripten heap errors)
// Use capture phase to intercept BEFORE Emscripten's handlers
// Also stop propagation to prevent the event from reaching SDL
// Prevent browser zoom on canvas
document.addEventListener('wheel', function(e) {
if (e.ctrlKey) {
e.preventDefault();
@ -148,7 +356,6 @@
}
}, { passive: false, capture: true });
// Also prevent Ctrl+Plus/Minus zoom
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && (e.key === '+' || e.key === '-' || e.key === '=' || e.key === '_')) {
e.preventDefault();
@ -156,6 +363,98 @@
return false;
}
}, { capture: true });
// Click on canvas to focus it (for keyboard input)
canvasElement.addEventListener('click', function() {
canvasElement.focus();
});
// Also handle mousedown to ensure focus happens before SDL processes the click
canvasElement.addEventListener('mousedown', function() {
if (document.activeElement !== canvasElement) {
canvasElement.focus();
}
});
// REPL functionality
function runCode() {
var code = codeEditor.value;
if (!code.trim()) return;
replOutput.innerHTML += '<span style="color:#666">>>> </span><span style="color:#888">' + escapeHtml(code.split('\n')[0]) + (code.includes('\n') ? '...' : '') + '</span>\n';
try {
var result = window.runPython(code);
if (result) {
// Check if result contains error indicators
if (result.includes('Traceback') || result.includes('Error:')) {
replOutput.innerHTML += '<span class="error">' + escapeHtml(result) + '</span>\n';
} else {
// Show result (could be print output or repr of expression)
replOutput.innerHTML += '<span class="success">' + escapeHtml(result) + '</span>\n';
}
}
} catch (e) {
replOutput.innerHTML += '<span class="error">JavaScript Error: ' + escapeHtml(e.toString()) + '</span>\n';
}
replOutput.scrollTop = replOutput.scrollHeight;
}
function resetEnvironment() {
replOutput.innerHTML += '<span style="color:#888">>>> Resetting environment...</span>\n';
try {
window.resetGame();
replOutput.innerHTML += '<span class="success">Environment reset.</span>\n';
} catch (e) {
replOutput.innerHTML += '<span class="error">Reset error: ' + escapeHtml(e.toString()) + '</span>\n';
}
replOutput.scrollTop = replOutput.scrollHeight;
}
function clearOutput() {
replOutput.innerHTML = '';
}
function escapeHtml(text) {
var div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
// Button handlers
runBtn.addEventListener('click', runCode);
resetBtn.addEventListener('click', resetEnvironment);
clearBtn.addEventListener('click', clearOutput);
// Keyboard shortcut: Ctrl+Enter to run
// IMPORTANT: Stop propagation to prevent SDL from consuming keystrokes
codeEditor.addEventListener('keydown', function(e) {
e.stopPropagation(); // Prevent SDL from receiving this event
if (e.ctrlKey && e.key === 'Enter') {
e.preventDefault();
if (!runBtn.disabled) {
runCode();
}
}
// Tab key inserts spaces instead of changing focus
if (e.key === 'Tab') {
e.preventDefault();
var start = this.selectionStart;
var end = this.selectionEnd;
this.value = this.value.substring(0, start) + ' ' + this.value.substring(end);
this.selectionStart = this.selectionEnd = start + 4;
}
});
// Stop all keyboard events from reaching SDL when REPL is focused
codeEditor.addEventListener('keyup', function(e) {
e.stopPropagation();
});
codeEditor.addEventListener('keypress', function(e) {
e.stopPropagation();
});
</script>
{{{ SCRIPT }}}
</body>