NoJobEngine 2.0.7
Loading...
Searching...
No Matches
ProjectScriptBuildSystem.cpp
Go to the documentation of this file.
2
3#include <atomic>
4#include <cstdint>
5#include <cstdio>
6#include <cstdlib>
7#include <mutex>
8#include <thread>
9#include <vector>
10
11#ifdef _WIN32
12#define NOMINMAX
13#include <Windows.h>
14#endif
15
16namespace NoJob
17{
18 namespace
19 {
21 std::mutex s_StateMutex;
22 std::thread s_Worker;
23 std::atomic_bool s_Running{ false };
24 std::atomic_bool s_ReloadPending{ false };
25 std::uint64_t s_Generation = 0;
26
27 // Backup protection for abnormal exit paths that bypass EditorLayer::Shutdown().
28 // Declared after the worker so its destructor runs before s_Worker is destroyed.
29 struct WorkerLifetimeGuard final
30 {
31 ~WorkerLifetimeGuard() noexcept
32 {
33 if (s_Worker.joinable()) s_Worker.join();
34 }
35 } s_WorkerLifetimeGuard;
36
37 void Log(std::string message)
38 {
39 if (s_Log) s_Log(std::move(message));
40 }
41
42 std::filesystem::path FindCMakeExecutable()
43 {
44#ifdef _WIN32
45 wchar_t pathBuffer[32768]{};
46 const DWORD found = SearchPathW(nullptr, L"cmake.exe", nullptr,
47 static_cast<DWORD>(std::size(pathBuffer)), pathBuffer, nullptr);
48 if (found > 0 && found < std::size(pathBuffer)) return pathBuffer;
49
50 wchar_t* programFilesX86 = nullptr;
51 std::size_t envLength = 0;
52 if (_wdupenv_s(&programFilesX86, &envLength, L"ProgramFiles(x86)") == 0 && programFilesX86)
53 {
54 const auto vswhere = std::filesystem::path(programFilesX86) /
55 "Microsoft Visual Studio" / "Installer" / "vswhere.exe";
56 free(programFilesX86);
57 if (std::filesystem::exists(vswhere))
58 {
59 const std::wstring command = L"\"" + vswhere.wstring() +
60 L"\" -latest -products * -property installationPath";
61 FILE* pipe = _wpopen(command.c_str(), L"rt");
62 if (pipe)
63 {
64 wchar_t buffer[4096]{};
65 std::wstring installPath;
66 if (fgetws(buffer, static_cast<int>(std::size(buffer)), pipe)) installPath = buffer;
67 _pclose(pipe);
68 while (!installPath.empty() &&
69 (installPath.back()==L'\r' || installPath.back()==L'\n' ||
70 installPath.back()==L' ' || installPath.back()==L'\t'))
71 installPath.pop_back();
72 if (!installPath.empty())
73 {
74 const auto bundled = std::filesystem::path(installPath) /
75 "Common7" / "IDE" / "CommonExtensions" / "Microsoft" /
76 "CMake" / "CMake" / "bin" / "cmake.exe";
77 if (std::filesystem::exists(bundled)) return bundled;
78 }
79 }
80 }
81 }
82
83 wchar_t* programFiles = nullptr;
84 envLength = 0;
85 if (_wdupenv_s(&programFiles, &envLength, L"ProgramFiles") == 0 && programFiles)
86 {
87 const auto standalone = std::filesystem::path(programFiles) / "CMake" / "bin" / "cmake.exe";
88 free(programFiles);
89 if (std::filesystem::exists(standalone)) return standalone;
90 }
91#endif
92 return {};
93 }
94
95 int RunProcess(const std::filesystem::path& executable,
96 const std::vector<std::wstring>& arguments,
97 const std::string& prefix)
98 {
99#ifdef _WIN32
100 SECURITY_ATTRIBUTES security{};
101 security.nLength = sizeof(SECURITY_ATTRIBUTES);
102 security.bInheritHandle = TRUE;
103 HANDLE readPipe = nullptr, writePipe = nullptr;
104 if (!CreatePipe(&readPipe, &writePipe, &security, 0)) { Log("[Scripts] CreatePipe failed."); return -1; }
105 SetHandleInformation(readPipe, HANDLE_FLAG_INHERIT, 0);
106
107 std::wstring commandLine = L"\"" + executable.wstring() + L"\"";
108 for (const auto& arg : arguments)
109 {
110 commandLine += L" \"";
111 for (wchar_t c : arg) { if (c == L'\"') commandLine += L'\\'; commandLine += c; }
112 commandLine += L"\"";
113 }
114 std::vector<wchar_t> mutableCommand(commandLine.begin(), commandLine.end());
115 mutableCommand.push_back(L'\0');
116
117 STARTUPINFOW startup{}; startup.cb = sizeof(startup);
118 startup.dwFlags = STARTF_USESTDHANDLES;
119 startup.hStdOutput = writePipe; startup.hStdError = writePipe;
120 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
121 PROCESS_INFORMATION process{};
122 const BOOL created = CreateProcessW(nullptr, mutableCommand.data(), nullptr, nullptr, TRUE,
123 CREATE_NO_WINDOW, nullptr, nullptr, &startup, &process);
124 CloseHandle(writePipe);
125 if (!created) { CloseHandle(readPipe); Log(prefix + "Failed to start process."); return -1; }
126
127 char buffer[4096]; DWORD bytesRead = 0; std::string pending;
128 while (ReadFile(readPipe, buffer, sizeof(buffer), &bytesRead, nullptr) && bytesRead > 0)
129 {
130 pending.append(buffer, buffer + bytesRead);
131 std::size_t newline = 0;
132 while ((newline = pending.find('\n')) != std::string::npos)
133 {
134 std::string line = pending.substr(0, newline);
135 if (!line.empty() && line.back() == '\r') line.pop_back();
136 Log(prefix + line); pending.erase(0, newline + 1);
137 }
138 }
139 if (!pending.empty()) Log(prefix + pending);
140 WaitForSingleObject(process.hProcess, INFINITE);
141 DWORD exitCode = 1; GetExitCodeProcess(process.hProcess, &exitCode);
142 CloseHandle(process.hThread); CloseHandle(process.hProcess); CloseHandle(readPipe);
143 return static_cast<int>(exitCode);
144#else
145 (void)executable; (void)arguments; (void)prefix; return -1;
146#endif
147 }
148 }
149
150 void ProjectScriptBuildSystem::SetLogger(LogFunction logger) { s_Log = std::move(logger); }
151
152 bool ProjectScriptBuildSystem::Start(const std::filesystem::path& projectRoot)
153 {
154 if (s_Running.exchange(true)) { Log("[Scripts] Compilation is already running."); return false; }
155 const auto cmake = FindCMakeExecutable();
156 if (cmake.empty())
157 {
158 Log("[Scripts] CMake was not found.");
159 Log("[Scripts] Install CMake or the Visual Studio C++/CMake tools.");
160 s_Running = false; return false;
161 }
162
163 std::lock_guard<std::mutex> lock(s_StateMutex);
164 if (s_Worker.joinable()) s_Worker.join();
165 s_ReloadPending = false;
166 const std::uint64_t generation = ++s_Generation;
167 Log("[Scripts] Hot reload generation: " + std::to_string(generation));
168
169 s_Worker = std::thread([projectRoot, cmake, generation]()
170 {
171 Log("[Scripts] CMake: " + cmake.string());
172 Log("[Scripts] Configuring project...");
173 const auto out = projectRoot / "out";
174 const int configCode = RunProcess(cmake,
175 {L"-S", projectRoot.wstring(), L"-B", out.wstring(),
176 L"-DNOJOB_HOT_RELOAD_GENERATION=" + std::to_wstring(generation)}, "[CMake] ");
177 if (configCode != 0)
178 {
179 Log("[Scripts] CMake configure FAILED (exit code " + std::to_string(configCode) + ").");
180 s_Running = false; return;
181 }
182 Log("[Scripts] Incremental build: compiling changed scripts only...");
183 const int buildCode = RunProcess(cmake,
184 {L"--build", out.wstring(), L"--target", L"NoJobProjectScripts", L"--config", L"Debug"}, "[Build] ");
185 if (buildCode != 0)
186 {
187 Log("[Scripts] Build FAILED (exit code " + std::to_string(buildCode) + ").");
188 s_Running = false; return;
189 }
190 Log("[Scripts] Build succeeded. DLL reload queued...");
191 s_ReloadPending = true;
192 s_Running = false;
193 });
194 return true;
195 }
196
197 bool ProjectScriptBuildSystem::IsRunning() { return s_Running.load(); }
198 bool ProjectScriptBuildSystem::ConsumeReloadPending() { return s_ReloadPending.exchange(false); }
199
201 {
202 std::lock_guard<std::mutex> lock(s_StateMutex);
203 if (s_Worker.joinable()) s_Worker.join();
204 s_Running = false;
205 s_ReloadPending = false;
206 }
207}
Project-native script build orchestration and reload notifications.
std::function< void(std::string)> LogFunction
static void SetLogger(LogFunction logger)
static bool Start(const std::filesystem::path &projectRoot)
Starts compilation for the specified project root.
static bool ConsumeReloadPending()
Consumes the pending reload notification after compilation.