From 5a5bd5cb2ee2606d99aa904b34105c62d2f56091 Mon Sep 17 00:00:00 2001 From: MihailRis Date: Fri, 3 Oct 2025 22:02:56 +0300 Subject: [PATCH] add platform::new_engine_instance --- src/util/platform.cpp | 67 +++++++++++++++++++++++++++++++++++++++++++ src/util/platform.hpp | 3 ++ 2 files changed, 70 insertions(+) diff --git a/src/util/platform.cpp b/src/util/platform.cpp index 7bb7f7f4..b36d5eb7 100644 --- a/src/util/platform.cpp +++ b/src/util/platform.cpp @@ -115,6 +115,73 @@ int platform::get_process_id() { return getpid(); } +void platform::new_engine_instance(const std::vector& args) { + auto executable = get_executable_path(); + +#ifdef _WIN32 + std::stringstream ss; + for (int i = 0; i < args.size(); i++) { + ss << " " << util::quote(args[i]); + } + + auto toWString = [](const std::string& src) { + if (src.empty()) + return L""; + int size = MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, nullptr, 0); + if (size == 0) { + throw std::runtime_error( + "MultiByteToWideChar failed with code: " + + std::to_string(GetLastError()) + ) + } + std::vector buffer(size); + MultiByteToWideChar(CP_UTF8, 0, src.c_str(), -1, buffer.data(), size); + return std::wstring(buffer.data()); + }; + + auto executableString = toWString(executable.u8string()); + auto argsString = toWString(ss.str()); + + STARTUPINFOW si = { sizeof(si) }; + PROCESS_INFORMATION pi = { 0 }; + DWORD flags = CREATE_NEW_PROCESS_GROUP | DETACHED_PROCESS; + // | CREATE_NO_WINDOW; + BOOL success = CreateProcessW( + executable.u8string().c_str(), + argsString.c_str(), + nullptr, + nullptr, + FALSE, + flags, + nullptr, + "", + &si, + &pi + ); + if (!success) { + throw std::runtime_error( + "starting an engine instance failed with code: " + + std::to_string(GetLastError()) + ); + } +#else + std::stringstream ss; + ss << executable; + for (int i = 0; i < args.size(); i++) { + ss << " " << util::quote(args[i]); + } + ss << " >/dev/null &"; + + auto command = ss.str(); + if (int res = system(command.c_str())) { + throw std::runtime_error( + "starting an engine instance failed with code: " + + std::to_string(res) + ); + } +#endif +} + bool platform::open_url(const std::string& url) { if (url.empty()) return false; diff --git a/src/util/platform.hpp b/src/util/platform.hpp index c4b45650..148c64c4 100644 --- a/src/util/platform.hpp +++ b/src/util/platform.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include namespace platform { @@ -16,6 +17,8 @@ namespace platform { int get_process_id(); /// @brief Get current process running executable path std::filesystem::path get_executable_path(); + /// @brief Run a separate engine instance with specified arguments + void new_engine_instance(const std::vector& args); /// @brief Open URL in web browser bool open_url(const std::string& url); }