载入中...
搜索中...
未找到
EditorHost.cpp
浏览该文件的文档.
1#include "ui/EditorHost.h"
2
3#include "common/config.h"
4
5#if defined(EVENGINE_WEBGPU) && defined(__EMSCRIPTEN__)
6
7// The browser runtime trims Poco / DevTools / the host path. Keep EVUI
8// linkable with a no-op implementation; `eve mcp` is desktop-only anyway.
9namespace eve::ui {
10struct EditorHost::Impl {};
11
12EditorHost& EditorHost::instance() {
13 static EditorHost* inst = new EditorHost();
14 return *inst;
15}
16EditorHost::EditorHost() = default;
17EditorHost::~EditorHost() = default;
18void EditorHost::start(ssq::VM&, const std::string&, bool) {}
19void EditorHost::stop() {}
20bool EditorHost::isWindowOpen() const { return false; }
21std::string EditorHost::openWindow(const std::string&, int, int) {
22 return "error: editor host unavailable on this platform";
23}
24std::string EditorHost::closeWindow() { return "ok"; }
25std::string EditorHost::windowState() const { return "{}"; }
26std::string EditorHost::applyEditor(const std::string&) {
27 return "error: editor host unavailable on this platform";
28}
29std::string EditorHost::removeEditor(const std::string&) {
30 return "error: editor host unavailable on this platform";
31}
32std::string EditorHost::listEditors() const { return "{\"editors\":[]}"; }
33std::string EditorHost::editorState(const std::string&) const { return "{\"editors\":[]}"; }
35std::string EditorHost::setEditorValue(const std::string&, const std::string&, const std::string&) {
36 return "error: editor host unavailable on this platform";
37}
38std::string EditorHost::consumeEvents(const std::string&) { return "[]"; }
39std::string EditorHost::widgetRect(const std::string&, const std::string&) const {
40 return "{\"x\":0,\"y\":0,\"width\":0,\"height\":0}";
41}
42std::string EditorHost::registerVM(const std::string&, const std::string&, const std::string&) {
43 return "error: editor host unavailable on this platform";
44}
45std::string EditorHost::unregisterVM(const std::string&) {
46 return "error: editor host unavailable on this platform";
47}
48std::string EditorHost::saveEditor(const std::string&) {
49 return "error: editor host unavailable on this platform";
50}
51std::string EditorHost::unloadEditor(const std::string&) {
52 return "error: editor host unavailable on this platform";
53}
55std::string EditorHost::runScript(const std::string&, const std::string&) {
56 return "error: editor host unavailable on this platform";
57}
58std::string EditorHost::capture(const std::string&) {
59 return "error: editor host unavailable on this platform";
60}
61std::string EditorHost::status() const {
62 return "{\"running\":false,\"windowOpen\":false,\"editors\":[],\"viewModels\":[]}";
63}
64void EditorHost::frame() {}
66void EditorHost::exposeScriptApi(ssq::VM&) {}
67} // namespace eve::ui
68
69#else // full implementation
70
71#include "common/Module.h"
72#include "common/Runtime.h"
74#include "common/ScriptError.h"
75#include "common/ScriptModule.h"
77#include "filesystem/FileData.h"
78#include "graphics/Graphics.h"
79#include "image/ImageData.h"
81#include "timer/Timer.h"
82#include "ui/UI.h"
84#include "window/Window.h"
85
86#include <Poco/Dynamic/Var.h>
87#include <Poco/Exception.h>
88#include <Poco/JSON/Array.h>
89#include <Poco/JSON/Object.h>
90#include <Poco/JSON/Parser.h>
91#include <Poco/JSON/Stringifier.h>
92
93#include <imgui.h>
94#include <imgui_internal.h>
95#include <simplesquirrel/simplesquirrel.hpp>
96#include <squirrel.h>
97
98#include <algorithm>
99#include <cstdlib>
100#include <cstring>
101#include <cstdio>
102#include <fstream>
103#include <filesystem>
104#include <fstream>
105#include <functional>
106#include <map>
107#include <sstream>
108#include <string>
109#include <utility>
110#include <vector>
111
112namespace eve::ui {
113namespace {
114
115using Poco::Dynamic::Var;
116using Poco::JSON::Array;
117using Poco::JSON::Object;
118using Poco::JSON::Parser;
119
120std::string jsonStringify(const Var& v) {
121 std::ostringstream oss;
122 Poco::JSON::Stringifier::stringify(v, oss, 0, 0);
123 return oss.str();
124}
125
126Object::Ptr parseObject(const std::string& json) {
127 Poco::JSON::Parser parser;
128 return parser.parse(json).extract<Object::Ptr>();
129}
130
131std::string strOf(Object::Ptr o, const char* key, const std::string& def = {}) {
132 if (!o || !o->has(key)) return def;
133 try {
134 return o->get(key).convert<std::string>();
135 } catch (...) {
136 return def;
137 }
138}
139
140int intOf(Object::Ptr o, const char* key, int def = 0) {
141 if (!o || !o->has(key)) return def;
142 try {
143 return o->get(key).convert<int>();
144 } catch (...) {
145 return def;
146 }
147}
148
149float floatOf(Object::Ptr o, const char* key, float def = 0.f) {
150 if (!o || !o->has(key)) return def;
151 try {
152 return static_cast<float>(o->get(key).convert<double>());
153 } catch (...) {
154 return def;
155 }
156}
157
158bool boolOf(Object::Ptr o, const char* key, bool def = false) {
159 if (!o || !o->has(key)) return def;
160 try {
161 return o->get(key).convert<bool>();
162 } catch (...) {
163 return def;
164 }
165}
166
167float varFloat(const Var& v, float def = 0.f) {
168 try {
169 return static_cast<float>(v.convert<double>());
170 } catch (...) {
171 return def;
172 }
173}
174
175bool varBool(const Var& v, bool def = false) {
176 try {
177 return v.convert<bool>();
178 } catch (...) {
179 return def;
180 }
181}
182
183std::string varString(const Var& v, const std::string& def = {}) {
184 try {
185 return v.convert<std::string>();
186 } catch (...) {
187 return def;
188 }
189}
190
191Array::Ptr varToArray(const Var& v) {
192 try {
193 return v.extract<Array::Ptr>();
194 } catch (...) {
195 return nullptr;
196 }
197}
198
199std::vector<float> varFloats(const Var& v) {
200 std::vector<float> out;
201 Array::Ptr arr = varToArray(v);
202 if (!arr) return out;
203 for (size_t i = 0; i < arr->size(); ++i) {
204 try {
205 out.push_back(
206 static_cast<float>(arr->get(static_cast<unsigned int>(i)).convert<double>()));
207 } catch (...) {
208 out.push_back(0.f);
209 }
210 }
211 return out;
212}
213
215std::vector<float> widgetFloatInit(const Var& v) {
216 std::vector<float> init = varFloats(v);
217 if (!init.empty()) return init;
218 try {
219 init.push_back(static_cast<float>(v.convert<double>()));
220 } catch (...) {
221 }
222 return init;
223}
224
225std::vector<std::string> varStrings(const Var& v) {
226 std::vector<std::string> out;
227 Array::Ptr arr = varToArray(v);
228 if (!arr) return out;
229 for (size_t i = 0; i < arr->size(); ++i)
230 out.push_back(varString(arr->get(static_cast<unsigned int>(i))));
231 return out;
232}
233
234// ---- raw Squirrel helpers -------------------------------------------------
235
236Var stackVar(HSQUIRRELVM vm, SQInteger index) {
237 switch (sq_gettype(vm, index)) {
238 case OT_NULL:
239 return Var();
240 case OT_BOOL: {
241 SQBool b = SQFalse;
242 if (SQ_SUCCEEDED(sq_getbool(vm, index, &b))) return Var(bool(b));
243 return Var();
244 }
245 case OT_INTEGER: {
246 SQInteger i = 0;
247 if (SQ_SUCCEEDED(sq_getinteger(vm, index, &i)))
248 return Var(static_cast<Poco::Int64>(i));
249 return Var();
250 }
251 case OT_FLOAT: {
252 SQFloat f = 0.f;
253 if (SQ_SUCCEEDED(sq_getfloat(vm, index, &f)))
254 return Var(static_cast<double>(f));
255 return Var();
256 }
257 case OT_STRING: {
258 const SQChar* s = nullptr;
259 if (SQ_SUCCEEDED(sq_getstring(vm, index, &s)) && s) return Var(std::string(s));
260 return Var();
261 }
262 case OT_ARRAY: {
263 HSQOBJECT obj;
264 if (SQ_FAILED(sq_getstackobj(vm, index, &obj))) return Var();
265 sq_pushobject(vm, obj);
266 sq_pushnull(vm);
267 Array::Ptr arr = new Array();
268 while (SQ_SUCCEEDED(sq_next(vm, -2))) {
269 arr->add(stackVar(vm, -1));
270 sq_pop(vm, 2);
271 }
272 sq_pop(vm, 1);
273 return Var(arr);
274 }
275 default:
276 return Var();
277 }
278}
279
280void pushVar(HSQUIRRELVM vm, const Var& v) {
281 if (v.isEmpty()) {
282 sq_pushnull(vm);
283 return;
284 }
285 try {
286 if (v.isBoolean()) {
287 sq_pushbool(vm, v.convert<bool>() ? SQTrue : SQFalse);
288 return;
289 }
290 if (v.isNumeric()) {
291 sq_pushfloat(vm, static_cast<SQFloat>(v.convert<double>()));
292 return;
293 }
294 if (v.isString()) {
295 const std::string s = v.convert<std::string>();
296 sq_pushstring(vm, s.c_str(), static_cast<SQInteger>(s.size()));
297 return;
298 }
299 if (v.isArray()) {
300 Array::Ptr arr;
301 try {
302 arr = v.extract<Array::Ptr>();
303 } catch (...) {
304 sq_pushnull(vm);
305 return;
306 }
307 sq_newarray(vm, 0);
308 if (arr) {
309 for (size_t i = 0; i < arr->size(); ++i) {
310 pushVar(vm, arr->get(static_cast<unsigned int>(i)));
311 if (SQ_FAILED(sq_arrayappend(vm, -2))) break;
312 }
313 }
314 return;
315 }
316 } catch (...) {
317 }
318 sq_pushnull(vm);
319}
320
322std::string runSquirrel(HSQUIRRELVM vm, const std::string& source, const char* name) {
323 const SQInteger top = sq_gettop(vm);
324 // ScriptCompiler::compileBuffer records `import` edges and compiles those
325 // modules. A raw sq_compilebuffer leaves them Compiled-but-not-Ready, so
326 // the import opcode then fails with "module was not instantiated".
328 static_cast<SQInteger>(source.size()),
329 name, SQTrue))) {
330 // A compile error never reaches the runtime error store, so it is read from the
331 // compiler's own context. Reporting only "compile failed" told the tool caller
332 // nothing about the file, line or reason.
333 const script::ScriptErrorContext context = script::captureCompileError(vm);
334 sq_settop(vm, top);
335 if (context.empty()) return "compile failed";
336 return "compile failed: " + script::formatScriptError(context);
337 }
338 if (Runtime* rt = ModuleManager::runtime()) {
339 try {
340 rt->scriptModules().instantiateDependencies(name);
341 } catch (const std::exception& error) {
342 sq_settop(vm, top);
343 return error.what();
344 }
345 }
346 sq_pushroottable(vm);
347 // The count is derived from the pushes (R-FACE-7): the compiled chunk plus its
348 // receiver. The failure report is consumed here because the caller needs the reason
349 // text for its own message.
350 const SQInteger params = sq_gettop(vm) - top - 1; // receiver + arguments
351 if (SQ_FAILED(sq_call(vm, params, SQFalse, SQTrue))) {
352 const std::string detail = script::reportScriptCallFailure(vm, name);
353 sq_settop(vm, top);
354 return "runtime failed: " + detail;
355 }
356 sq_settop(vm, top);
357 return {};
358}
359
360void callRootFunc(HSQUIRRELVM vm, const std::string& name, const std::vector<Var>& args) {
361 const SQInteger top = sq_gettop(vm);
362 sq_pushroottable(vm);
363 sq_pushstring(vm, name.c_str(), static_cast<SQInteger>(name.size()));
364 if (SQ_FAILED(sq_get(vm, -2))) {
365 sq_settop(vm, top);
366 return; // hook not defined
367 }
368 if (sq_gettype(vm, -1) != OT_CLOSURE) {
369 sq_settop(vm, top);
370 return;
371 }
372 // Remove the lookup table so only the closure precedes receiver + arguments.
373 sq_remove(vm, -2);
374 sq_pushroottable(vm);
375 for (const auto& a : args) pushVar(vm, a);
376 // `Var` is a runtime variant, so the shared helper's typed-argument form does not fit;
377 // the count is derived from the pushes instead -- the same rule (R-FACE-7). The report
378 // used to be a bare "%s() failed" that left out the reason the hook raised.
379 const SQInteger params = sq_gettop(vm) - top - 1; // receiver + arguments
380 if (SQ_FAILED(sq_call(vm, params, SQFalse, SQTrue))) script::reportScriptCallFailure(vm, name.c_str());
381 sq_settop(vm, top);
382}
383
384bool callTableFunc(HSQUIRRELVM vm, const ssq::Table& tbl, const std::string& name,
385 const std::vector<Var>& args, std::string* err) {
386 if (name.empty()) return true;
387 const SQInteger top = sq_gettop(vm);
388 try {
389 ssq::Function fn = tbl.findFunc(name.c_str());
390 sq_pushobject(vm, fn.getRaw());
391 sq_pushobject(vm, tbl.getRaw());
392 for (const auto& a : args) pushVar(vm, a);
393 // Same runtime-variant exception as callRootFunc(): derive the count, and let the
394 // shared reporter produce the reason the callback raised.
395 const SQInteger params = sq_gettop(vm) - top - 1; // receiver + arguments
396 if (SQ_FAILED(sq_call(vm, params, SQFalse, SQTrue))) {
397 const std::string detail = script::reportScriptCallFailure(vm, name.c_str());
398 if (err) *err = "runtime failed: " + name + ": " + detail;
399 sq_settop(vm, top);
400 return false;
401 }
402 sq_settop(vm, top);
403 return true;
404 } catch (const ssq::NotFoundException&) {
405 sq_settop(vm, top);
406 return true; // optional callback / command absent
407 } catch (const std::exception& e) {
408 if (err) *err = e.what();
409 sq_settop(vm, top);
410 return false;
411 }
412}
413
415bool splitBindPath(const std::string& bind, std::string& slot, std::string& nested) {
416 if (bind.rfind("vm.", 0) != 0) return false;
417 std::string rest = bind.substr(3);
418 const size_t dot = rest.find('.');
419 if (dot == std::string::npos) {
420 slot = rest;
421 nested.clear();
422 } else if (rest.find('.', dot + 1) == std::string::npos) {
423 slot = rest.substr(0, dot);
424 nested = rest.substr(dot + 1);
425 } else {
426 return false; // only one nesting level supported in v1
427 }
428 return !slot.empty();
429}
430
431Var objectToVar(ssq::VM& vm, const ssq::Object& o) {
432 // Push the object and convert through the stack so arrays recurse cleanly.
433 HSQUIRRELVM v = vm.getHandle();
434 const SQInteger top = sq_gettop(v);
435 sq_pushobject(v, o.getRaw());
436 Var out = stackVar(v, -1);
437 sq_settop(v, top);
438 return out;
439}
440
441Var readVMVar(ssq::VM& vm, const ssq::Table& tbl, const std::string& bind, bool* ok = nullptr) {
442 std::string slot, nested;
443 if (ok) *ok = false;
444 if (!splitBindPath(bind, slot, nested)) return Var();
445 try {
446 ssq::Object o = tbl.find(slot.c_str());
447 if (!nested.empty()) {
448 if (o.getType() != ssq::Type::TABLE) return Var();
449 o = o.toTable().find(nested.c_str());
450 }
451 if (ok) *ok = true;
452 return objectToVar(vm, o);
453 } catch (...) {
454 return Var();
455 }
456}
457
458void writeVMVar(ssq::VM& vm, const ssq::Table& tbl, const std::string& bind, const Var& value) {
459 std::string slot, nested;
460 if (!splitBindPath(bind, slot, nested)) return;
461 HSQUIRRELVM v = vm.getHandle();
462 const SQInteger top = sq_gettop(v);
463 if (nested.empty()) {
464 sq_pushobject(v, tbl.getRaw());
465 sq_pushstring(v, slot.c_str(), static_cast<SQInteger>(slot.size()));
466 pushVar(v, value);
467 sq_newslot(v, -3, false);
468 } else {
469 try {
470 ssq::Table t2 = tbl.find(slot.c_str()).toTable();
471 sq_pushobject(v, t2.getRaw());
472 sq_pushstring(v, nested.c_str(), static_cast<SQInteger>(nested.size()));
473 pushVar(v, value);
474 sq_newslot(v, -3, false);
475 } catch (...) {
476 }
477 }
478 sq_settop(v, top);
479}
480
481struct HostEvent {
482 std::string type; // "click" | "change" | "closed"
483 std::string widget;
484 Var value;
485};
486
487struct Editor {
488 std::string id;
489 std::string title;
490 std::string vmName;
491 Object::Ptr view;
492 float x = 0.f, y = 0.f, width = 0.f, height = 0.f;
493 bool resizable = true;
494 bool collapsible = true;
495 std::string layout = "vertical";
496 Object::Ptr theme;
497 std::map<std::string, Var> values;
498 std::vector<HostEvent> events;
499 std::map<std::string, ImVec2> rectMin, rectMax;
500 bool removed = false;
501};
502
503void forEachWidget(Object::Ptr parent, const std::function<void(Object::Ptr)>& fn) {
504 if (!parent) return;
505 Array::Ptr kids = parent->has("children") ? parent->getArray("children") : nullptr;
506 if (!kids) return;
507 for (size_t i = 0; i < kids->size(); ++i) {
508 Object::Ptr w = kids->getObject(static_cast<unsigned>(i));
509 if (!w) continue;
510 fn(w);
511 forEachWidget(w, fn);
512 }
513}
514
515Object::Ptr findWidget(Object::Ptr parent, const std::string& id) {
516 if (!parent || id.empty()) return nullptr;
517 Array::Ptr kids = parent->has("children") ? parent->getArray("children") : nullptr;
518 if (!kids) return nullptr;
519 for (size_t i = 0; i < kids->size(); ++i) {
520 Object::Ptr w = kids->getObject(static_cast<unsigned>(i));
521 if (!w) continue;
522 if (strOf(w, "id") == id) return w;
523 if (Object::Ptr sub = findWidget(w, id)) return sub;
524 }
525 return nullptr;
526}
527
528std::string widgetIdLabel(Object::Ptr w) {
529 const std::string id = strOf(w, "id");
530 const std::string label = strOf(w, "label");
531 if (label.empty()) return "##" + id;
532 if (id.empty()) return label;
533 return label + "##" + id;
534}
535
537std::string vmFuncName(const std::string& path) {
538 if (path.rfind("vm.", 0) == 0) return path.substr(3);
539 return path;
540}
541
542void recordRect(Editor& ed, const std::string& id) {
543 if (id.empty()) return;
544 ed.rectMin[id] = ImGui::GetItemRectMin();
545 ed.rectMax[id] = ImGui::GetItemRectMax();
546}
547
548void emitEvent(Editor& ed, const std::string& type, const std::string& widget, const Var& value) {
549 ed.events.push_back({type, widget, value});
550}
551
552void renderChildren(EditorHost::Impl& I, Editor& ed, Array::Ptr kids, const std::string& layout);
553void syncVMToView(EditorHost::Impl& I, Editor& ed);
554
555} // namespace
556
557// Out-of-line definition of the pimpl. Lives at eve::ui scope (not inside the
558// anonymous namespace) so it can be named as eve::ui::EditorHost::Impl.
560 ssq::VM* vm = nullptr;
561 bool allowWindow = true;
562 std::string rootDir;
565 eve::ui::UI* ui = nullptr;
568 bool windowOpen = false;
569 bool inFrame = false;
570 std::string windowTitle;
571 std::map<std::string, Editor> editors;
572 std::map<std::string, ssq::Table> vms;
573 std::map<std::string, std::string> vmSources;
574};
575
576// ---------------------------------------------------------------------------
577// public surface
578// ---------------------------------------------------------------------------
579
581 // Intentionally leaked: the host VM may be torn down after the singleton.
582 static EditorHost* inst = new EditorHost();
583 return *inst;
584}
585
586EditorHost::EditorHost() = default;
587EditorHost::~EditorHost() = default;
588
589void EditorHost::start(ssq::VM& vm, const std::string& gameRoot, bool allowWindow) {
590 if (running_) return;
591 impl_ = std::make_unique<Impl>();
592 impl_->vm = &vm;
593 impl_->allowWindow = allowWindow;
594 allowWindow_ = allowWindow;
595 gameRoot_ = gameRoot.empty() ? std::filesystem::current_path().string() : gameRoot;
596 impl_->rootDir = gameRoot_;
597 running_ = true;
599}
600
602 if (!running_) return;
603 closeWindow();
604 impl_.reset();
605 running_ = false;
606 exitRequested_ = false;
607}
608
609std::string EditorHost::openWindow(const std::string& title, int width, int height) {
610 if (!impl_) return "error: host not started";
611 auto& I = *impl_;
612 if (!I.allowWindow) return "error: window creation disabled";
613 try {
614 if (!I.win) I.win = ModuleManager::requireInstance<eve::window::Window>("Window");
615 if (!I.gfx) I.gfx = ModuleManager::requireInstance<eve::graphics::Graphics>("Graphics");
616 // setWindowSettings() always close()+SDL_CreateWindow. Reuse any live
617 // OS window (load.nut, a previous openWindow, or MCP attaching later).
618 const bool alreadyOpen = I.win->isOpen() || I.win->getHandle() != nullptr;
619 if (alreadyOpen) {
620 std::fprintf(stderr, "[editor-host] reuse existing window %dx%d\n",
621 I.win->getWidth(), I.win->getHeight());
622 if (!title.empty()) I.win->setWindowTitle(title);
623 } else {
625 s.width = static_cast<uint16_t>(width > 0 ? width : 1280);
626 s.height = static_cast<uint16_t>(height > 0 ? height : 800);
627 s.centered = true;
628 s.resizable = true;
629 std::fprintf(stderr, "[editor-host] create window %dx%d\n",
630 static_cast<int>(s.width), static_cast<int>(s.height));
631 if (!I.win->setWindowSettings(s)) return "error: setWindowSettings failed";
632 I.win->setWindowTitle(title.empty() ? "EVEngine AI Host" : title);
633 }
634 if (!I.ui) I.ui = ModuleManager::requireInstance<eve::ui::UI>("UI");
635 I.windowOpen = true;
636 I.windowTitle = title.empty() ? I.win->getWindowTitle() : title;
637 // Keep screen readback on while the host window is open: the AI's whole
638 // feedback loop is "render -> capture", so every presented frame should
639 // be available to eve_host_capture immediately (the Vulkan backend
640 // installs the present-copy hook as soon as readback is enabled).
641 if (I.gfx) I.gfx->setScreenReadbackEnabled(true);
642 return "ok";
643 } catch (const std::exception& e) {
644 return std::string("error: ") + e.what();
645 }
646}
647
649 if (!impl_) return "ok";
650 auto& I = *impl_;
651 if (I.windowOpen && I.win) {
652 try {
653 I.win->close();
654 } catch (...) {
655 }
656 if (I.ui) I.ui->shutdownBackend();
657 I.windowOpen = false;
658 }
659 return "ok";
660}
661
663 return impl_ && impl_->windowOpen;
664}
665
666std::string EditorHost::windowState() const {
667 if (!impl_ || !impl_->windowOpen) return "{\"open\":false}";
668 Object::Ptr o = new Object();
669 o->set("open", true);
670 o->set("title", impl_->windowTitle);
671 if (impl_->win) {
672 o->set("width", impl_->win->getWidth());
673 o->set("height", impl_->win->getHeight());
674 }
675 return jsonStringify(Var(o));
676}
677
678std::string EditorHost::applyEditor(const std::string& json) {
679 if (!impl_) return "error: host not started";
680 auto& I = *impl_;
681 try {
682 Object::Ptr root = parseObject(json);
683 const std::string id = strOf(root, "id");
684 if (id.empty()) return "error: editor requires id";
685 Editor ed;
686 ed.id = id;
687 ed.title = strOf(root, "title", id);
688 ed.vmName = strOf(root, "vm");
689 ed.view = root;
690 ed.x = static_cast<float>(intOf(root, "x", 0));
691 ed.y = static_cast<float>(intOf(root, "y", 0));
692 ed.width = static_cast<float>(intOf(root, "width", 0));
693 ed.height = static_cast<float>(intOf(root, "height", 0));
694 ed.resizable = boolOf(root, "resizable", true);
695 ed.collapsible = boolOf(root, "collapsible", true);
696 ed.layout = strOf(root, "layout", "vertical");
697 if (root->has("theme")) ed.theme = root->getObject("theme");
698 forEachWidget(root, [&](Object::Ptr w) {
699 const std::string wid = strOf(w, "id");
700 if (wid.empty()) return;
701 if (w->has("value")) ed.values[wid] = w->get("value");
702 });
703 I.editors[id] = std::move(ed);
704 if (!I.windowOpen && I.allowWindow) {
705 // Prefer the live window size (config.nut) over the 1280x800
706 // fallback so applyEditor cannot close()+recreate a different size.
707 int w = 1280;
708 int h = 800;
709 try {
710 if (!I.win) I.win = ModuleManager::requireInstance<eve::window::Window>("Window");
711 if (I.win->isOpen() || I.win->getHandle() != nullptr) {
712 w = I.win->getWidth();
713 h = I.win->getHeight();
714 }
715 } catch (...) {
716 }
717 std::string err = openWindow(I.editors.at(id).title + " - EVEngine AI Host", w, h);
718 if (err.rfind("error:", 0) == 0) return err;
719 }
720 return editorState(id);
721 } catch (const std::exception& e) {
722 return std::string("error: ") + e.what();
723 }
724}
725
726std::string EditorHost::removeEditor(const std::string& id) {
727 if (!impl_) return "error: host not started";
728 auto it = impl_->editors.find(id);
729 if (it == impl_->editors.end()) return "error: editor not found: " + id;
730 impl_->editors.erase(it);
731 return "ok";
732}
733
734std::string EditorHost::listEditors() const {
735 if (!impl_) return "{\"editors\":[]}";
736 Array::Ptr arr = new Array();
737 for (const auto& [k, ed] : impl_->editors) {
738 Object::Ptr o = new Object();
739 o->set("id", k);
740 o->set("title", ed.title);
741 o->set("vm", ed.vmName);
742 arr->add(o);
743 }
744 Object::Ptr root = new Object();
745 root->set("editors", arr);
746 return jsonStringify(Var(root));
747}
748
749namespace {
750
751Poco::JSON::Object::Ptr editorStateObject(const Editor& ed) {
752 Object::Ptr o = new Object();
753 o->set("id", ed.id);
754 o->set("title", ed.title);
755 o->set("vm", ed.vmName);
756 Object::Ptr vals = new Object();
757 for (const auto& [k, v] : ed.values) vals->set(k, v);
758 o->set("values", vals);
759 Array::Ptr evs = new Array();
760 for (const auto& e : ed.events) {
761 Object::Ptr eo = new Object();
762 eo->set("editor", ed.id);
763 eo->set("widget", e.widget);
764 eo->set("type", e.type);
765 if (!e.value.isEmpty()) eo->set("value", e.value);
766 evs->add(eo);
767 }
768 o->set("events", evs);
769 return o;
770}
771
772} // namespace
773
774std::string EditorHost::editorState(const std::string& id) const {
775 if (!impl_) return "{\"editors\":[]}";
776 const_cast<EditorHost*>(this)->syncBindings();
777 Array::Ptr arr = new Array();
778 if (!id.empty()) {
779 auto it = impl_->editors.find(id);
780 if (it == impl_->editors.end()) return "error: editor not found: " + id;
781 arr->add(editorStateObject(it->second));
782 } else {
783 for (const auto& [k, ed] : impl_->editors) arr->add(editorStateObject(ed));
784 }
785 Object::Ptr root = new Object();
786 root->set("editors", arr);
787 return jsonStringify(Var(root));
788}
789
791 if (!impl_) return;
792 for (auto& [k, ed] : impl_->editors) syncVMToView(*impl_, ed);
793}
794
795namespace {
796
797void pushViewToVM(EditorHost::Impl& I, Editor& ed, const std::string& widgetId, const Var& value) {
798 if (!I.vm || ed.vmName.empty()) return;
799 auto it = I.vms.find(ed.vmName);
800 if (it == I.vms.end()) return;
801 Object::Ptr w = findWidget(ed.view, widgetId);
802 if (!w) return;
803 const std::string bind = strOf(w, "bind");
804 if (!bind.empty()) writeVMVar(*I.vm, it->second, bind, value);
805 const std::string onChange = strOf(w, "onChange");
806 if (!onChange.empty()) {
807 std::string err;
808 callTableFunc(I.vm->getHandle(), it->second, vmFuncName(onChange),
809 {Var(widgetId), value}, &err);
810 if (!err.empty())
811 fprintf(stderr, "eve.host: onChange %s: %s\n", onChange.c_str(), err.c_str());
812 }
813}
814
815void setWidgetValue(EditorHost::Impl& I, Editor& ed, const std::string& widgetId,
816 const Var& value) {
817 ed.values[widgetId] = value;
818 emitEvent(ed, "change", widgetId, value);
819 pushViewToVM(I, ed, widgetId, value);
820}
821
822void resolveOneWay(EditorHost::Impl& I, Editor& ed, Object::Ptr w) {
823 if (!I.vm || ed.vmName.empty()) return;
824 auto it = I.vms.find(ed.vmName);
825 if (it == I.vms.end()) return;
826 const char* oneWay[] = {"bind:label", "bind:visible", "bind:enabled"};
827 for (const char* key : oneWay) {
828 const std::string bind = strOf(w, key);
829 if (bind.empty()) continue;
830 const Var v = readVMVar(*I.vm, it->second, bind);
831 if (v.isEmpty()) continue;
832 const std::string k(key);
833 if (k == "bind:label") w->set("label", varString(v));
834 else if (k == "bind:visible") w->set("visible", varBool(v, true));
835 else if (k == "bind:enabled") w->set("enabled", varBool(v, true));
836 }
837 const std::string optBind = strOf(w, "bind:options");
838 if (!optBind.empty()) {
839 const Var v = readVMVar(*I.vm, it->second, optBind);
840 if (!v.isEmpty()) {
841 Array::Ptr opts = new Array();
842 for (const auto& s : varStrings(v)) opts->add(s);
843 w->set("options", opts);
844 }
845 }
846}
847
848void syncVMToView(EditorHost::Impl& I, Editor& ed) {
849 if (!I.vm || ed.vmName.empty()) return;
850 auto it = I.vms.find(ed.vmName);
851 if (it == I.vms.end()) return;
852 forEachWidget(ed.view, [&](Object::Ptr w) {
853 const std::string bind = strOf(w, "bind");
854 const std::string id = strOf(w, "id");
855 if (bind.empty() || id.empty()) return;
856 const Var v = readVMVar(*I.vm, it->second, bind);
857 if (v.isEmpty()) return;
858 auto cur = ed.values.find(id);
859 if (cur == ed.values.end() || jsonStringify(cur->second) != jsonStringify(v))
860 ed.values[id] = v;
861 });
862}
863
864void renderWidget(EditorHost::Impl& I, Editor& ed, Object::Ptr w);
865
866void renderChildren(EditorHost::Impl& I, Editor& ed, Array::Ptr kids, const std::string& layout) {
867 if (!kids) return;
868 for (size_t i = 0; i < kids->size(); ++i) {
869 Object::Ptr w = kids->getObject(static_cast<unsigned>(i));
870 if (!w) continue;
871 resolveOneWay(I, ed, w);
872 renderWidget(I, ed, w);
873 if (layout == "horizontal" && i + 1 < kids->size()) ImGui::SameLine();
874 }
875}
876
877void renderWidget(EditorHost::Impl& I, Editor& ed, Object::Ptr w) {
878 if (!w) return;
879 if (!boolOf(w, "visible", true)) return;
880 const std::string type = strOf(w, "type", "label");
881 const std::string id = strOf(w, "id");
882 const std::string label = strOf(w, "label");
883 const bool enabled = boolOf(w, "enabled", true);
884 if (!enabled) {
885 ImGui::PushStyleVar(ImGuiStyleVar_Alpha, ImGui::GetStyle().Alpha * 0.5f);
886 ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true);
887 }
888
889 const auto cur = [&](const char* key, const Var& def) -> Var {
890 if (!id.empty()) {
891 auto it = ed.values.find(id);
892 if (it != ed.values.end()) return it->second;
893 }
894 if (w->has(key)) return w->get(key);
895 return def;
896 };
897
898 if (type == "label" || type == "text") {
899 const std::string text = strOf(w, "text", label);
900 if (type == "text") ImGui::TextWrapped("%s", text.c_str());
901 else ImGui::TextUnformatted(text.c_str());
902 recordRect(ed, id);
903 } else if (type == "separator") {
904 ImGui::Separator();
905 } else if (type == "spacer") {
906 ImGui::Dummy(ImVec2(floatOf(w, "width", 0.f), floatOf(w, "height", 8.f)));
907 } else if (type == "progress") {
908 float v = std::clamp(varFloat(cur("value", 0.0), 0.f), 0.f, 1.f);
909 const float pw = floatOf(w, "width", 0.f);
910 ImGui::ProgressBar(v, ImVec2(pw > 0.f ? pw : -FLT_MIN, 0.f),
911 label.empty() ? nullptr : label.c_str());
912 recordRect(ed, id);
913 } else if (type == "plot") {
914 const std::vector<float> data = varFloats(cur("data", Var()));
915 if (!data.empty()) {
916 ImGui::PlotLines(widgetIdLabel(w).c_str(), data.data(), static_cast<int>(data.size()), 0,
917 nullptr, floatOf(w, "min", 0.f), floatOf(w, "max", 1.f),
918 ImVec2(floatOf(w, "width", 0.f), floatOf(w, "height", 80.f)));
919 recordRect(ed, id);
920 }
921 } else if (type == "input") {
922 std::string buf = varString(cur("value", strOf(w, "value")));
923 const bool multi = boolOf(w, "multiline", false);
924 const bool changed = controls::inputText(widgetIdLabel(w).c_str(), buf, multi,
925 ImVec2(floatOf(w, "width", 0.f), floatOf(w, "height", 96.f)),
926 boolOf(w, "readOnly", false),
927 strOf(w, "placeholder").c_str()) == controls::ControlEdit::Changed;
928 if (enabled && changed && !id.empty()) {
929 setWidgetValue(I, ed, id, Var(buf));
930 }
931 recordRect(ed, id);
932 } else if (type == "slider" || type == "slider2" || type == "slider3") {
933 const int n = type == "slider" ? 1 : (type == "slider2" ? 2 : 3);
934 float v[3] = {0.f, 0.f, 0.f};
935 const std::vector<float> init = widgetFloatInit(cur("value", Var()));
936 for (int i = 0; i < n; ++i) v[i] = i < static_cast<int>(init.size()) ? init[i] : 0.f;
937 const float lo = floatOf(w, "min", 0.f), hi = floatOf(w, "max", 1.f);
938 const std::string fmt = strOf(w, "format", "%.2f");
939 bool changed = false;
940 if (n == 1)
941 changed = controls::slider(widgetIdLabel(w).c_str(), v[0], lo, hi, fmt.c_str()) ==
943 else if (n == 2) changed = ImGui::SliderFloat2(widgetIdLabel(w).c_str(), v, lo, hi, fmt.c_str());
944 else changed = ImGui::SliderFloat3(widgetIdLabel(w).c_str(), v, lo, hi, fmt.c_str());
945 if (enabled && changed && !id.empty()) {
946 Array::Ptr arr = new Array();
947 for (int i = 0; i < n; ++i) arr->add(static_cast<double>(v[i]));
948 setWidgetValue(I, ed, id, Var(arr));
949 }
950 recordRect(ed, id);
951 } else if (type == "color") {
952 const bool alpha = boolOf(w, "alpha", false);
953 const std::vector<float> init = varFloats(cur("value", Var()));
954 float c[4] = {1.f, 1.f, 1.f, 1.f};
955 for (size_t i = 0; i < std::min<size_t>(init.size(), 4); ++i) c[i] = init[i];
956 const bool changed = alpha ? ImGui::ColorEdit4(widgetIdLabel(w).c_str(), c)
957 : ImGui::ColorEdit3(widgetIdLabel(w).c_str(), c);
958 if (enabled && changed && !id.empty()) {
959 Array::Ptr arr = new Array();
960 const int n = alpha ? 4 : 3;
961 for (int i = 0; i < n; ++i) arr->add(static_cast<double>(c[i]));
962 setWidgetValue(I, ed, id, Var(arr));
963 }
964 recordRect(ed, id);
965 } else if (type == "checkbox") {
966 bool b = varBool(cur("value", false), boolOf(w, "value", false));
967 if (enabled &&
968 controls::checkbox(widgetIdLabel(w).c_str(), b) == controls::ControlEdit::Changed &&
969 !id.empty())
970 setWidgetValue(I, ed, id, Var(b));
971 recordRect(ed, id);
972 } else if (type == "dropdown" || type == "listbox") {
973 const std::vector<std::string> opts = varStrings(cur("options", Var()));
974 std::vector<const char*> items;
975 items.reserve(opts.size());
976 for (const auto& s : opts) items.push_back(s.c_str());
977 std::string sel = varString(cur("value", strOf(w, "value")));
978 int idx = 0;
979 for (size_t i = 0; i < opts.size(); ++i)
980 if (opts[i] == sel) idx = static_cast<int>(i);
981 bool changed = false;
982 if (type == "dropdown")
983 changed = controls::combo(widgetIdLabel(w).c_str(), idx, items) ==
985 else
986 changed = !opts.empty() && ImGui::ListBox(widgetIdLabel(w).c_str(), &idx, items.data(),
987 static_cast<int>(items.size()),
988 intOf(w, "heightItems", -1));
989 if (enabled && changed && !id.empty() && idx >= 0 && idx < static_cast<int>(opts.size()))
990 setWidgetValue(I, ed, id, Var(opts[static_cast<size_t>(idx)]));
991 recordRect(ed, id);
992 } else if (type == "link") {
993 if (controls::textLink(widgetIdLabel(w).c_str()) == controls::ControlEdit::Changed && enabled)
994 emitEvent(ed, "click", id, Var(strOf(w, "target")));
995 recordRect(ed, id);
996 } else if (type == "button") {
997 if (enabled &&
998 controls::button(widgetIdLabel(w).c_str(), floatOf(w, "width", 0.f)) ==
1000 emitEvent(ed, "click", id, Var());
1001 const std::string cmd = strOf(w, "command", strOf(w, "action"));
1002 if (!cmd.empty() && !ed.vmName.empty() && I.vm) {
1003 auto it = I.vms.find(ed.vmName);
1004 if (it != I.vms.end()) {
1005 std::string err;
1006 callTableFunc(I.vm->getHandle(), it->second, vmFuncName(cmd),
1007 {Var(ed.id), Var(id)}, &err);
1008 if (!err.empty())
1009 fprintf(stderr, "eve.host: command %s: %s\n", cmd.c_str(), err.c_str());
1010 }
1011 }
1012 }
1013 recordRect(ed, id);
1014 } else if (type == "tree") {
1015 const bool open = boolOf(w, "open", true);
1016 if (ImGui::TreeNodeEx(widgetIdLabel(w).c_str(),
1017 open ? ImGuiTreeNodeFlags_DefaultOpen : 0)) {
1018 renderChildren(I, ed,
1019 w->has("children") ? w->getArray("children") : nullptr, ed.layout);
1020 ImGui::TreePop();
1021 }
1022 recordRect(ed, id);
1023 } else if (type == "group") {
1024 const bool border = boolOf(w, "border", true);
1025 if (border) {
1026 if (ImGui::BeginChild(widgetIdLabel(w).c_str(),
1027 ImVec2(floatOf(w, "width", 0.f), floatOf(w, "height", 0.f)), true)) {
1028 if (!label.empty()) ImGui::TextUnformatted(label.c_str());
1029 renderChildren(I, ed,
1030 w->has("children") ? w->getArray("children") : nullptr,
1031 strOf(w, "layout", "vertical"));
1032 }
1033 ImGui::EndChild();
1034 } else {
1035 ImGui::BeginGroup();
1036 if (!label.empty()) ImGui::TextUnformatted(label.c_str());
1037 renderChildren(I, ed,
1038 w->has("children") ? w->getArray("children") : nullptr,
1039 strOf(w, "layout", "vertical"));
1040 ImGui::EndGroup();
1041 }
1042 recordRect(ed, id);
1043 } else if (type == "tabs") {
1044 Array::Ptr tabs = w->has("children") ? w->getArray("children") : nullptr;
1045 if (tabs && ImGui::BeginTabBar((id.empty() ? "tabs" : id).c_str())) {
1046 for (size_t i = 0; i < tabs->size(); ++i) {
1047 Object::Ptr tab = tabs->getObject(static_cast<unsigned>(i));
1048 if (!tab) continue;
1049 if (ImGui::BeginTabItem(strOf(tab, "label", "Tab").c_str())) {
1050 renderChildren(I, ed,
1051 tab->has("children") ? tab->getArray("children") : nullptr,
1052 strOf(tab, "layout", "vertical"));
1053 ImGui::EndTabItem();
1054 }
1055 }
1056 ImGui::EndTabBar();
1057 }
1058 } else if (type == "tab") {
1059 renderChildren(I, ed, w->has("children") ? w->getArray("children") : nullptr,
1060 strOf(w, "layout", "vertical"));
1061 } else if (type == "table") {
1062 const std::vector<std::string> cols =
1063 w->has("columns") ? varStrings(w->get("columns")) : std::vector<std::string>();
1064 Array::Ptr rows = w->has("rows") ? w->getArray("rows") : nullptr;
1065 if (!cols.empty() && ImGui::BeginTable((id.empty() ? "table" : id).c_str(),
1066 static_cast<int>(cols.size()),
1067 ImGuiTableFlags_Borders | ImGuiTableFlags_RowBg)) {
1068 for (const auto& c : cols) ImGui::TableSetupColumn(c.c_str());
1069 ImGui::TableHeadersRow();
1070 if (rows) {
1071 for (size_t r = 0; r < rows->size(); ++r) {
1072 ImGui::TableNextRow();
1073 Array::Ptr cells = rows->getArray(static_cast<unsigned>(r));
1074 if (!cells) continue;
1075 for (size_t c = 0; c < cells->size(); ++c) {
1076 ImGui::TableSetColumnIndex(static_cast<int>(c));
1077 ImGui::TextUnformatted(
1078 varString(cells->get(static_cast<unsigned int>(c))).c_str());
1079 }
1080 }
1081 }
1082 ImGui::EndTable();
1083 }
1084 recordRect(ed, id);
1085 } else if (type == "viewport") {
1086 const float vw = floatOf(w, "width", 0.f);
1087 const float vh = floatOf(w, "height", 120.f);
1088 const std::vector<float> bg =
1089 w->has("bg") ? varFloats(w->get("bg")) : std::vector<float>();
1090 const ImVec2 pos = ImGui::GetCursorScreenPos();
1091 ImVec2 size(vw > 0.f ? vw : ImGui::GetContentRegionAvail().x, vh);
1092 ImU32 col = IM_COL32(10, 12, 16, 255);
1093 if (bg.size() >= 3)
1094 col = IM_COL32(static_cast<int>(bg[0] * 255.f), static_cast<int>(bg[1] * 255.f),
1095 static_cast<int>(bg[2] * 255.f), 255);
1096 ImGui::GetWindowDrawList()->AddRectFilled(pos, ImVec2(pos.x + size.x, pos.y + size.y), col);
1097 if (ImGui::BeginChild(widgetIdLabel(w).c_str(), size, true)) {
1098 if (!label.empty()) ImGui::TextUnformatted(label.c_str());
1099 // AI scripts draw inside here using eve.host.widgetRect().
1100 }
1101 ImGui::EndChild();
1102 if (!id.empty()) {
1103 ed.rectMin[id] = ImGui::GetItemRectMin();
1104 ed.rectMax[id] = ImGui::GetItemRectMax();
1105 }
1106 }
1107
1108 const std::string tip =
1109 !enabled && !strOf(w, "disabledReason").empty() ? strOf(w, "disabledReason") : strOf(w, "tooltip");
1110 if (!tip.empty() && (ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) || ImGui::IsItemFocused()))
1111 ImGui::SetTooltip("%s", tip.c_str());
1112 const std::string help = strOf(w, "helpText");
1113 if (!help.empty()) ImGui::TextDisabled("%s", help.c_str());
1114 if (!enabled) {
1115 ImGui::PopItemFlag();
1116 ImGui::PopStyleVar();
1117 }
1118}
1119
1120void renderEditor(EditorHost::Impl& I, Editor& ed) {
1121 if (ed.removed) return;
1122 if (ed.width > 0.f)
1123 ImGui::SetNextWindowSize(ImVec2(ed.width, ed.height), ImGuiCond_FirstUseEver);
1124 if (ed.x != 0.f || ed.y != 0.f)
1125 ImGui::SetNextWindowPos(ImVec2(ed.x, ed.y), ImGuiCond_FirstUseEver);
1126
1127 ImVec4 accent(0.35f, 0.60f, 1.00f, 1.f), bg(0.10f, 0.11f, 0.13f, 1.f);
1128 ImVec4 panel(0.14f, 0.15f, 0.18f, 1.f), text(0.92f, 0.93f, 0.95f, 1.f);
1129 float radius = 4.f, fontScale = 1.f;
1130 if (ed.theme) {
1131 if (ed.theme->has("accent")) {
1132 const auto c = varFloats(ed.theme->get("accent"));
1133 if (c.size() >= 3) accent = ImVec4(c[0], c[1], c[2], 1.f);
1134 }
1135 if (ed.theme->has("bg")) {
1136 const auto c = varFloats(ed.theme->get("bg"));
1137 if (c.size() >= 3) bg = ImVec4(c[0], c[1], c[2], 1.f);
1138 }
1139 if (ed.theme->has("panel")) {
1140 const auto c = varFloats(ed.theme->get("panel"));
1141 if (c.size() >= 3) panel = ImVec4(c[0], c[1], c[2], 1.f);
1142 }
1143 if (ed.theme->has("text")) {
1144 const auto c = varFloats(ed.theme->get("text"));
1145 if (c.size() >= 3) text = ImVec4(c[0], c[1], c[2], 1.f);
1146 }
1147 radius = floatOf(ed.theme, "radius", 4.f);
1148 fontScale = floatOf(ed.theme, "fontScale", 1.f);
1149 if (strOf(ed.theme, "preset") == "light") {
1150 bg = ImVec4(0.93f, 0.93f, 0.93f, 1.f);
1151 panel = ImVec4(0.84f, 0.84f, 0.86f, 1.f);
1152 text = ImVec4(0.10f, 0.10f, 0.12f, 1.f);
1153 }
1154 }
1155
1156 ImGui::PushStyleColor(ImGuiCol_WindowBg, bg);
1157 ImGui::PushStyleColor(ImGuiCol_ChildBg, panel);
1158 ImGui::PushStyleColor(ImGuiCol_Text, text);
1159 ImGui::PushStyleColor(ImGuiCol_Button, accent);
1160 ImGui::PushStyleColor(ImGuiCol_ButtonHovered,
1161 ImVec4(accent.x + 0.08f, accent.y + 0.08f, accent.z + 0.08f, 1.f));
1162 ImGui::PushStyleColor(ImGuiCol_ButtonActive,
1163 ImVec4(accent.x - 0.05f, accent.y - 0.05f, accent.z - 0.05f, 1.f));
1164 ImGui::PushStyleColor(ImGuiCol_Header, accent);
1165 ImGui::PushStyleColor(ImGuiCol_SliderGrab, accent);
1166 ImGui::PushStyleColor(ImGuiCol_CheckMark, accent);
1167 ImGui::PushStyleVar(ImGuiStyleVar_FrameRounding, radius);
1168 ImGui::PushStyleVar(ImGuiStyleVar_GrabRounding, radius);
1169 ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, radius);
1170
1171 bool open = true;
1172 ImGuiWindowFlags flags = ImGuiWindowFlags_NoSavedSettings;
1173 if (!ed.resizable) flags |= ImGuiWindowFlags_NoResize;
1174 if (!ed.collapsible) flags |= ImGuiWindowFlags_NoCollapse;
1175 if (ImGui::Begin((ed.title + "##" + ed.id).c_str(), &open, flags)) {
1176 if (fontScale != 1.f) ImGui::SetWindowFontScale(fontScale);
1177 renderChildren(I, ed,
1178 (ed.view && ed.view->has("children")) ? ed.view->getArray("children")
1179 : nullptr,
1180 ed.layout);
1181 }
1182 if (!open) {
1183 emitEvent(ed, "closed", "", Var());
1184 ed.removed = true;
1185 }
1186 ImGui::End();
1187 if (fontScale != 1.f) ImGui::SetWindowFontScale(1.f);
1188 ImGui::PopStyleVar(3);
1189 ImGui::PopStyleColor(9);
1190}
1191
1192} // namespace
1193
1195 if (!impl_ || !impl_->windowOpen || !impl_->ui) return;
1196 auto& I = *impl_;
1197 for (auto& [id, ed] : I.editors) {
1198 syncVMToView(I, ed);
1199 renderEditor(I, ed);
1200 }
1201 for (auto it = I.editors.begin(); it != I.editors.end();) {
1202 if (it->second.removed) it = I.editors.erase(it);
1203 else ++it;
1204 }
1205}
1206
1208 if (!impl_ || !impl_->windowOpen || !impl_->vm) return;
1209 auto& I = *impl_;
1210 I.inFrame = true;
1211 if (!I.event) I.event = ModuleManager::requireInstance<eve::platform_event::PlatformEvent>("PlatformEvent");
1212 if (!I.timer) I.timer = ModuleManager::requireInstance<eve::timer::Timer>("Timer");
1213 if (!I.gfx) {
1214 I.inFrame = false;
1215 return;
1216 }
1217
1218 I.event->pump();
1219 while (auto m = I.event->pollOwned()) {
1220 const std::string name = m->name;
1221 if (name == "quit") {
1222 closeWindow();
1223 requestExit();
1224 I.inFrame = false;
1225 return;
1226 }
1227 }
1228
1229 const float dt = I.timer ? I.timer->step() : 0.f;
1230 callRootFunc(I.vm->getHandle(), "eve_host_update", {Var(static_cast<double>(dt))});
1231 I.gfx->clearScreen();
1232 callRootFunc(I.vm->getHandle(), "eve_host_render", {});
1233 if (I.ui) {
1234 I.ui->beginFrameAndRender();
1235 renderImGui();
1236 }
1237 I.gfx->present();
1238 if (I.ui) I.ui->dispatchEvents();
1239 I.inFrame = false;
1240}
1241
1242namespace {
1243
1244Var parseEditorValue(const std::string& jsonValue) {
1245 Var v;
1246 try {
1247 Poco::JSON::Parser p;
1248 v = p.parse(jsonValue);
1249 } catch (...) {
1250 // Poco's parser wants a top-level JSON value; some clients pass bare
1251 // numbers/booleans without JSON quoting. Handle those explicitly.
1252 if (jsonValue == "true")
1253 v = Var(true);
1254 else if (jsonValue == "false")
1255 v = Var(false);
1256 else if (jsonValue == "null")
1257 v = Var();
1258 else {
1259 char* end = nullptr;
1260 const double d = std::strtod(jsonValue.c_str(), &end);
1261 if (end && end != jsonValue.c_str() && *end == '\0')
1262 v = Var(d);
1263 else
1264 v = Var(jsonValue); // plain text
1265 }
1266 }
1267 return v;
1268}
1269
1270} // namespace
1271
1272std::string EditorHost::setEditorValue(const std::string& editorId, const std::string& widgetId,
1273 const std::string& jsonValue) {
1274 if (!impl_) return "error: host not started";
1275 auto it = impl_->editors.find(editorId);
1276 if (it == impl_->editors.end()) return "error: editor not found: " + editorId;
1277 if (widgetId.empty()) return "error: missing widget";
1278 const Var v = parseEditorValue(jsonValue);
1279 setWidgetValue(*impl_, it->second, widgetId, v);
1280 return "ok";
1281}
1282
1283std::string EditorHost::restoreEditorValue(const std::string& editorId, const std::string& widgetId,
1284 const std::string& jsonValue) {
1285 if (!impl_ || !impl_->vm) return "error: host not started";
1286 auto it = impl_->editors.find(editorId);
1287 if (it == impl_->editors.end()) return "error: editor not found: " + editorId;
1288 if (widgetId.empty()) return "error: missing widget";
1289 const Var v = parseEditorValue(jsonValue);
1290 it->second.values[widgetId] = v;
1291 auto vmIt = impl_->vms.find(it->second.vmName);
1292 const auto widget = findWidget(it->second.view, widgetId);
1293 if (vmIt != impl_->vms.end() && widget) {
1294 const std::string bind = strOf(widget, "bind");
1295 if (!bind.empty()) writeVMVar(*impl_->vm, vmIt->second, bind, v);
1296 }
1297 return "ok";
1298}
1299
1300std::string EditorHost::consumeEvents(const std::string& editorId) {
1301 if (!impl_) return "[]";
1302 Array::Ptr arr = new Array();
1303 auto drain = [&](Editor& ed) {
1304 for (const auto& e : ed.events) {
1305 Object::Ptr eo = new Object();
1306 eo->set("editor", ed.id);
1307 eo->set("widget", e.widget);
1308 eo->set("type", e.type);
1309 if (!e.value.isEmpty()) eo->set("value", e.value);
1310 arr->add(eo);
1311 }
1312 ed.events.clear();
1313 };
1314 if (!editorId.empty()) {
1315 auto it = impl_->editors.find(editorId);
1316 if (it == impl_->editors.end()) return "error: editor not found: " + editorId;
1317 drain(it->second);
1318 } else {
1319 for (auto& [k, ed] : impl_->editors) drain(ed);
1320 }
1321 return jsonStringify(Var(arr));
1322}
1323
1324std::string EditorHost::widgetRect(const std::string& editorId, const std::string& widgetId) const {
1325 if (!impl_) return "{\"x\":0,\"y\":0,\"width\":0,\"height\":0}";
1326 auto it = impl_->editors.find(editorId);
1327 if (it == impl_->editors.end()) return "{\"x\":0,\"y\":0,\"width\":0,\"height\":0}";
1328 const Editor& ed = it->second;
1329 auto mn = ed.rectMin.find(widgetId), mx = ed.rectMax.find(widgetId);
1330 Object::Ptr o = new Object();
1331 if (mn != ed.rectMin.end() && mx != ed.rectMax.end()) {
1332 o->set("x", static_cast<double>(mn->second.x));
1333 o->set("y", static_cast<double>(mn->second.y));
1334 o->set("width", static_cast<double>(mx->second.x - mn->second.x));
1335 o->set("height", static_cast<double>(mx->second.y - mn->second.y));
1336 } else {
1337 o->set("x", 0);
1338 o->set("y", 0);
1339 o->set("width", 0);
1340 o->set("height", 0);
1341 }
1342 return jsonStringify(Var(o));
1343}
1344
1345std::string EditorHost::registerVM(const std::string& name, const std::string& source,
1346 const std::string& sourceName) {
1347 if (!impl_ || !impl_->vm) return "error: host not started";
1348 if (name.empty()) return "error: missing name";
1349 const std::string uri = sourceName.empty() ? std::string("host_vm.nut") : sourceName;
1350 const std::string err = runSquirrel(impl_->vm->getHandle(), source, uri.c_str());
1351 if (!err.empty()) return "error: " + err;
1352 try {
1353 ssq::Table tbl = impl_->vm->find(name.c_str()).toTable();
1354 impl_->vms[name] = tbl;
1355 impl_->vmSources[name] = source;
1356 return "ok";
1357 } catch (const std::exception& e) {
1358 return std::string("error: table '") + name + "' not found after run: " + e.what();
1359 }
1360}
1361
1362std::string EditorHost::unregisterVM(const std::string& name) {
1363 if (!impl_) return "error: host not started";
1364 if (name.empty()) return "error: missing name";
1365 impl_->vms.erase(name);
1366 impl_->vmSources.erase(name);
1367 if (impl_->vm) {
1368 HSQUIRRELVM v = impl_->vm->getHandle();
1369 const SQInteger top = sq_gettop(v);
1370 sq_pushroottable(v);
1371 sq_pushstring(v, name.c_str(), static_cast<SQInteger>(name.size()));
1372 sq_deleteslot(v, -2, SQFalse);
1373 sq_pop(v, 1);
1374 sq_settop(v, top);
1375 }
1376 return "ok";
1377}
1378
1379std::string EditorHost::saveEditor(const std::string& id) {
1380 if (!impl_) return "error: host not started";
1381 auto it = impl_->editors.find(id);
1382 if (it == impl_->editors.end()) return "error: editor not found: " + id;
1383 try {
1384 std::error_code ec;
1385 std::filesystem::path dir = std::filesystem::path(impl_->rootDir) / "editors";
1386 std::filesystem::create_directories(dir, ec);
1387 std::filesystem::path vp = dir / (id + ".editor.json");
1388 {
1389 std::ofstream ofs(vp, std::ios::trunc);
1390 if (!ofs) return "error: cannot write " + vp.string();
1391 ofs << jsonStringify(Var(it->second.view));
1392 }
1393 if (!it->second.vmName.empty()) {
1394 auto vs = impl_->vmSources.find(it->second.vmName);
1395 if (vs != impl_->vmSources.end()) {
1396 std::filesystem::path sp = dir / (id + ".vm.nut");
1397 std::ofstream ofs2(sp, std::ios::trunc);
1398 if (!ofs2) return "error: cannot write " + sp.string();
1399 ofs2 << vs->second;
1400 }
1401 }
1402 return "ok";
1403 } catch (const std::exception& e) {
1404 return std::string("error: ") + e.what();
1405 }
1406}
1407
1408std::string EditorHost::unloadEditor(const std::string& id) {
1409 if (!impl_) return "error: host not started";
1410 auto it = impl_->editors.find(id);
1411 if (it == impl_->editors.end()) return "error: editor not found: " + id;
1412 impl_->editors.erase(it);
1413 return "ok";
1414}
1415
1417 if (!impl_) return;
1418 std::error_code ec;
1419 std::filesystem::path dir = std::filesystem::path(impl_->rootDir) / "editors";
1420 if (!std::filesystem::is_directory(dir, ec)) return;
1421 std::vector<std::pair<std::string, std::string>> pending;
1422 for (auto& entry : std::filesystem::directory_iterator(dir, ec)) {
1423 if (ec) break;
1424 const std::filesystem::path& p = entry.path();
1425 const std::string name = p.filename().string();
1426 const std::string suffix = ".editor.json";
1427 if (p.extension() != ".json" || name.size() <= suffix.size() ||
1428 name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
1429 continue;
1430 const std::string id = name.substr(0, name.size() - suffix.size());
1431 std::ifstream ifs(p);
1432 std::string json((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
1433 if (!json.empty()) pending.emplace_back(id, json);
1434 }
1435 for (const auto& [id, json] : pending) {
1436 // Every outcome is recorded, not just the happy path: a ViewModel that fails to
1437 // load at startup used to be invisible (the result was discarded and the parse
1438 // exception swallowed), so an MCP client asking hotReloadStatus() saw a healthy
1439 // host while the editor had no working script behind it.
1440 const std::string resource = "editors/" + id + ".editor.json";
1441 std::string result;
1442 try {
1443 Object::Ptr root = parseObject(json);
1444 const std::string vmName = strOf(root, "vm");
1445 if (!vmName.empty()) {
1446 std::ifstream ifs2(dir / (id + ".vm.nut"));
1447 std::string src((std::istreambuf_iterator<char>(ifs2)),
1448 std::istreambuf_iterator<char>());
1449 if (!src.empty()) result = registerVM(vmName, src, "game:/editors/" + id + ".vm.nut");
1450 }
1451 } catch (const std::exception& e) {
1452 result = std::string("error: ") + e.what();
1453 } catch (...) {
1454 result = "error: editor manifest load failed";
1455 }
1456 if (result.rfind("error:", 0) == 0) recordHostResourceOutcome(resource, result);
1457
1458 const std::string applied = applyEditor(json);
1459 if (applied.rfind("error:", 0) == 0) recordHostResourceOutcome(resource, applied);
1460 }
1461}
1462
1463std::string EditorHost::runScript(const std::string& source, const std::string& sourceName) {
1464 if (!impl_ || !impl_->vm) return "error: host not started";
1465 if (source.empty()) return "error: missing source";
1466 const std::string uri = sourceName.empty() ? std::string("host_snippet.nut") : sourceName;
1467 const std::string err = runSquirrel(impl_->vm->getHandle(), source, uri.c_str());
1468 return err.empty() ? "ok" : ("error: " + err);
1469}
1470
1471std::string EditorHost::capture(const std::string& path) {
1472 if (!impl_ || !impl_->gfx) return "error: no window";
1473 auto& I = *impl_;
1474 try {
1475 std::string p = path.empty() ? "eve_host_capture.png" : path;
1476 I.gfx->setScreenReadbackEnabled(true);
1477 eve::image::ImageData* img = nullptr;
1478 try {
1479 img = I.gfx->newImageData();
1480 } catch (...) {
1481 // No presented frame yet (e.g. capture right after the window was
1482 // opened). Render one frame with readback enabled, then retry.
1483 if (I.inFrame) throw; // cannot present reentrantly from a script hook
1484 frame();
1485 img = I.gfx->newImageData();
1486 }
1487 if (!img) return "error: readback returned no image";
1488 const int w = I.gfx->getPixelWidth();
1489 const int h = I.gfx->getPixelHeight();
1491 img->encode(eve::image::ImageData::FormatHandler::ENCODED_PNG, p.c_str(), false);
1492 delete img;
1493 if (!png) return "error: PNG encode failed";
1494 std::error_code ec;
1495 std::filesystem::create_directories(std::filesystem::path(p).parent_path(), ec);
1496 std::ofstream out(p, std::ios::binary | std::ios::trunc);
1497 if (!out.good()) {
1498 delete png;
1499 return "error: cannot write " + p;
1500 }
1501 out.write(static_cast<const char*>(png->getData()),
1502 static_cast<std::streamsize>(png->getSize()));
1503 out.close();
1504 const bool wrote = out.good();
1505 delete png;
1506 if (!wrote) return "error: failed writing " + p;
1507 Object::Ptr o = new Object();
1508 o->set("path", p);
1509 o->set("width", w);
1510 o->set("height", h);
1511 return jsonStringify(Var(o));
1512 } catch (const std::exception& e) {
1513 return std::string("error: ") + e.what();
1514 }
1515}
1516
1517std::string EditorHost::status() const {
1518 if (!impl_) return "{\"running\":false,\"windowOpen\":false,\"editors\":[],\"viewModels\":[]}";
1519 Object::Ptr o = new Object();
1520 o->set("running", running_);
1521 o->set("windowOpen", impl_->windowOpen);
1522 o->set("windowTitle", impl_->windowTitle);
1523 o->set("gameRoot", gameRoot_);
1524 Array::Ptr eds = new Array();
1525 for (const auto& [k, ed] : impl_->editors) {
1526 Object::Ptr e = new Object();
1527 e->set("id", k);
1528 e->set("title", ed.title);
1529 eds->add(e);
1530 }
1531 o->set("editors", eds);
1532 Array::Ptr vms = new Array();
1533 for (const auto& [k, v] : impl_->vms) vms->add(k);
1534 o->set("viewModels", vms);
1535 return jsonStringify(Var(o));
1536}
1537
1539 try {
1540 ssq::Table eveTbl = vm.find("eve").toTable();
1541 ssq::Table host = eveTbl.addTable("host");
1542 host.addFunc("status", []() { return EditorHost::instance().status(); });
1543 host.addFunc("openWindow", [](std::string t, int w, int h) {
1544 return EditorHost::instance().openWindow(t, w, h);
1545 });
1546 host.addFunc("closeWindow", []() { return EditorHost::instance().closeWindow(); });
1547 host.addFunc("windowState", []() { return EditorHost::instance().windowState(); });
1548 host.addFunc("applyEditor", [](std::string json) {
1549 return EditorHost::instance().applyEditor(json);
1550 });
1551 host.addFunc("removeEditor", [](std::string id) {
1553 });
1554 host.addFunc("setValue", [](std::string editor, std::string widget, std::string value) {
1556 });
1557 host.addFunc("events", [](std::string editor) {
1558 return EditorHost::instance().consumeEvents(editor);
1559 });
1560 host.addFunc("registerVM", [](std::string name, std::string source, std::string uri) {
1562 });
1563 host.addFunc("unregisterVM", [](std::string name) {
1565 });
1566 host.addFunc("widgetRect", [](std::string editor, std::string widget) {
1567 return EditorHost::instance().widgetRect(editor, widget);
1568 });
1569 host.addFunc("capture", [](std::string path) {
1571 });
1572 host.addFunc("save", [](std::string id) {
1573 return EditorHost::instance().saveEditor(id);
1574 });
1575 host.addFunc("runScript", [](std::string source, std::string uri) {
1577 });
1578 host.addFunc("reloadResource", [](std::string path) {
1580 });
1581 host.addFunc("hotReloadStatus", []() {
1583 });
1584 } catch (...) {
1585 // eve table missing — the host surface is optional.
1586 }
1587}
1588
1589} // namespace eve::ui
1590
1591#endif // EVENGINE_WEBGPU && __EMSCRIPTEN__
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
int tip
Definition AnimSmr.cpp:121
int root
Definition AnimSmr.cpp:119
std::vector< QuestEvent > pending
const std::string & s
struct SQVM * HSQUIRRELVM
std::string title
bool changed
bool applied
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
int rows
int cols
std::string layout
glm::vec3 n
Definition Grass.cpp:63
double r
bool border
float v
std::int32_t c
int h
std::uint32_t height
std::uint32_t width
const ColourScope * parent
std::string label
std::string id
Poco::JSON::Object::Ptr result
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
double radius
Definition MeleeHit.cpp:42
MeleePoint3 a
Definition MeleeHit.cpp:40
double dt
OceanSprayView view
std::string error
Definition Package.cpp:174
std::vector< particles::ParticleRecordEvent > events
int idx
float f
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::string path
Definition PlayHost.cpp:111
std::string uri
std::set< std::string > values
Object::Ptr value
float d
int detail
float t
std::string slot
int removed
std::string text
ScriptStructure out
std::string_view source
size_t end
std::string resource
std::string string
The single Squirrel projection for common Result, Status and Value.
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
UIHostHandle host
uint32_t index
const VegetationPresetContext & context
uint32_t flags
static Runtime * runtime()
Active runtime associated with the last expose() call, or nullptr. @ownership Borrowed; the embedding...
Data buffer paired with a filename (used for type identification).
Definition FileData.h:14
size_t getSize() const
Byte length of the owned buffer.
Definition FileData.h:29
void * getData() const
Pointer to the owned byte buffer.
Definition FileData.h:27
Represents raw pixel data.
Definition ImageData.h:38
filesystem::FileData * encode(FormatHandler::EncodedFormat format, const char *filename, bool writefile) const
Encodes raw pixel data into a given format.
EVENGINE_API_FOUNDATION public API.
static SQRESULT compileBuffer(HSQUIRRELVM vm, const SQChar *source, SQInteger size, const SQChar *sourceName, SQBool raiseError)
Unified raw-VM entry used by REPL, debugger, MCP, and editor adapters.
High-resolution frame/elapsed timer backed by SDL_GetPerformanceCounter(). Script: timer <- eve....
Definition Timer.h:20
Headless MCP editor host (MVVM).
Definition EditorHost.h:34
void stop()
Stops .
std::string status() const
Status.
std::string consumeEvents(const std::string &editorId)
Read and clear pending interaction events for one editor ("" = all).
void requestExit()
Request exit.
Definition EditorHost.h:122
std::string closeWindow()
Closes window.
std::string listEditors() const
List editors.
std::string unregisterVM(const std::string &name)
Unregisters vm.
EditorHost(const EditorHost &)=delete
void syncBindings()
Pull bound ViewModel values into widget state (per-frame + on read).
void renderImGui()
Draw editor ImGui windows; call between beginFrameAndRender/present.
bool isWindowOpen() const
True when window open.
void loadEditorsFromDisk()
Load editors/<id>.editor.json (+ matching .vm.nut) on host startup.
std::string setEditorValue(const std::string &editorId, const std::string &widgetId, const std::string &jsonValue)
Sets the editor value.
std::string capture(const std::string &path)
Capture.
std::string applyEditor(const std::string &json)
JSON object/string: {id,title,vm,x,y,width,height,theme,children[]}.
std::string unloadEditor(const std::string &id)
Remove an editor from the session (files stay on disk).
std::string windowState() const
Window state.
const std::string & gameRoot() const
Game root.
Definition EditorHost.h:53
std::string editorState(const std::string &id) const
Full state JSON: editors + values + (non-destructive) events.
void frame()
Pump events + update/render hooks + present (no-op without window).
std::string removeEditor(const std::string &id)
Removes editor.
std::string hotReloadStatus() const
Watch count, reload counters and latest diagnostic as compact JSON.
static EditorHost & instance()
Instance.
std::string openWindow(const std::string &title, int width, int height)
Opens window.
std::string registerVM(const std::string &name, const std::string &source, const std::string &sourceName={})
Compile Squirrel source in the host VM, then register table name.
std::string widgetRect(const std::string &editorId, const std::string &widgetId) const
Last-frame widget rect JSON (for script drawing inside viewports).
std::string reloadResource(const std::string &path)
Reload mcp.nut, scripts under mcp, or editor VM and manifest files.
std::string restoreEditorValue(const std::string &editorId, const std::string &widgetId, const std::string &jsonValue)
Restore a widget and its binding without emitting events or onChange.
std::string saveEditor(const std::string &id)
Write editors/<id>.editor.json + editors/<id>.vm.nut under gameRoot.
~EditorHost()
Editor host.
void start(ssq::VM &vm, const std::string &gameRoot={}, bool allowWindow=true)
Attach to the host VM. gameRoot is the project dir for editors/.
void exposeScriptApi(ssq::VM &vm)
Expose eve.host table (registerVM/unregisterVM/widgetRect/...).
std::string runScript(const std::string &source, const std::string &sourceName={})
Compile and run Squirrel source in the host VM.
Declarative UI module (eve.UI).
Definition UI.h:41
Platform window interface (SDL implementation on desktop/mobile). Script: win <- eve....
Definition Window.h:47
SQInteger top
Definition Snapshot.cpp:115
ForceVector add(ForceVector a, ForceVector b)
Definition ForceMath.h:13
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
Vec3 sub(Vec3 a, Vec3 b)
std::string formatScriptError(const ScriptErrorContext &ctx)
Formats a context into a human-readable multi-line report.
ScriptErrorContext captureCompileError(HSQUIRRELVM vm)
Captures the last compilation error recorded by the VM.
std::string reportScriptCallFailure(HSQUIRRELVM vm, const char *what)
Report a failed engine-to-script call, consuming the VM's script error.
ControlEdit slider(const char *label, float &value, float minimum, float maximum, const char *format="%.3f")
Shared immediate renderer for scalar sliders.
ControlEdit button(const char *label, float width=0.f, float height=0.f)
Shared immediate renderer for retained and EditorHost buttons.
ControlEdit combo(const char *label, int &selected, const std::vector< const char * > &items)
Shared immediate renderer for indexed combo boxes.
ControlEdit inputText(const char *label, std::string &value, bool multiline=false, ImVec2 multilineSize=ImVec2(0.f, 96.f), bool readOnly=false, const char *hint="")
UTF-8 owning text editor with automatic buffer growth.
ControlEdit textLink(const char *label)
Render a keyboard-accessible text link without launching its target.
ControlEdit checkbox(const char *label, bool &value)
Shared immediate renderer for retained and EditorHost checkboxes.
WidgetDesc tab(std::string label, std::string pageId, bool selected, std::string id, std::function< void()> onClick)
Selectable tab label.
Definition Widget.cpp:715
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120
SettlementPipeline::Stage fn
bool enabled
eve::window::Window * win
eve::graphics::Graphics * gfx
std::map< std::string, ssq::Table > vms
std::map< std::string, Editor > editors
eve::timer::Timer * timer
std::map< std::string, std::string > vmSources
Display settings for window creation/resize. width/height == 0 selects the desktop display mode size.
Definition Window.h:18
std::map< std::string, ImVec2 > rectMin
bool collapsible
std::string widget
Object::Ptr theme
std::map< std::string, ImVec2 > rectMax
std::string vmName
bool resizable