Skip to content

Commit

Permalink
chore: Code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
shdwmtr committed Jan 4, 2025
1 parent 558a779 commit f56c52b
Show file tree
Hide file tree
Showing 15 changed files with 212 additions and 72 deletions.
4 changes: 1 addition & 3 deletions assets/core/util/theme_installer.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,9 +154,7 @@ async def handler(self, websocket):
await websocket.send(json.dumps({ "type": type, "data": action_handlers[type]() }))
else:
await self.unknown_message(websocket)

# Send a response back
await websocket.send(f"Server received: {message}")

except websockets.ConnectionClosed:
logger.log("Client disconnected")

Expand Down
18 changes: 15 additions & 3 deletions examples/plugin/frontend/index.tsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,30 @@
import { callable, Millennium } from "@steambrew/client";
import { callable, Millennium, staticEmbed, PopupManager, PopupProps } from "@steambrew/client";

class classname {
static method(country: string, age: number) {
console.log(`age: ${age}, country: ${country}`);
return "method called"
}
}

const cssAsset = staticEmbed("../styles/styles.css")

// export classname class to global context
Millennium.exposeObj({ classname });

function windowCreated(context: object)
{
function windowCreated(context: PopupProps) {
// window create event.
// you can interact directly with the document and monitor it with dom observers
// you can then render components in specific pages.
console.log(context)

// here we are using `g_PopupManager`, which is Steams window manager.
// every time a new window is created, we check all open windows for the context menu, and then we add our css to it.
PopupManager.m_mapPopups.data_.forEach(popup => {
if (popup.value_._strName === "contextmenu_1") {
popup.value_.m_popup.document.head.appendChild(cssAsset.toDOMElement())
}
})
}

// Declare a function that exists on the backend
Expand All @@ -23,6 +33,8 @@ const backendMethod = callable<[{ message: string, status: boolean, count: numbe
// Entry point on the front end of your plugin
export default async function PluginMain() {

console.log(cssAsset.contents)

// Call the backend method
const message = await backendMethod({ message: "Hello World From Frontend!", status: true, count: 69 })
console.log("Result from callServerMethod:", message)
Expand Down
3 changes: 3 additions & 0 deletions examples/plugin/styles/styles.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
:root {
--example-color: #000;
}
41 changes: 27 additions & 14 deletions src/core/ffi/ffi.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class PythonGIL : public std::enable_shared_from_this<PythonGIL>
private:
PyGILState_STATE m_interpreterGIL{};
PyThreadState* m_interpreterThreadState = nullptr;
PyInterpreterState* m_mainInterpreter = nullptr;
PyInterpreterState* m_mainInterpreter = nullptr;

public:
const void HoldAndLockGIL();
Expand Down Expand Up @@ -78,43 +78,56 @@ namespace JavaScript {

std::string OnMessage(const std::string& event, const std::string name, EventHandler handler) {
events[event].push_back(std::make_pair(name, handler));

// Deliver any missed messages
auto it = missedMessages.find(event);
if (it != missedMessages.end()) {
for (const auto message : it->second) {
if (it != missedMessages.end())
{
for (const auto message : it->second)
{
handler(message, name);
}
missedMessages.erase(it); // Clear missed messages once delivered
}
return name;
}

void RemoveListener(const std::string& event, std::string listenerId) {
void RemoveListener(const std::string& event, std::string listenerId)
{
auto it = events.find(event);
if (it != events.end()) {
if (it != events.end())
{
auto& handlers = it->second;
handlers.erase(std::remove_if(handlers.begin(), handlers.end(), [listenerId](const auto& handler) {
if (handler.first == listenerId) {
handlers.erase(std::remove_if(handlers.begin(), handlers.end(), [listenerId](const auto& handler)
{
if (handler.first == listenerId)
{
return true;
}
return false;
}), handlers.end());
}),
handlers.end());
}
}

void EmitMessage(const std::string& event, const nlohmann::json& data) {
auto it = events.find(event);
if (it != events.end()) {
if (it != events.end())
{
const auto& handlers = it->second;
for (const auto& handler : handlers) {
try {
for (const auto& handler : handlers)
{
try
{
handler.second(data, handler.first);
} catch (const std::bad_function_call& e) {
}
catch (const std::bad_function_call& e)
{
Logger.Warn("Failed to emit message on {}. exception: {}", handler.first, e.what());
}
}
} else {
}
else
{
missedMessages[event].push_back(data);
}
}
Expand Down
43 changes: 41 additions & 2 deletions src/core/loader.cc
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ void Sockets::Shutdown()
if (browserClient != nullptr)
{
browserClient->close(browserHandle, websocketpp::close::status::normal, "Shutting down");
Logger.Log("Shut down browser connection...");
}
}
catch(const websocketpp::exception& e)
Expand Down Expand Up @@ -109,6 +110,10 @@ class CEFBrowser
if (method == "Target.attachedToTarget" && json["params"]["targetInfo"]["title"] == "SharedJSContext")
{
sharedJsContextSessionId = json["params"]["sessionId"];
this->UnPatchSharedJSContext();
}
else if (json.value("id", -1) == 9773)
{
this->onSharedJsConnect();
}
else if (method == "Console.messageAdded")
Expand All @@ -127,6 +132,31 @@ class CEFBrowser
Sockets::PostGlobal({ { "id", 0 }, { "method", "Target.getTargets" } });
}

const void UnPatchSharedJSContext()
{
Logger.Log("Restoring shared_js_context...");

const auto shared_js_path = SystemIO::GetSteamPath() / "steamui" / "index.html";
const auto shared_js_bak_path = SystemIO::GetSteamPath() / "steamui" / "orig.html";

try
{
if (std::filesystem::exists(shared_js_bak_path) && std::filesystem::is_regular_file(shared_js_bak_path))
{
std::filesystem::remove(shared_js_path);
}

std::filesystem::rename(shared_js_bak_path, shared_js_path);
}
catch (const std::exception& e)
{
Logger.Warn("Failed to restore shared_js_context: {}", e.what());
}

Logger.Log("Restored shared_js_context...");
Sockets::PostShared({ { "id", 9773 }, { "method", "Page.reload" } });
}

const void onSharedJsConnect()
{
std::thread([this]() {
Expand Down Expand Up @@ -324,11 +354,20 @@ const void PluginLoader::StartBackEnds(PythonManager& manager)

std::function<void(SettingsStore::PluginTypeSchema)> cb = std::bind(CoInitializer::BackendStartCallback, std::placeholders::_1);

std::thread(
m_threadPool.push_back(std::thread(
[&manager, &plugin, cb]() {
Logger.Log("Starting backend for '{}'", plugin.pluginName);
manager.CreatePythonInstance(plugin, cb);
}
).detach();
));
}
}

// PluginLoader::~PluginLoader()
// {
// Logger.Log("Shutting down plugin loader...");
// for (auto& thread : m_threadPool)
// {
// thread.join();
// }
// }
3 changes: 3 additions & 0 deletions src/core/loader.h
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ class PluginLoader {
public:

PluginLoader(std::chrono::system_clock::time_point startTime, uint16_t ftpPort);
// ~PluginLoader();

const void StartBackEnds(PythonManager& manager);
const void StartFrontEnds();
Expand All @@ -32,6 +33,8 @@ class PluginLoader {
std::shared_ptr<std::vector<SettingsStore::PluginTypeSchema>> m_pluginsPtr, m_enabledPluginsPtr;
std::chrono::system_clock::time_point m_startTime;
uint16_t m_ftpPort, m_ipcPort;

std::vector<std::thread> m_threadPool;
};

namespace Sockets {
Expand Down
1 change: 1 addition & 0 deletions src/core/py_controller/co_spawn.cc
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ PythonManager::~PythonManager()

for (const auto& [pluginName, threadState, interpMutex] : this->m_pythonInstances)
{
Logger.Warn("Shutting down plugin '{}'", pluginName);
this->DestroyPythonInstance(pluginName);
}

Expand Down
30 changes: 30 additions & 0 deletions src/main.cc
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,32 @@ const static void EntryMain()
signal(SIGINT, [](int signalCode) { std::exit(128 + SIGINT); });

#ifdef _WIN32

// try {
// if (std::filesystem::exists(SystemIO::GetInstallPath() / "user32.queue.dll"))
// {
// Logger.Log("Updating shim module from cache...");

// while (true) {
// try {
// std::filesystem::remove(SystemIO::GetInstallPath() / "user32.dll");
// break;
// }
// catch (std::filesystem::filesystem_error& e) {
// continue;
// }
// }

// Logger.Log("Removed old inject shim...");

// std::filesystem::rename(SystemIO::GetInstallPath() / "user32.queue.dll", SystemIO::GetInstallPath() / "user32.dll");
// Logger.Log("Successfully updated user32.dll!");
// }
// }
// catch (std::exception& e) {
// LOG_ERROR("Failed to update user32.dll: {}", e.what());
// }

std::unique_ptr<StartupParameters> startupParams = std::make_unique<StartupParameters>();

if (startupParams->HasArgument("-verbose"))
Expand All @@ -95,6 +121,8 @@ const static void EntryMain()

backendThread.join();
frontendThreads.join();

Logger.Log("Millennium has gracefully shut down.");
}

#ifdef _WIN32
Expand All @@ -117,6 +145,8 @@ int __stdcall DllMain(void*, unsigned long fdwReason, void*)
Sockets::Shutdown();
g_millenniumThread->join();
Logger.PrintMessage(" MAIN ", "Millennium has been shut down.", COL_MAGENTA);

std::this_thread::sleep_for(std::chrono::seconds(1000));
break;
}
}
Expand Down
4 changes: 3 additions & 1 deletion src/procmon/cmd.h
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#pragma once
#include <string>
#include <vector>
#ifdef _WIN32
#if defined(_WIN32)
#if !defined(__MILLENNIUM_SHIM__)
#include <winsock2.h>
#endif
#include <Windows.h>
#include <shellapi.h>
#endif
Expand Down
33 changes: 0 additions & 33 deletions src/sys/log.cc
Original file line number Diff line number Diff line change
Expand Up @@ -25,29 +25,6 @@ std::string OutputLogger::GetLocalTime()
return fmt::format("[{}]", bufferStream.str());
}

#ifdef _WIN32
void EnableVirtualTerminalProcessing()
{
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hOut == INVALID_HANDLE_VALUE)
{
return;
}

DWORD dwMode = 0;
if (!GetConsoleMode(hOut, &dwMode))
{
return;
}

dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(hOut, dwMode))
{
return;
}
}
#endif

void OutputLogger::PrintMessage(std::string type, const std::string& message, std::string color)
{
std::lock_guard<std::mutex> lock(logMutex);
Expand All @@ -72,16 +49,6 @@ OutputLogger::OutputLogger()

m_bIsConsoleEnabled = startupParams->HasArgument("-dev");
m_bIsVersbose = startupParams->HasArgument("-verbose");

if (!m_bIsVersbose && m_bIsConsoleEnabled && static_cast<bool>(AllocConsole()))
{
SetConsoleTitleA(fmt::format("Millennium@{}", MILLENNIUM_VERSION).c_str());
}

SetConsoleOutputCP(CP_UTF8);
void(freopen("CONOUT$", "w", stdout));
void(freopen("CONOUT$", "w", stderr));
EnableVirtualTerminalProcessing();
}
#elif __linux__
{
Expand Down
1 change: 0 additions & 1 deletion win32/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -38,4 +38,3 @@ target_link_libraries(ShimDll CURL::libcurl unofficial::minizip::minizip)
set_target_properties(ShimDll PROPERTIES OUTPUT_NAME "user32")
set_target_properties(ShimDll PROPERTIES PREFIX "")
set_target_properties(ShimDll PROPERTIES NO_EXPORT TRUE)

6 changes: 4 additions & 2 deletions win32/http.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ size_t write_callback(char* ptr, size_t size, size_t nmemb, std::string* data) {
}

bool download_file(const std::string& url, const std::string& outputFilePath) {

std::cout << "downloading to " << outputFilePath << std::endl;

CURL* curl;
CURLcode res;
std::ofstream outputFile;
Expand Down Expand Up @@ -68,12 +71,11 @@ const std::string get(const char* url, bool retry = true) {

while (true) {
res = curl_easy_perform(curl);

if (!retry || res == CURLE_OK) {
break;
}

std::cerr << "res: " << res << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3));
}
curl_easy_cleanup(curl);
Expand Down
Loading

0 comments on commit f56c52b

Please sign in to comment.