10#include <Poco/Exception.h>
11#include <Poco/JSON/Array.h>
12#include <Poco/JSON/Object.h>
13#include <Poco/JSON/Parser.h>
14#include <Poco/JSON/Stringifier.h>
15#include <Poco/Net/HTTPClientSession.h>
16#include <Poco/Net/HTTPRequest.h>
17#include <Poco/Net/HTTPResponse.h>
18#include <Poco/StreamCopier.h>
19#include <Poco/Timespan.h>
23#include <simplesquirrel/simplesquirrel.hpp>
25#if defined(EVENGINE_ANDROID)
26#include "android/android.h"
28#elif defined(EVENGINE_IOS)
39#include <system_error>
46std::string joinDir(
const std::string &
dir,
const std::string &
name) {
48 if (
dir.back() ==
'/' ||
dir.back() ==
'\\')
return dir +
name;
52std::filesystem::path pathFromUtf8(
const std::string &
text) {
53 const auto *data =
reinterpret_cast<const char8_t *
>(
text.data());
54 return std::filesystem::path(std::u8string_view(data,
text.size()));
57std::string pathToUtf8(
const std::filesystem::path &
p) {
58 auto u8 =
p.u8string();
59 return std::string(
reinterpret_cast<const char *
>(u8.data()), u8.size());
62bool looksAbsoluteOs(
const std::string &
path) {
63 if (
path.empty())
return false;
64 if (
path[0] ==
'/' ||
path[0] ==
'\\')
return true;
66 if (
path.size() >= 2 &&
path[1] ==
':')
return true;
71bool hasParentSegment(
const std::string &
path) {
72 if (
path ==
"..")
return true;
73 if (
path.size() >= 3 && (
path.compare(0, 3,
"../") == 0 ||
path.compare(0, 3,
"..\\") == 0))
75 return path.find(
"/..") != std::string::npos ||
path.find(
"\\..") != std::string::npos;
78bool skipWatchDirName(
const std::string &
name) {
79 return name ==
".git" ||
name ==
"build" ||
name ==
"third-party" ||
name ==
"node_modules" ||
80 name ==
".cursor" ||
name ==
".local-debug" ||
name ==
"CMakeFiles";
83std::string posixRelative(
const std::filesystem::path &
dir,
const std::filesystem::path &
root) {
85 auto rel = std::filesystem::relative(
dir,
root, ec);
87 std::string
s = rel.generic_string();
88 if (
s.empty())
return ".";
92bool isPathPrefix(
const std::filesystem::path &prefix,
const std::filesystem::path &full) {
94 auto a = std::filesystem::weakly_canonical(prefix, ec);
95 if (ec)
a = prefix.lexically_normal();
96 auto b = std::filesystem::weakly_canonical(full, ec);
97 if (ec)
b = full.lexically_normal();
98 std::string as =
a.generic_string();
99 std::string bs =
b.generic_string();
100 if (as.size() > bs.size())
return false;
102 for (
char &ch : as) ch = static_cast<char>(
std::tolower(static_cast<unsigned char>(ch)));
103 for (
char &ch : bs) ch = static_cast<char>(
std::tolower(static_cast<unsigned char>(ch)));
105 if (bs.compare(0, as.size(), as) != 0)
return false;
106 return bs.size() == as.size() || bs[as.size()] ==
'/';
109int watchTreeVfs(Filesystem *fs,
const std::string &
root) {
111 std::vector<std::string> stack;
112 stack.push_back(
root ==
"." ? std::string(
".") :
root);
114 while (!stack.empty()) {
115 std::string
dir = stack.back();
117 if (fs->watch(
dir)) ++added;
119 std::vector<std::string> items;
121 if (
dir ==
"." ||
dir.empty())
122 items = fs->getDirectoryItems(
"");
124 items = fs->getDirectoryItems(
dir);
129 for (
const auto &item : items) {
130 if (item.empty() || item ==
"." || item ==
"..")
continue;
131 const std::string
child = (
dir ==
"." ||
dir.empty()) ? item : joinDir(
dir, item);
132 Filesystem::Info
info{};
133 if (!fs->getInfo(child,
info))
continue;
134 if (
info.type ==
"directory") stack.push_back(child);
140int watchTreeOs(Filesystem *fs,
const std::filesystem::path &realRoot) {
142 if (!std::filesystem::is_directory(realRoot, ec))
return 0;
144 const auto cwd = pathFromUtf8(fs->getWorkingDirectory());
145 auto reportFor = [&](
const std::filesystem::path &
dir) -> std::string {
146 std::error_code canonEc;
147 auto d = std::filesystem::weakly_canonical(
dir, canonEc);
148 if (canonEc)
d =
dir;
149 auto c = std::filesystem::weakly_canonical(cwd, canonEc);
150 if (canonEc)
c = cwd;
151 if (isPathPrefix(
c,
d)) {
152 const std::string rel = posixRelative(
d,
c);
153 return rel.empty() ?
"." : rel;
155 const std::string rel = posixRelative(
d, realRoot);
156 return rel.empty() ?
"." : rel;
160 if (fs->watchRealDirectory(pathToUtf8(realRoot), reportFor(realRoot)).
ok()) ++added;
162 auto it = std::filesystem::recursive_directory_iterator(
163 realRoot, std::filesystem::directory_options::skip_permission_denied, ec);
164 const auto end = std::filesystem::recursive_directory_iterator();
165 for (; it !=
end; it.increment(ec)) {
170 std::error_code dirEc;
171 if (!it->is_directory(dirEc))
continue;
172 const auto name = it->path().filename().string();
173 if (
name.empty() ||
name ==
"." ||
name ==
".." || skipWatchDirName(
name)) {
174 it.disable_recursion_pending();
177 const auto &
dir = it->path();
180 if (isPathPrefix(realRoot, cwd)) {
181 const auto appsDir = cwd.parent_path();
182 if (isPathPrefix(appsDir,
dir) && !isPathPrefix(
dir, appsDir) && !isPathPrefix(cwd,
dir)) {
183 it.disable_recursion_pending();
187 const std::string report = reportFor(
dir);
188 if (report.empty() || report.find(
"..") != std::string::npos)
continue;
189 if (fs->watchRealDirectory(pathToUtf8(
dir), report).
ok()) ++added;
194bool resolveOsWatchRoot(Filesystem *fs,
const std::string &
root, std::filesystem::path &
out) {
196 std::filesystem::path candidate;
198 candidate = pathFromUtf8(fs->getWorkingDirectory());
199 }
else if (looksAbsoluteOs(
root)) {
200 candidate = pathFromUtf8(
root);
202 candidate = pathFromUtf8(fs->getWorkingDirectory()) / pathFromUtf8(
root);
204 auto canonical = std::filesystem::weakly_canonical(candidate, ec);
205 if (ec)
return false;
206 if (!std::filesystem::is_directory(canonical, ec))
return false;
207 out = std::move(canonical);
213#ifndef EVENGINE_WEBGPU
214std::string stripTrailingSlash(std::string
s) {
215 while (
s.size() > 1 &&
s.back() ==
'/')
s.pop_back();
220std::string urlPathEscape(
const std::string &
s) {
222 out.reserve(
s.size() + 8);
223 const char hex[] =
"0123456789ABCDEF";
224 for (
unsigned char c :
s) {
225 if (std::isalnum(
c) ||
c ==
'-' ||
c ==
'_' ||
c ==
'.' ||
c ==
'~' ||
c ==
'/') {
226 out +=
static_cast<char>(
c);
237std::string httpGet(
const std::string &url,
int timeoutMs) {
240 Poco::Net::HTTPClientSession
session(
uri.getHost(),
uri.getPort());
241 session.setTimeout(Poco::Timespan(timeoutMs / 1000, (timeoutMs % 1000) * 1000));
242 std::string
path =
uri.getPathAndQuery();
244 Poco::Net::HTTPRequest req(Poco::Net::HTTPRequest::HTTP_GET,
path,
245 Poco::Net::HTTPMessage::HTTP_1_1);
246 req.setHost(
uri.getHost());
247 std::ostream &os =
session.sendRequest(req);
249 Poco::Net::HTTPResponse resp;
250 std::istream &is =
session.receiveResponse(resp);
251 if (resp.getStatus() != Poco::Net::HTTPResponse::HTTP_OK)
return {};
252 std::ostringstream oss;
253 Poco::StreamCopier::copyStream(is, oss);
260bool writeFileBytes(
const std::string &realPath,
const std::string &data) {
262 std::filesystem::path
p(realPath);
263 std::filesystem::create_directories(
p.parent_path(), ec);
264 std::ofstream ofs(realPath, std::ios::binary | std::ios::trunc);
265 if (!ofs)
return false;
266 ofs.write(data.data(),
static_cast<std::streamsize
>(data.size()));
278 for (
char &
c :
path) {
279 if (
c ==
'\\')
c =
'/';
281 while (
path.size() >= 2 &&
path[0] ==
'.' &&
path[1] ==
'/')
path.erase(0, 2);
282 while (
path.size() > 1 &&
path.back() ==
'/')
path.pop_back();
288 if (
path.empty())
return;
299 if (norm.empty())
return false;
301 std::string
kind =
"auto";
302 auto bit = bindings_.find(norm);
303 if (bit != bindings_.end())
kind = bit->second;
310 const bool wanted = (
kind ==
"auto") ?
r->handlesPath(norm) : (
kind ==
r->reloadKind());
319 StartupStage stage(
"hotreload: watchTree (recursive walk + register watches)");
320 auto *fs = Filesystem::create();
326 const bool vfsDir = (
root ==
"." ||
root ==
"./") ||
327 (!looksAbsoluteOs(
root) && !hasParentSegment(
root) && fs->getInfo(
root,
info) &&
328 info.type ==
"directory");
329 if (vfsDir)
return watchTreeVfs(fs,
root);
331 std::filesystem::path realRoot;
332 if (!resolveOsWatchRoot(fs,
root, realRoot))
return 0;
333 return watchTreeOs(fs, realRoot);
337 auto *fs = Filesystem::create();
338 if (!fs)
return false;
340 if (
path.empty())
return false;
343 if (fs->getInfo(
path,
info) &&
info.type ==
"directory") {
347 std::filesystem::path real;
348 if (!resolveOsWatchRoot(fs,
path, real))
return false;
349 watchTreeOs(fs, real);
357#ifndef EVENGINE_WEBGPU
359std::string HotReload::ensureHotDir() {
360 if (!hotDir_.empty())
return hotDir_;
363#if defined(EVENGINE_ANDROID)
364 base = eve::android::getHotReloadDirectory();
365#elif defined(EVENGINE_IOS)
366 base = eve::ios::getHotReloadDirectory();
369 auto *fs = Filesystem::create();
370 base = fs ? fs->getAppdataDirectory() : std::string(
".");
371 if (!base.empty() && base.back() ==
'/') base.pop_back();
372 base +=
"/EVE/hotreload";
375 if (base.empty()) base =
".";
377 std::filesystem::create_directories(base, ec);
383 if (syncStarted_)
return;
385 std::filesystem::create_directories(
dir, ec);
386 hotDir_ = std::move(
dir);
389bool HotReload::mountHotDir() {
390 if (hotDirMounted_)
return true;
391 auto *fs = Filesystem::create();
392 if (!fs)
return false;
393 const std::string
dir = ensureHotDir();
394 if (!fs->mountRealDirectory(
dir,
"/",
false))
return false;
395 hotDirMounted_ =
true;
399bool HotReload::fetchManifest(std::vector<RemoteFile> &
out) {
400 const std::string url = stripTrailingSlash(syncUrl_) +
"/manifest";
401 const std::string
body = httpGet(url, 2000);
402 if (
body.empty())
return false;
405 Poco::JSON::Parser parser;
406 Poco::Dynamic::Var
result = parser.parse(
body);
407 Poco::JSON::Array::Ptr arr =
result.extract<Poco::JSON::Array::Ptr>();
408 if (!arr)
return false;
409 for (
size_t i = 0; i < arr->size(); ++i) {
410 Poco::JSON::Object::Ptr o = arr->getObject(
static_cast<unsigned int>(i));
413 f.path = o->optValue<std::string>(
"path",
"");
414 if (
f.path.empty())
continue;
415 f.size = o->optValue<int64_t>(
"size", -1);
416 f.mtime = o->optValue<int64_t>(
"mtime", -1);
418 if (!
f.path.empty())
out.push_back(std::move(
f));
426bool HotReload::downloadFile(
const std::string &relPath) {
427 const std::string url = stripTrailingSlash(syncUrl_) +
"/raw/" + urlPathEscape(relPath);
428 const std::string
body = httpGet(url, 5000);
429 if (
body.empty())
return false;
430 const std::string real = joinDir(ensureHotDir(), relPath);
431 return writeFileBytes(real,
body);
434std::map<std::string, std::pair<int64_t, int64_t>> HotReload::loadRecord()
const {
435 std::map<std::string, std::pair<int64_t, int64_t>>
record;
436 const std::string real = joinDir(hotDir_,
".eve-manifest.json");
437 std::ifstream ifs(real, std::ios::binary);
439 std::ostringstream oss;
442 Poco::JSON::Parser parser;
443 Poco::Dynamic::Var
result = parser.parse(oss.str());
444 Poco::JSON::Array::Ptr arr =
result.extract<Poco::JSON::Array::Ptr>();
446 for (
size_t i = 0; i < arr->size(); ++i) {
447 Poco::JSON::Object::Ptr o = arr->getObject(
static_cast<unsigned int>(i));
449 const std::string
path = o->optValue<std::string>(
"path",
"");
450 if (
path.empty())
continue;
451 record[
path] = {o->optValue<int64_t>(
"size", -1), o->optValue<int64_t>(
"mtime", -1)};
458void HotReload::saveRecord(
const std::map<std::string, std::pair<int64_t, int64_t>> &
record)
const {
459 Poco::JSON::Array::Ptr arr =
new Poco::JSON::Array();
460 for (
const auto &kv :
record) {
461 Poco::JSON::Object::Ptr o =
new Poco::JSON::Object();
462 o->set(
"path", kv.first);
463 o->set(
"size", kv.second.first);
464 o->set(
"mtime", kv.second.second);
467 std::ostringstream oss;
468 Poco::JSON::Stringifier::stringify(arr, oss, 0, 0);
469 const std::string real = joinDir(hotDir_,
".eve-manifest.json");
470 writeFileBytes(real, oss.str());
473void HotReload::queueChange(std::string
path) {
474 std::lock_guard<std::mutex> lock(syncMu_);
475 changedQueue_.push_back(std::move(
path));
478void HotReload::applyManifest(
const std::vector<RemoteFile> &manifest) {
479 auto record = loadRecord();
480 std::map<std::string, bool> seen;
481 for (
const auto &
file : manifest) {
482 seen[
file.path] =
true;
484 if (it !=
record.end() && it->second.first ==
file.size && it->second.second ==
file.mtime)
486 if (downloadFile(
file.path)) {
488 queueChange(
file.path);
493 if (seen.find(it->first) != seen.end()) {
497 const std::string real = joinDir(hotDir_, it->first);
499 std::filesystem::remove(real, ec);
500 queueChange(it->first);
506void HotReload::syncLoop(
int pollMs) {
508 while (syncRunning_.load()) {
509 std::vector<RemoteFile> manifest;
510 if (fetchManifest(manifest)) {
513 std::lock_guard<std::mutex> l(syncMu_);
514 syncStatus_ =
"syncing";
516 applyManifest(manifest);
518 std::lock_guard<std::mutex> l(syncMu_);
519 syncStatus_ =
"synced";
524 std::lock_guard<std::mutex> l(syncMu_);
525 syncStatus_ = failStreak > 3 ?
"error:unreachable" :
"idle";
529 std::unique_lock<std::mutex> l(syncMu_);
530 syncCv_.wait_for(l, std::chrono::milliseconds(pollMs), [
this]() {
return !syncRunning_.load(); });
533 std::lock_guard<std::mutex> l(syncMu_);
534 syncStatus_ =
"idle";
539 std::lock_guard<std::mutex> lock(syncMu_);
540 if (syncStarted_)
return false;
541 url = stripTrailingSlash(std::move(url));
542 if (url.empty())
return false;
543 if (url.rfind(
"http://", 0) != 0 && url.rfind(
"https://", 0) != 0) url =
"http://" + url;
545 syncUrl_ = std::move(url);
546 syncStatus_ =
"syncing";
548 hotDirMounted_ =
false;
551 if (!mountHotDir()) {
552 syncStarted_ =
false;
553 syncStatus_ =
"error:mount";
556 syncRunning_.store(
true);
557 syncThread_ = std::thread([
this, pollMs]() { syncLoop(pollMs); });
563 std::lock_guard<std::mutex> lock(syncMu_);
564 if (!syncStarted_)
return;
565 syncRunning_.store(
false);
567 syncCv_.notify_all();
568 if (syncThread_.joinable()) syncThread_.join();
569 std::lock_guard<std::mutex> lock(syncMu_);
570 syncStarted_ =
false;
571 changedQueue_.clear();
577 std::lock_guard<std::mutex> lock(syncMu_);
582 std::lock_guard<std::mutex> lock(syncMu_);
583 if (changedQueue_.empty())
return {};
584 std::string
p = std::move(changedQueue_.front());
585 changedQueue_.pop_front();
591#ifdef EVENGINE_WEBGPU
593std::string HotReload::ensureHotDir() {
return {}; }
594bool HotReload::mountHotDir() {
return false; }
595bool HotReload::fetchManifest(std::vector<RemoteFile> &) {
return false; }
596bool HotReload::downloadFile(
const std::string &) {
return false; }
597void HotReload::applyManifest(
const std::vector<RemoteFile> &) {}
598std::map<std::string, std::pair<int64_t, int64_t>> HotReload::loadRecord()
const {
return {}; }
599void HotReload::saveRecord(
const std::map<std::string, std::pair<int64_t, int64_t>> &)
const {}
600void HotReload::syncLoop(
int) {}
601void HotReload::queueChange(std::string) {}
610void HotReload::expose(ssq::Table &table) {
611 auto cls =
table.addClass(
name, HotReload::create,
false);
615void HotReload::expose(ssq::Class &
cls) {
ScriptComponentRecord record
#define Module_IMPL(ModuleName, newExpr)
std::optional< InteractionSession > session
virtual std::string getName() const =0
Returns the name.
EVENGINE_API_FOUNDATION public API.
Path→reload dispatcher for soft hot reload. Driven from load.nut via pollWatch → tryReload; also used...
void setRemoteHotDir(std::string dir)
Sets the remote hot dir.
int watchTree(std::string root=".")
Recursively watch root and all subdirectories. Virtual paths walk the VFS. .., ../…,...
std::string pollRemoteChange()
Polls remote change.
bool isRemoteSyncing() const
True when remote syncing.
bool tryReload(std::string path)
Offer a (normalized) path to the registered reloaders; true if any reloaded.
~HotReload() override
Hot reload.
bool watchNewDirectory(std::string path)
If path is a directory, recursively add watches for it and its current descendants.
void unbind(std::string path)
Unbinds unbind.
void stopRemoteSync()
Stops remote sync.
bool startRemoteSync(std::string url, int pollMs=1000)
Starts remote sync.
std::string remoteSyncStatus() const
Remote sync status.
void bind(std::string path, std::string kind="auto")
Pin a path to one reloader kind ("particle" / "tilemap" / "texture" / whatever a linked module regist...
static std::string normalizePath(std::string path)
Normalize path.
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
std::unordered_map< std::string, SkillDefinition > & table()