mirror-chatterino2/src/BrowserExtension.cpp

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

104 lines
2.1 KiB
C++
Raw Normal View History

2018-08-02 14:23:27 +02:00
#include "BrowserExtension.hpp"
#include "singletons/NativeMessaging.hpp"
#include "util/RenameThread.hpp"
2018-08-02 14:23:27 +02:00
#include <iostream>
#include <memory>
#include <thread>
2018-08-02 14:23:27 +02:00
#ifdef Q_OS_WIN
2018-08-15 22:46:20 +02:00
# include <fcntl.h>
# include <io.h>
2018-08-02 14:23:27 +02:00
# include <cstdio>
#endif
2018-08-02 14:23:27 +02:00
namespace {
using namespace chatterino;
void initFileMode()
{
2018-08-02 14:23:27 +02:00
#ifdef Q_OS_WIN
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
2018-08-02 14:23:27 +02:00
#endif
}
2019-08-25 21:25:31 +02:00
// TODO(Qt6): Use QUtf8String
void sendToBrowser(QLatin1String str)
{
auto len = static_cast<uint32_t>(str.size());
std::cout.write(reinterpret_cast<const char *>(&len), sizeof(len));
std::cout.write(str.data(), str.size());
std::cout.flush();
}
2019-08-25 21:25:31 +02:00
QByteArray receiveFromBrowser()
{
uint32_t size = 0;
std::cin.read(reinterpret_cast<char *>(&size), sizeof(size));
2018-08-02 14:23:27 +02:00
if (std::cin.eof())
{
return {};
}
2018-08-02 14:23:27 +02:00
QByteArray buffer{static_cast<QByteArray::size_type>(size),
Qt::Uninitialized};
std::cin.read(buffer.data(), size);
2018-08-02 14:23:27 +02:00
return buffer;
}
2018-08-02 14:23:27 +02:00
void runLoop()
{
auto receivedMessage = std::make_shared<std::atomic_bool>(true);
2019-08-25 21:25:31 +02:00
auto thread = std::thread([=]() {
while (true)
{
using namespace std::chrono_literals;
if (!receivedMessage->exchange(false))
2019-08-25 21:25:31 +02:00
{
sendToBrowser(QLatin1String{
R"({"type":"status","status":"exiting-host","reason":"no message was received in 10s"})"});
_Exit(1);
2019-08-25 21:25:31 +02:00
}
std::this_thread::sleep_for(10s);
}
});
renameThread(thread, "BrowserPingCheck");
2019-08-25 21:25:31 +02:00
while (true)
{
auto buffer = receiveFromBrowser();
if (buffer.isNull())
{
break;
2018-08-15 22:46:20 +02:00
}
receivedMessage->store(true);
nm::client::sendMessage(buffer);
2018-08-02 14:23:27 +02:00
}
sendToBrowser(QLatin1String{
R"({"type":"status","status":"exiting-host","reason":"received EOF"})"});
_Exit(0);
}
2018-08-02 14:23:27 +02:00
} // namespace
namespace chatterino {
2018-08-02 14:23:27 +02:00
void runBrowserExtensionHost()
{
initFileMode();
runLoop();
2018-08-02 14:23:27 +02:00
}
} // namespace chatterino