mirror-chatterino2/src/BrowserExtension.cpp

91 lines
2.2 KiB
C++
Raw Normal View History

2018-08-02 14:23:27 +02:00
#include "BrowserExtension.hpp"
#include "singletons/NativeMessaging.hpp"
#include <QStringList>
#include <QTimer>
#include <fstream>
#include <iostream>
#include <memory>
#ifdef Q_OS_WIN
2018-08-15 22:46:20 +02:00
# include <fcntl.h>
# include <io.h>
# include <stdio.h>
2018-08-02 14:23:27 +02:00
#endif
namespace chatterino {
namespace {
2018-08-15 22:46:20 +02:00
void initFileMode()
{
2018-08-02 14:23:27 +02:00
#ifdef Q_OS_WIN
2018-08-15 22:46:20 +02:00
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
2018-08-02 14:23:27 +02:00
#endif
2018-08-15 22:46:20 +02:00
}
2018-08-02 14:23:27 +02:00
2018-08-15 22:46:20 +02:00
void runLoop(NativeMessagingClient &client)
{
2018-10-21 13:43:02 +02:00
while (true)
{
2018-08-15 22:46:20 +02:00
char size_c[4];
std::cin.read(size_c, 4);
2018-08-02 14:23:27 +02:00
2018-10-21 13:43:02 +02:00
if (std::cin.eof())
break;
2018-08-02 14:23:27 +02:00
2018-08-15 22:46:20 +02:00
auto size = *reinterpret_cast<uint32_t *>(size_c);
2018-08-02 14:23:27 +02:00
#if 0
bool bigEndian = isBigEndian();
// To avoid breaking strict-aliasing rules and potentially inducing undefined behaviour, the following code can be run instead
uint32_t size = 0;
if (bigEndian) {
size = size_c[3] | static_cast<uint32_t>(size_c[2]) << 8 |
static_cast<uint32_t>(size_c[1]) << 16 | static_cast<uint32_t>(size_c[0]) << 24;
} else {
size = size_c[0] | static_cast<uint32_t>(size_c[1]) << 8 |
static_cast<uint32_t>(size_c[2]) << 16 | static_cast<uint32_t>(size_c[3]) << 24;
}
#endif
2018-08-15 22:46:20 +02:00
std::unique_ptr<char[]> buffer(new char[size + 1]);
std::cin.read(buffer.get(), size);
*(buffer.get() + size) = '\0';
2018-08-02 14:23:27 +02:00
2018-08-15 22:46:20 +02:00
client.sendMessage(QByteArray::fromRawData(
buffer.get(), static_cast<int32_t>(size)));
}
2018-08-02 14:23:27 +02:00
}
} // namespace
bool shouldRunBrowserExtensionHost(const QStringList &args)
{
2018-08-06 21:17:03 +02:00
return args.size() > 0 && (args[0].startsWith("chrome-extension://") ||
args[0].endsWith(".json"));
2018-08-02 14:23:27 +02:00
}
void runBrowserExtensionHost()
{
initFileMode();
std::atomic<bool> ping(false);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&ping] {
2018-10-21 13:43:02 +02:00
if (!ping.exchange(false))
{
2018-08-02 14:23:27 +02:00
_Exit(0);
}
});
timer.setInterval(11000);
timer.start();
NativeMessagingClient client;
runLoop(client);
}
} // namespace chatterino