Refactor Native Messages (#4738)

* refactor: move ipc queue into its own class

* refactor: move windows.h related functions to AW

* refactor: make NM-Client methods static

* refactor: json access

* refactor: use struct initializer

* refactor: move `handleMessage` to anon-namespace

* refactor: clean-up includes

* refactor: move action handler to functions

* refactor: cleanup `handleSelect`

* fix: cleanup clang-tidy warnings

* chore: simplify json

* revert: keep handlers as methods

This is more readable and extensible.

* fix: typo

* fix: namespace

* fix: rename define

* refactor: `IpcQueue` to be simpler

* fix: rename cmake option

* fix: use variant when constructing

* fix: make it a ref

* fix: its a pair now
This commit is contained in:
nerix
2023-07-30 13:14:58 +02:00
committed by GitHub
parent c496a68633
commit 378aee7ab1
9 changed files with 301 additions and 186 deletions
+151 -176
View File
@@ -1,38 +1,38 @@
#include "singletons/NativeMessaging.hpp"
#include "Application.hpp"
#include "common/Literals.hpp"
#include "common/QLogging.hpp"
#include "providers/twitch/TwitchIrcServer.hpp"
#include "singletons/Paths.hpp"
#include "util/IpcQueue.hpp"
#include "util/PostToThread.hpp"
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/interprocess/ipc/message_queue.hpp>
#include <QCoreApplication>
#include <QFile>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
namespace ipc = boost::interprocess;
#include <QSettings>
#ifdef Q_OS_WIN
// clang-format off
# include <QSettings>
# include <Windows.h>
// clang-format on
# include "singletons/WindowManager.hpp"
# include "widgets/AttachedWindow.hpp"
#endif
#include <iostream>
namespace {
#define EXTENSION_ID "glknmaideaikkmemifbfkhnomoknepka"
#define MESSAGE_SIZE 1024
using namespace chatterino::literals;
const QString EXTENSION_ID = u"glknmaideaikkmemifbfkhnomoknepka"_s;
constexpr const size_t MESSAGE_SIZE = 1024;
} // namespace
namespace chatterino {
using namespace literals;
void registerNmManifest(Paths &paths, const QString &manifestFilename,
const QString &registryKeyName,
const QJsonDocument &document);
@@ -40,47 +40,42 @@ void registerNmManifest(Paths &paths, const QString &manifestFilename,
void registerNmHost(Paths &paths)
{
if (paths.isPortable())
{
return;
}
auto getBaseDocument = [&] {
QJsonObject obj;
obj.insert("name", "com.chatterino.chatterino");
obj.insert("description", "Browser interaction with chatterino.");
obj.insert("path", QCoreApplication::applicationFilePath());
obj.insert("type", "stdio");
return obj;
auto getBaseDocument = [] {
return QJsonObject{
{u"name"_s, "com.chatterino.chatterino"_L1},
{u"description"_s, "Browser interaction with chatterino."_L1},
{u"path"_s, QCoreApplication::applicationFilePath()},
{u"type"_s, "stdio"_L1},
};
};
// chrome
{
QJsonDocument document;
auto obj = getBaseDocument();
QJsonArray allowed_origins_arr = {"chrome-extension://" EXTENSION_ID
"/"};
obj.insert("allowed_origins", allowed_origins_arr);
document.setObject(obj);
QJsonArray allowedOriginsArr = {
u"chrome-extension://%1/"_s.arg(EXTENSION_ID)};
obj.insert("allowed_origins", allowedOriginsArr);
registerNmManifest(paths, "/native-messaging-manifest-chrome.json",
"HKCU\\Software\\Google\\Chrome\\NativeMessagingHost"
"s\\com.chatterino.chatterino",
document);
QJsonDocument(obj));
}
// firefox
{
QJsonDocument document;
auto obj = getBaseDocument();
QJsonArray allowed_extensions = {"chatterino_native@chatterino.com"};
obj.insert("allowed_extensions", allowed_extensions);
document.setObject(obj);
QJsonArray allowedExtensions = {"chatterino_native@chatterino.com"};
obj.insert("allowed_extensions", allowedExtensions);
registerNmManifest(paths, "/native-messaging-manifest-firefox.json",
"HKCU\\Software\\Mozilla\\NativeMessagingHosts\\com."
"chatterino.chatterino",
document);
QJsonDocument(obj));
}
}
@@ -112,32 +107,26 @@ std::string &getNmQueueName(Paths &paths)
// CLIENT
void NativeMessagingClient::sendMessage(const QByteArray &array)
{
try
namespace nm::client {
void sendMessage(const QByteArray &array)
{
ipc::message_queue messageQueue(ipc::open_only, "chatterino_gui");
messageQueue.try_send(array.data(), size_t(array.size()), 1);
// messageQueue.timed_send(array.data(), size_t(array.size()), 1,
// boost::posix_time::second_clock::local_time() +
// boost::posix_time::seconds(10));
ipc::sendMessage("chatterino_gui", array);
}
catch (ipc::interprocess_exception &ex)
void writeToCout(const QByteArray &array)
{
qCDebug(chatterinoNativeMessage) << "send to gui process:" << ex.what();
const auto *data = array.data();
auto size = uint32_t(array.size());
// We're writing the raw bytes to cout.
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
std::cout.write(reinterpret_cast<char *>(&size), 4);
std::cout.write(data, size);
std::cout.flush();
}
}
void NativeMessagingClient::writeToCout(const QByteArray &array)
{
auto *data = array.data();
auto size = uint32_t(array.size());
std::cout.write(reinterpret_cast<char *>(&size), 4);
std::cout.write(data, size);
std::cout.flush();
}
} // namespace nm::client
// SERVER
@@ -148,146 +137,132 @@ void NativeMessagingServer::start()
void NativeMessagingServer::ReceiverThread::run()
{
try
{
ipc::message_queue::remove("chatterino_gui");
ipc::message_queue messageQueue(ipc::open_or_create, "chatterino_gui",
100, MESSAGE_SIZE);
auto [messageQueue, error] =
ipc::IpcQueue::tryReplaceOrCreate("chatterino_gui", 100, MESSAGE_SIZE);
while (true)
{
try
{
auto buf = std::make_unique<char[]>(MESSAGE_SIZE);
auto retSize = ipc::message_queue::size_type();
auto priority = static_cast<unsigned int>(0);
messageQueue.receive(buf.get(), MESSAGE_SIZE, retSize,
priority);
auto document = QJsonDocument::fromJson(
QByteArray::fromRawData(buf.get(), retSize));
this->handleMessage(document.object());
}
catch (ipc::interprocess_exception &ex)
{
qCDebug(chatterinoNativeMessage)
<< "received from gui process:" << ex.what();
}
}
}
catch (ipc::interprocess_exception &ex)
if (!error.isEmpty())
{
qCDebug(chatterinoNativeMessage)
<< "run ipc message queue:" << ex.what();
<< "Failed to create message queue:" << error;
nmIpcError().set(QString::fromLatin1(ex.what()));
nmIpcError().set(error);
return;
}
while (true)
{
auto buf = messageQueue->receive();
if (buf.isEmpty())
{
continue;
}
auto document = QJsonDocument::fromJson(buf);
this->handleMessage(document.object());
}
}
void NativeMessagingServer::ReceiverThread::handleMessage(
const QJsonObject &root)
{
QString action = root.value("action").toString();
if (action.isNull())
{
qCDebug(chatterinoNativeMessage) << "NM action was null";
return;
}
QString action = root["action"_L1].toString();
if (action == "select")
{
QString _type = root.value("type").toString();
bool attach = root.value("attach").toBool();
bool attachFullscreen = root.value("attach_fullscreen").toBool();
QString name = root.value("name").toString();
#ifdef USEWINSDK
AttachedWindow::GetArgs args;
args.winId = root.value("winId").toString();
args.yOffset = root.value("yOffset").toInt(-1);
{
const auto sizeObject = root.value("size").toObject();
args.x = sizeObject.value("x").toDouble(-1.0);
args.pixelRatio = sizeObject.value("pixelRatio").toDouble(-1.0);
args.width = sizeObject.value("width").toInt(-1);
args.height = sizeObject.value("height").toInt(-1);
}
args.fullscreen = attachFullscreen;
qCDebug(chatterinoNativeMessage)
<< args.x << args.pixelRatio << args.width << args.height
<< args.winId;
if (_type.isNull() || args.winId.isNull())
{
qCDebug(chatterinoNativeMessage)
<< "NM type, name or winId missing";
attach = false;
attachFullscreen = false;
return;
}
#endif
if (_type == "twitch")
{
postToThread([=] {
auto *app = getApp();
if (!name.isEmpty())
{
auto channel = app->twitch->getOrAddChannel(name);
if (app->twitch->watchingChannel.get() != channel)
{
app->twitch->watchingChannel.reset(channel);
}
}
if (attach || attachFullscreen)
{
#ifdef USEWINSDK
auto *window =
AttachedWindow::get(::GetForegroundWindow(), args);
if (!name.isEmpty())
{
window->setChannel(app->twitch->getOrAddChannel(name));
}
#endif
}
});
}
else
{
qCDebug(chatterinoNativeMessage) << "NM unknown channel type";
}
this->handleSelect(root);
return;
}
else if (action == "detach")
if (action == "detach")
{
QString winId = root.value("winId").toString();
if (winId.isNull())
{
qCDebug(chatterinoNativeMessage) << "NM winId missing";
return;
}
#ifdef USEWINSDK
postToThread([winId] {
qCDebug(chatterinoNativeMessage) << "NW detach";
AttachedWindow::detach(winId);
});
#endif
}
else
{
qCDebug(chatterinoNativeMessage) << "NM unknown action " + action;
this->handleDetach(root);
return;
}
qCDebug(chatterinoNativeMessage) << "NM unknown action" << action;
}
// NOLINTBEGIN(readability-convert-member-functions-to-static)
void NativeMessagingServer::ReceiverThread::handleSelect(
const QJsonObject &root)
{
QString type = root["type"_L1].toString();
bool attach = root["attach"_L1].toBool();
bool attachFullscreen = root["attach_fullscreen"_L1].toBool();
QString name = root["name"_L1].toString();
#ifdef USEWINSDK
const auto sizeObject = root["size"_L1].toObject();
AttachedWindow::GetArgs args = {
.winId = root["winId"_L1].toString(),
.yOffset = root["yOffset"_L1].toInt(-1),
.x = sizeObject["x"_L1].toDouble(-1.0),
.pixelRatio = sizeObject["pixelRatio"_L1].toDouble(-1.0),
.width = sizeObject["width"_L1].toInt(-1),
.height = sizeObject["height"_L1].toInt(-1),
.fullscreen = attachFullscreen,
};
qCDebug(chatterinoNativeMessage)
<< args.x << args.pixelRatio << args.width << args.height << args.winId;
if (args.winId.isNull())
{
qCDebug(chatterinoNativeMessage) << "winId in select is missing";
return;
}
#endif
if (type != u"twitch"_s)
{
qCDebug(chatterinoNativeMessage) << "NM unknown channel type";
return;
}
postToThread([=] {
auto *app = getApp();
if (!name.isEmpty())
{
auto channel = app->twitch->getOrAddChannel(name);
if (app->twitch->watchingChannel.get() != channel)
{
app->twitch->watchingChannel.reset(channel);
}
}
if (attach || attachFullscreen)
{
#ifdef USEWINSDK
auto *window = AttachedWindow::getForeground(args);
if (!name.isEmpty())
{
window->setChannel(app->twitch->getOrAddChannel(name));
}
#endif
}
});
}
void NativeMessagingServer::ReceiverThread::handleDetach(
const QJsonObject &root)
{
QString winId = root["winId"_L1].toString();
if (winId.isNull())
{
qCDebug(chatterinoNativeMessage) << "NM winId missing";
return;
}
#ifdef USEWINSDK
postToThread([winId] {
qCDebug(chatterinoNativeMessage) << "NW detach";
AttachedWindow::detach(winId);
});
#endif
}
// NOLINTEND(readability-convert-member-functions-to-static)
Atomic<boost::optional<QString>> &nmIpcError()
{
static Atomic<boost::optional<QString>> x;