Finality Engine
Loading...
Searching...
No Matches
ExternalTools.h
Go to the documentation of this file.
1
6#pragma once
8#include <Core/Log.h>
9#include <Core/Process.h>
10#include <algorithm>
11#include <filesystem>
12#include <fstream>
13#include <future>
14#include <iomanip>
15#include <sstream>
16#ifndef NOMINMAX
17#define NOMINMAX
18#endif
19#include <Windows.h>
20#include <shellapi.h>
21
22namespace FINALITY
23{
26 {
27 public:
28 std::filesystem::path ProjectRoot;
29 std::string Executable;
30 std::string ProjectName;
31 std::vector<std::string> Installations;
32 std::string Status;
33 std::future<ProcessResult> Detection;
34 std::future<ProcessResult> SolutionGeneration;
35 std::filesystem::path PendingSource;
37 std::chrono::steady_clock::time_point VisualStudioDeadline{}, VisualStudioRetry{};
38 std::string ScriptDirectory = "Assets/Scripts";
39
40 static std::string SafeName(std::string name)
41 {
42 for (auto& c : name)
43 if (static_cast<unsigned char>(c) < 32 ||
44 std::string("<>:\"/\\|?*").find(c) != std::string::npos)
45 c = '_';
46 while (!name.empty() && name.front() == ' ')
47 name.erase(name.begin());
48 while (!name.empty() && (name.back() == ' ' || name.back() == '.'))
49 name.pop_back();
50 return name.empty() ? "FinalityProject" : name;
51 }
52 static std::wstring QuoteArgument(const std::wstring& value)
53 {
54 std::wstring result = L"\"";
55 size_t slashes = 0;
56 for (auto c : value)
57 {
58 if (c == L'\\')
59 {
60 ++slashes;
61 continue;
62 }
63 result.append(c == L'\"' ? slashes * 2 + 1 : slashes, L'\\');
64 result += c;
65 slashes = 0;
66 }
67 result.append(slashes * 2, L'\\');
68 return result + L"\"";
69 }
70 static std::wstring ScriptArguments(const std::filesystem::path& executable,
71 const std::filesystem::path& root,
72 const std::filesystem::path& solution,
73 const std::filesystem::path& source)
74 {
75 const auto name = executable.filename().wstring();
76 const auto file = std::filesystem::absolute(source).wstring();
77 if (_wcsicmp(name.c_str(), L"devenv.exe") == 0)
78 return QuoteArgument(solution.wstring());
79 if (_wcsicmp(name.c_str(), L"Code.exe") == 0 ||
80 _wcsicmp(name.c_str(), L"Code - Insiders.exe") == 0)
81 return L"--reuse-window \"" +
82 (root / (solution.stem().string() + ".code-workspace")).wstring() + L"\" --goto \"" +
83 file + L":1\"";
84 return L"\"" + root.wstring() + L"\" \"" + file + L"\"";
85 }
86
88 {
89 if (SolutionGeneration.valid())
91 if (Detection.valid())
92 Detection.get();
93 PendingSource.clear();
96 ProjectRoot.clear();
97 ProjectName.clear();
98 Executable.clear();
99 Installations.clear();
100 Status.clear();
101 }
102
103 void OpenProject(const std::filesystem::path& root,
104 const std::string& scriptDirectory = "Assets/Scripts", const std::string& name = {})
105 {
106 ProjectRoot = root;
107 ProjectName = SafeName(name.empty() ? root.filename().string() : name);
108 ScriptDirectory = scriptDirectory;
109 Executable.clear();
110 std::ifstream input(root / "Settings/ExternalTools.ini");
111 input >> std::quoted(Executable);
112 Detect();
113 }
114
115 void Save()
116 {
117 std::filesystem::create_directories(ProjectRoot / "Settings");
118 std::ofstream(ProjectRoot / "Settings/ExternalTools.ini") << std::quoted(Executable);
119 }
120
121 void Detect()
122 {
123 if (Detection.valid())
124 return;
125 const auto root = ProjectRoot;
126 Detection = std::async(std::launch::async, [root] {
127 const auto* directory = std::getenv("ProgramFiles(x86)");
128 const auto locator = std::filesystem::path(directory ? directory : "C:/Program Files (x86)") /
129 "Microsoft Visual Studio/Installer/vswhere.exe";
130 return Process::Run({locator.wstring(), L"-all", L"-prerelease", L"-legacy", L"-products",
131 L"*", L"-sort", L"-property", L"installationPath"},
132 root);
133 });
134 }
135
136 void Update()
137 {
138 const auto now = std::chrono::steady_clock::now();
139 if (!PendingVisualStudioSource.empty() && now >= VisualStudioRetry)
140 {
141 VisualStudioRetry = now + std::chrono::milliseconds(500);
143 {
145 Status = "Opened file in project solution";
146 }
147 else if (now >= VisualStudioDeadline)
148 {
150 Status = "Solution opened; Visual Studio did not become ready to open the selected file";
151 Logger::GetClientLogger()->error("{}", Status);
152 }
153 }
154 if (SolutionGeneration.valid() &&
155 SolutionGeneration.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
156 {
157 const auto result = SolutionGeneration.get();
158 const auto source = std::exchange(PendingSource, {});
159 if (result.ExitCode == 0)
160 OpenScript(source, false);
161 else
162 {
163 Status = result.Output;
164 Logger::GetClientLogger()->error("Solution generation failed: {}", Status);
165 }
166 }
167 if (!Detection.valid() ||
168 Detection.wait_for(std::chrono::seconds(0)) != std::future_status::ready)
169 return;
170 const auto result = Detection.get();
171 Installations.clear();
172 std::istringstream lines(result.Output);
173 std::string line;
174 while (std::getline(lines, line))
175 {
176 if (!line.empty() && line.back() == '\r')
177 line.pop_back();
178 const auto executable = std::filesystem::path(line) / "Common7/IDE/devenv.exe";
179 if (std::filesystem::is_regular_file(executable))
180 Installations.push_back(executable.string());
181 }
182 for (const auto* variable : {"LOCALAPPDATA", "ProgramFiles", "ProgramFiles(x86)"})
183 if (const auto* base = std::getenv(variable))
184 for (const auto& relative :
185 {"Programs/Microsoft VS Code/Code.exe", "Microsoft VS Code/Code.exe",
186 "Programs/Microsoft VS Code Insiders/Code - Insiders.exe",
187 "Microsoft VS Code Insiders/Code - Insiders.exe"})
188 {
189 const auto executable = std::filesystem::path(base) / relative;
190 if (std::filesystem::is_regular_file(executable) &&
191 std::find(Installations.begin(), Installations.end(), executable.string()) ==
192 Installations.end())
193 Installations.push_back(executable.string());
194 }
195 if (Executable.empty() && !Installations.empty())
196 {
197 Executable = Installations.front();
198 Save();
199 }
200 Status = !Installations.empty() ? "External editor discovery complete"
201 : "No editors detected; select an executable manually";
202 }
203
204 bool OpenScript(const std::filesystem::path& source, bool allowGeneration = true)
205 {
206 if (!std::filesystem::is_regular_file(source))
207 return false;
208 if (Executable.empty())
209 {
210 Status = "Select a script editor under Project Settings > External Tools";
211 return false;
212 }
213 const std::filesystem::path executable(Executable);
214 auto solution = ProjectRoot / (ProjectName + ".slnx");
215 bool included = false;
216 std::ifstream manifest(ProjectRoot / ".Finality/NativeScripts/IDEFiles.txt");
217 const auto sourceKey = std::filesystem::absolute(source).lexically_normal().generic_string();
218 std::string line;
219 while (std::getline(manifest, line))
220 {
221 if (!line.empty() && line.back() == '\r')
222 line.pop_back();
223 std::error_code error;
224 if (_stricmp(line.c_str(), sourceKey.c_str()) == 0 ||
225 std::filesystem::equivalent(std::filesystem::path(line), source, error))
226 {
227 included = true;
228 break;
229 }
230 }
231 if (!std::filesystem::is_regular_file(solution) &&
232 std::filesystem::is_regular_file(ProjectRoot / (ProjectName + ".sln")))
233 solution = ProjectRoot / (ProjectName + ".sln");
234 if (!included || !std::filesystem::is_regular_file(solution) ||
235 !std::filesystem::is_regular_file(ProjectRoot /
236 ".Finality/NativeScripts/GameScripts.vcxproj") ||
237 !std::filesystem::is_regular_file(ProjectRoot / (ProjectName + ".code-workspace")))
238 {
239 if (!allowGeneration)
240 {
241 Status = "The selected file could not be added to the project solution";
242 Logger::GetClientLogger()->error("{}: {}", Status, source.string());
243 return false;
244 }
245 if (SolutionGeneration.valid())
246 return false;
247 auto engine = Process::ExecutablePath().parent_path();
248 while (!engine.empty() &&
249 !std::filesystem::is_regular_file(engine / "Scripts/Templates/ProjectScripts.lua"))
250 {
251 const auto parent = engine.parent_path();
252 if (parent == engine)
253 {
254 engine.clear();
255 break;
256 }
257 engine = parent;
258 }
259 if (engine.empty())
260 {
261 Status = "Native script tools were not found";
262 return false;
263 }
264 PendingSource = source;
265 const auto root = ProjectRoot;
266 const auto bin = Process::ExecutablePath().parent_path();
267 const auto scripts = ScriptDirectory;
268 const auto projectName = ProjectName;
270 std::async(std::launch::async, [engine, root, bin, scripts, projectName] {
271#ifdef NDEBUG
272 const std::wstring configuration = L"Release";
273#else
274 const std::wstring configuration = L"Debug";
275#endif
276 return Process::Run({(bin / "FIBuild.exe").wstring(), L"native",
277 L"--project",
278 root.wstring(),
279 L"--name",
280 std::filesystem::path(projectName).wstring(),
281 L"--engine",
282 engine.wstring(),
283 L"--bin",
284 bin.wstring(),
285 L"--source",
286 std::filesystem::path(scripts).wstring(),
287 L"--configuration",
288 configuration,
289 L"--generate-only"},
290 root);
291 });
292 Status = "Generating engine-linked solution";
293 return true;
294 }
295 if (_wcsicmp(executable.filename().c_str(), L"devenv.exe") == 0 &&
296 OpenInRunningSolution(solution, source))
297 {
298 Status = "Opened script in project solution";
299 return true;
300 }
301 if (_wcsicmp(executable.filename().c_str(), L"devenv.exe") == 0 &&
303 {
305 return true;
306 }
307 const auto arguments = ScriptArguments(executable, ProjectRoot, solution, source);
308 const auto result = reinterpret_cast<INT_PTR>(ShellExecuteW(
309 nullptr, L"open", executable.c_str(), arguments.c_str(), ProjectRoot.c_str(), SW_SHOWNORMAL));
310 Status = result > 32 ? "Opened script in external editor"
311 : "Could not launch the selected external editor";
312 if (result <= 32)
313 Logger::GetClientLogger()->error("{}", Status);
314 else if (_wcsicmp(executable.filename().c_str(), L"devenv.exe") == 0)
315 {
318 VisualStudioDeadline = std::chrono::steady_clock::now() + std::chrono::seconds(120);
319 VisualStudioRetry = std::chrono::steady_clock::now() + std::chrono::milliseconds(500);
320 Status = "Opening project solution in Visual Studio";
321 }
322 return result > 32;
323 }
324 };
325}
Runs external tools with captured diagnostics.
std::filesystem::path PendingSource
static std::wstring ScriptArguments(const std::filesystem::path &executable, const std::filesystem::path &root, const std::filesystem::path &solution, const std::filesystem::path &source)
std::vector< std::string > Installations
std::future< ProcessResult > Detection
static std::string SafeName(std::string name)
static std::wstring QuoteArgument(const std::wstring &value)
void OpenProject(const std::filesystem::path &root, const std::string &scriptDirectory="Assets/Scripts", const std::string &name={})
bool OpenScript(const std::filesystem::path &source, bool allowGeneration=true)
std::filesystem::path ProjectRoot
std::future< ProcessResult > SolutionGeneration
std::chrono::steady_clock::time_point VisualStudioDeadline
std::filesystem::path PendingVisualStudioSolution
std::filesystem::path PendingVisualStudioSource
std::chrono::steady_clock::time_point VisualStudioRetry
static std::shared_ptr< spdlog::logger > & GetClientLogger()
Definition Log.h:55
static ProcessResult Run(const std::vector< std::wstring > &arguments, const std::filesystem::path &directory)
static std::filesystem::path ExecutablePath()
bool OpenInRunningSolution(const std::filesystem::path &solution, const std::filesystem::path &source)