iw5-mod/src/module/console.cpp

116 lines
2.1 KiB
C++
Raw Normal View History

2018-12-24 17:22:56 -05:00
#include <std_include.hpp>
#include "loader/module_loader.hpp"
#include "game/game.hpp"
2018-12-27 11:11:52 -05:00
#include "scheduler.hpp"
2018-12-24 17:22:56 -05:00
class console final : public module
{
public:
console()
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
_pipe(this->handles_, 1024, _O_TEXT);
_dup2(this->handles_[1], 1);
_dup2(this->handles_[1], 2);
2018-12-27 11:11:52 -05:00
//setvbuf(stdout, nullptr, _IONBF, 0);
//setvbuf(stderr, nullptr, _IONBF, 0);
}
void post_start() override
{
2018-12-27 11:11:52 -05:00
scheduler::on_frame(std::bind(&console::log_messages, this));
this->console_runner_ = std::thread(std::bind(&console::runner, this));
}
void pre_destroy() override
{
this->terminate_runner_ = true;
printf("\r\n");
_flushall();
_close(this->handles_[0]);
_close(this->handles_[1]);
if (this->console_runner_.joinable())
{
this->console_runner_.join();
}
}
2018-12-24 17:22:56 -05:00
void post_load() override
{
2019-01-26 20:52:33 -05:00
if (!game::is_dedi())
{
game::native::Sys_ShowConsole();
}
std::lock_guard _(this->mutex_);
this->console_initialized_ = true;
}
private:
bool console_initialized_ = false;
bool terminate_runner_ = false;
std::mutex mutex_;
std::thread console_runner_;
std::queue<std::string> message_queue_;
int handles_[2]{};
2018-12-27 11:11:52 -05:00
void log_messages()
{
2018-12-27 11:11:52 -05:00
while (this->console_initialized_ && !this->message_queue_.empty())
{
2018-12-27 11:11:52 -05:00
std::queue<std::string> message_queue_copy;
{
std::lock_guard _(this->mutex_);
message_queue_copy = this->message_queue_;
this->message_queue_ = {};
}
while (!message_queue_copy.empty())
{
log_message(message_queue_copy.front());
message_queue_copy.pop();
}
}
2018-12-27 11:11:52 -05:00
fflush(stdout);
fflush(stderr);
}
2018-12-27 11:11:52 -05:00
static void log_message(const std::string& message)
{
OutputDebugStringA(message.data());
game::native::Conbuf_AppendText(message.data());
}
void runner()
{
char buffer[1024];
while (!this->terminate_runner_ && this->handles_[0])
{
const auto len = _read(this->handles_[0], buffer, sizeof(buffer));
if (len > 0)
{
2018-12-27 11:11:52 -05:00
std::lock_guard _(this->mutex_);
this->message_queue_.push(std::string(buffer, len));
}
else
{
std::this_thread::sleep_for(10ms);
}
}
std::this_thread::yield();
2018-12-24 17:22:56 -05:00
}
};
REGISTER_MODULE(console)