Files
BloomPatched/src/Application.cpp

605 lines
22 KiB
C++
Raw Normal View History

2021-08-22 20:46:52 +01:00
#include "Application.hpp"
2021-04-04 21:04:12 +01:00
#include <iostream>
#include <QTimer>
#include <QFile>
2021-04-04 21:04:12 +01:00
#include <QJsonDocument>
#include <unistd.h>
#include <yaml-cpp/yaml.h>
#include <yaml-cpp/exceptions.h>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkRequest>
#include <QtNetwork/QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
2021-04-04 21:04:12 +01:00
#include "src/Services/ProcessService.hpp"
2021-04-04 21:04:12 +01:00
#include "src/Logger/Logger.hpp"
#include "src/Services/PathService.hpp"
2022-06-22 22:24:27 +01:00
2022-02-06 13:45:35 +00:00
#include "src/Exceptions/InvalidConfig.hpp"
2021-04-04 21:04:12 +01:00
namespace Bloom
{
using namespace Exceptions;
2021-04-04 21:04:12 +01:00
2022-06-22 22:24:27 +01:00
Application::Application(std::vector<std::string>&& arguments)
: arguments(std::move(arguments))
, qtApplication(
(
Thread::blockAllSignals(),
QCoreApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true),
#ifndef BLOOM_DEBUG_BUILD
QCoreApplication::addLibraryPath(QString::fromStdString(Services::PathService::applicationDirPath() + "/plugins")),
#endif
QApplication(this->qtApplicationArgc, this->qtApplicationArgv.data())
)
)
2022-06-22 22:24:27 +01:00
{}
int Application::run() {
try {
this->setName("Bloom");
2021-04-04 21:04:12 +01:00
2022-06-22 22:24:27 +01:00
if (this->arguments.size() > 1) {
auto& firstArg = this->arguments.at(1);
2022-05-28 23:11:00 +01:00
const auto commandHandlersByCommandName = this->getCommandHandlersByCommandName();
2022-12-03 22:16:21 +00:00
const auto commandHandlerIt = commandHandlersByCommandName.find(firstArg);
2021-04-04 21:04:12 +01:00
2022-12-03 22:16:21 +00:00
if (commandHandlerIt != commandHandlersByCommandName.end()) {
// User has passed an argument that maps to a command callback - invoke the callback and shutdown
2022-12-03 22:16:21 +00:00
const auto returnValue = commandHandlerIt->second();
2021-04-04 21:04:12 +01:00
this->shutdown();
return returnValue;
}
2022-01-02 20:45:14 +00:00
// If the first argument didn't map to a command, we assume it's an environment name
2022-05-14 22:43:35 +01:00
this->selectedEnvironmentName = std::move(firstArg);
}
2021-04-04 21:04:12 +01:00
2021-04-24 16:22:04 +01:00
#ifdef BLOOM_DEBUG_BUILD
2022-06-22 22:24:27 +01:00
Logger::warning("This is a debug build - some functions may not work as expected");
2021-04-24 16:22:04 +01:00
#endif
2023-05-10 19:53:39 +01:00
#ifdef EXCLUDE_INSIGHT
Logger::warning(
"The Insight component has been excluded from this build. All Insight related configuration parameters "
"will be ignored."
);
#endif
this->startup();
2021-04-04 21:04:12 +01:00
2023-05-10 19:53:39 +01:00
#ifndef EXCLUDE_INSIGHT
if (this->insightConfig->activateOnStartup) {
this->activateInsight();
}
2023-05-10 19:53:39 +01:00
#endif
this->checkBloomVersion();
/*
* We can't run our own event loop here - we have to use Qt's event loop. But we still need to be able to
* process our events. To address this, we use a QTimer to dispatch our events on an interval.
*
* This allows us to use Qt's event loop whilst still being able to process our own events.
*/
auto* eventDispatchTimer = new QTimer(&(this->qtApplication));
QObject::connect(eventDispatchTimer, &QTimer::timeout, this, &Application::dispatchEvents);
eventDispatchTimer->start(100);
this->qtApplication.exec();
2022-02-06 13:45:35 +00:00
} catch (const InvalidConfig& exception) {
Logger::error("Invalid project configuration (bloom.yaml) - " + exception.getMessage());
2021-04-04 21:04:12 +01:00
2022-02-06 13:45:35 +00:00
} catch (const Exception& exception) {
Logger::error(exception.getMessage());
2021-04-04 21:04:12 +01:00
}
this->shutdown();
return EXIT_SUCCESS;
}
2021-04-04 21:04:12 +01:00
2022-05-28 23:11:00 +01:00
std::map<std::string, std::function<int()>> Application::getCommandHandlersByCommandName() {
return std::map<std::string, std::function<int()>> {
{
"--help",
std::bind(&Application::presentHelpText, this)
},
{
"-h",
std::bind(&Application::presentHelpText, this)
},
{
"--version",
std::bind(&Application::presentVersionText, this)
},
{
"-v",
std::bind(&Application::presentVersionText, this)
},
{
"--version-machine",
std::bind(&Application::presentVersionMachineText, this)
},
{
"init",
std::bind(&Application::initProject, this)
},
};
}
void Application::startup() {
2022-02-09 17:49:25 +00:00
auto& applicationEventListener = this->applicationEventListener;
2022-03-20 17:37:36 +00:00
EventManager::registerListener(applicationEventListener);
applicationEventListener->registerCallbackForEventType<Events::ShutdownApplication>(
std::bind(&Application::onShutdownApplicationRequest, this, std::placeholders::_1)
);
2021-04-04 21:04:12 +01:00
this->loadProjectSettings();
this->loadProjectConfiguration();
Logger::configure(this->projectConfig.value());
Logger::debug("Bloom version: " + Application::VERSION.toString());
2021-04-04 21:04:12 +01:00
this->startSignalHandler();
2021-04-04 21:04:12 +01:00
Logger::info("Selected environment: \"" + this->selectedEnvironmentName + "\"");
Logger::debug("Number of environments extracted from config: "
2022-02-06 13:45:35 +00:00
+ std::to_string(this->projectConfig->environments.size()));
applicationEventListener->registerCallbackForEventType<Events::TargetControllerThreadStateChanged>(
std::bind(&Application::onTargetControllerThreadStateChanged, this, std::placeholders::_1)
);
2021-04-04 21:04:12 +01:00
applicationEventListener->registerCallbackForEventType<Events::DebugServerThreadStateChanged>(
std::bind(&Application::onDebugServerThreadStateChanged, this, std::placeholders::_1)
);
2021-04-04 21:04:12 +01:00
applicationEventListener->registerCallbackForEventType<Events::DebugSessionFinished>(
std::bind(&Application::onDebugSessionFinished, this, std::placeholders::_1)
);
#ifndef EXCLUDE_INSIGHT
applicationEventListener->registerCallbackForEventType<Events::InsightActivationRequested>(
std::bind(&Application::onInsightActivationRequest, this, std::placeholders::_1)
);
#endif
this->startTargetController();
this->startDebugServer();
2021-04-04 21:04:12 +01:00
2023-05-25 23:16:30 +01:00
Thread::threadState = ThreadState::READY;
}
2021-04-04 21:04:12 +01:00
void Application::shutdown() {
2022-05-14 22:43:35 +01:00
const auto appState = Thread::getThreadState();
if (appState == ThreadState::STOPPED || appState == ThreadState::SHUTDOWN_INITIATED) {
return;
}
2021-04-04 21:04:12 +01:00
2023-05-25 23:16:30 +01:00
Thread::threadState = ThreadState::SHUTDOWN_INITIATED;
Logger::info("Shutting down Bloom");
2023-05-10 19:53:39 +01:00
#ifndef EXCLUDE_INSIGHT
if (this->insight != nullptr) {
this->insight->shutdown();
}
2023-05-10 19:53:39 +01:00
#endif
this->stopDebugServer();
this->stopTargetController();
this->stopSignalHandler();
2021-04-04 21:04:12 +01:00
this->saveProjectSettings();
this->qtApplication.exit(0);
2023-05-25 23:16:30 +01:00
Thread::threadState = ThreadState::STOPPED;
}
void Application::loadProjectSettings() {
const auto projectSettingsPath = Services::PathService::projectSettingsPath();
auto jsonSettingsFile = QFile(QString::fromStdString(projectSettingsPath));
if (jsonSettingsFile.exists()) {
try {
if (!jsonSettingsFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw Exception("Failed to open settings file.");
}
2022-02-09 17:49:25 +00:00
this->projectSettings = ProjectSettings(
QJsonDocument::fromJson(jsonSettingsFile.readAll()).object()
);
jsonSettingsFile.close();
return;
2022-02-06 13:45:35 +00:00
} catch (const std::exception& exception) {
Logger::error(
"Failed to load project settings from " + projectSettingsPath + " - " + exception.what()
);
}
}
2022-01-22 16:14:29 +00:00
this->projectSettings = ProjectSettings();
}
2022-01-22 16:14:29 +00:00
void Application::saveProjectSettings() {
if (!this->projectSettings.has_value()) {
return;
}
const auto projectSettingsPath = Services::PathService::projectSettingsPath();
auto jsonSettingsFile = QFile(QString::fromStdString(projectSettingsPath));
Logger::debug("Saving project settings to " + projectSettingsPath);
QDir().mkpath(QString::fromStdString(Services::PathService::projectSettingsDirPath()));
2022-01-22 16:14:29 +00:00
try {
const auto jsonDocument = QJsonDocument(this->projectSettings->toJson());
2022-01-22 16:14:29 +00:00
if (!jsonSettingsFile.open(QIODevice::ReadWrite | QIODevice::Truncate | QIODevice::Text)) {
throw Exception(
2022-08-30 02:05:43 +01:00
"Failed to open/create settings file (" + projectSettingsPath + "). Check file permissions."
);
}
2022-01-22 16:14:29 +00:00
jsonSettingsFile.write(jsonDocument.toJson());
jsonSettingsFile.close();
2022-01-22 16:14:29 +00:00
2022-02-06 13:45:35 +00:00
} catch (const Exception& exception) {
Logger::error(
"Failed to save project settings - " + exception.getMessage()
2022-01-22 16:14:29 +00:00
);
}
}
void Application::loadProjectConfiguration() {
auto configFile = QFile(QString::fromStdString(Services::PathService::projectConfigPath()));
2021-04-04 21:04:12 +01:00
if (!configFile.exists()) {
2023-05-24 19:36:58 +01:00
throw Exception(
"Bloom configuration file (bloom.yaml) not found. Working directory: "
+ Services::PathService::projectDirPath()
);
}
2021-04-04 21:04:12 +01:00
if (!configFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
throw InvalidConfig(
"Failed to open Bloom configuration file. Working directory: " + Services::PathService::projectDirPath()
);
}
2021-04-04 21:04:12 +01:00
try {
const auto configNode = YAML::Load(configFile.readAll().toStdString());
configFile.close();
this->projectConfig = ProjectConfig(configNode);
} catch (const YAML::Exception& exception) {
throw InvalidConfig(exception.msg);
}
// Validate the selected environment
2022-12-03 22:16:21 +00:00
const auto selectedEnvironmentIt = this->projectConfig->environments.find(this->selectedEnvironmentName);
if (selectedEnvironmentIt == this->projectConfig->environments.end()) {
throw InvalidConfig(
"Environment (\"" + this->selectedEnvironmentName + "\") not found in configuration."
);
}
2022-12-03 22:16:21 +00:00
this->environmentConfig = selectedEnvironmentIt->second;
2023-05-10 19:53:39 +01:00
#ifndef EXCLUDE_INSIGHT
if (this->environmentConfig->insightConfig.has_value()) {
this->insightConfig = this->environmentConfig->insightConfig.value();
2022-02-06 13:45:35 +00:00
} else if (this->projectConfig->insightConfig.has_value()) {
this->insightConfig = this->projectConfig->insightConfig.value();
2022-02-06 13:45:35 +00:00
} else {
throw InvalidConfig("Insight configuration missing.");
}
2023-05-10 19:53:39 +01:00
#endif
if (this->environmentConfig->debugServerConfig.has_value()) {
this->debugServerConfig = this->environmentConfig->debugServerConfig.value();
2022-02-06 13:45:35 +00:00
} else if (this->projectConfig->debugServerConfig.has_value()) {
this->debugServerConfig = this->projectConfig->debugServerConfig.value();
2022-02-06 13:45:35 +00:00
} else {
throw InvalidConfig("Debug server configuration missing.");
}
}
2021-04-04 21:04:12 +01:00
int Application::presentHelpText() {
/*
* Silence all logging here, as we're just to display the help text and then exit the application. Any
* further logging will just be noise.
*/
Logger::silence();
2021-04-04 21:04:12 +01:00
2022-07-23 16:13:08 +01:00
// The file help.txt is included in Bloom's binary, as a resource. See the root-level CMakeLists.txt for more.
auto helpFile = QFile(QString::fromStdString(Services::PathService::compiledResourcesPath() + "/resources/help.txt"));
2021-04-04 21:04:12 +01:00
if (!helpFile.open(QIODevice::ReadOnly)) {
// This should never happen - if it does, something has gone very wrong
throw Exception(
"Failed to open help file - please report this issue at " + Services::PathService::homeDomainName()
+ "/report-issue"
);
}
2021-04-04 21:04:12 +01:00
std::cout << "Bloom v" << Application::VERSION.toString() << "\n";
std::cout << QTextStream(&helpFile).readAll().toUtf8().constData() << "\n";
return EXIT_SUCCESS;
}
2021-04-04 21:04:12 +01:00
int Application::presentVersionText() {
Logger::silence();
std::cout << "Bloom v" << Application::VERSION.toString() << "\n";
2021-04-24 16:22:04 +01:00
2023-05-10 19:53:39 +01:00
#ifdef EXCLUDE_INSIGHT
std::cout << "Insight has been excluded from this build.\n";
#endif
2021-04-24 16:22:04 +01:00
#ifdef BLOOM_DEBUG_BUILD
std::cout << "DEBUG BUILD - Compilation timestamp: " << __DATE__ << " " << __TIME__ << "\n";
2021-04-24 16:22:04 +01:00
#endif
std::cout << Services::PathService::homeDomainName() + "/\n";
std::cout << "Nav Mohammed\n";
return EXIT_SUCCESS;
2021-04-04 21:04:12 +01:00
}
2022-05-06 19:30:43 +01:00
int Application::presentVersionMachineText() {
Logger::silence();
2023-05-10 19:53:39 +01:00
auto insightAvailable = true;
#ifdef EXCLUDE_INSIGHT
insightAvailable = false;
#endif
2022-05-06 19:30:43 +01:00
std::cout << QJsonDocument(QJsonObject({
{"version", QString::fromStdString(Application::VERSION.toString())},
{"components", QJsonObject({
{"major", Application::VERSION.major},
{"minor", Application::VERSION.minor},
{"patch", Application::VERSION.patch},
2022-05-06 19:30:43 +01:00
})},
2023-05-10 19:53:39 +01:00
{"insightAvailable", insightAvailable},
2022-05-06 19:30:43 +01:00
})).toJson().toStdString();
return EXIT_SUCCESS;
}
int Application::initProject() {
auto configFile = QFile(QString::fromStdString(Services::PathService::projectConfigPath()));
2021-04-04 21:04:12 +01:00
if (configFile.exists()) {
throw Exception("Bloom configuration file (bloom.yaml) already exists in working directory.");
}
2021-04-04 21:04:12 +01:00
/*
2022-07-23 16:13:08 +01:00
* The file bloom.template.yaml is just a template Bloom config file that is included in Bloom's binary, as a
* resource. See the root-level CMakeLists.txt for more.
*
* We simply copy the template file into the user's working directory.
*/
auto templateConfigFile = QFile(
QString::fromStdString(Services::PathService::compiledResourcesPath()+ "/resources/bloom.template.yaml")
);
2021-04-04 21:04:12 +01:00
if (!templateConfigFile.open(QIODevice::ReadOnly)) {
throw Exception(
"Failed to open template configuration file - please report this issue at "
+ Services::PathService::homeDomainName() + "/report-issue"
);
}
2021-04-04 21:04:12 +01:00
if (!configFile.open(QIODevice::ReadWrite)) {
throw Exception("Failed to create Bloom configuration file (bloom.yaml)");
}
2021-04-04 21:04:12 +01:00
configFile.write(templateConfigFile.readAll());
configFile.close();
templateConfigFile.close();
Logger::info("Bloom configuration file (bloom.yaml) created in working directory.");
return EXIT_SUCCESS;
}
void Application::startSignalHandler() {
this->signalHandlerThread = std::thread(&SignalHandler::run, std::ref(this->signalHandler));
}
2021-04-04 21:04:12 +01:00
void Application::stopSignalHandler() {
2022-05-23 23:50:10 +01:00
const auto shThreadState = this->signalHandler.getThreadState();
if (shThreadState != ThreadState::STOPPED && shThreadState != ThreadState::UNINITIALISED) {
this->signalHandler.triggerShutdown();
2021-04-04 21:04:12 +01:00
/*
* Send meaningless signal to the SignalHandler thread to have it shutdown. The signal will pull it out of
* a blocking state and allow it to action the shutdown. See SignalHandler::run() for more.
*/
pthread_kill(this->signalHandlerThread.native_handle(), SIGUSR1);
}
2021-04-04 21:04:12 +01:00
if (this->signalHandlerThread.joinable()) {
Logger::debug("Joining SignalHandler thread");
this->signalHandlerThread.join();
Logger::debug("SignalHandler thread joined");
}
2021-04-04 21:04:12 +01:00
}
void Application::startTargetController() {
this->targetController = std::make_unique<TargetController::TargetControllerComponent>(
this->projectConfig.value(),
this->environmentConfig.value()
);
this->targetControllerThread = std::thread(
&TargetController::TargetControllerComponent::run,
this->targetController.get()
2021-04-04 21:04:12 +01:00
);
2022-07-09 14:09:05 +01:00
const auto tcStateChangeEvent = this->applicationEventListener->waitForEvent<
Events::TargetControllerThreadStateChanged
>();
if (!tcStateChangeEvent.has_value() || tcStateChangeEvent->get()->getState() != ThreadState::READY) {
2022-08-27 17:56:55 +01:00
throw Exception("TargetController failed to start up");
}
2021-04-04 21:04:12 +01:00
}
void Application::stopTargetController() {
if (this->targetController == nullptr) {
return;
}
2023-05-26 00:23:12 +01:00
const auto tcThreadState = this->targetController->getThreadState();
if (tcThreadState == ThreadState::STARTING || tcThreadState == ThreadState::READY) {
2022-03-20 17:37:36 +00:00
EventManager::triggerEvent(std::make_shared<Events::ShutdownTargetController>());
this->applicationEventListener->waitForEvent<Events::TargetControllerThreadStateChanged>(
std::chrono::milliseconds(10000)
);
}
if (this->targetControllerThread.joinable()) {
Logger::debug("Joining TargetController thread");
this->targetControllerThread.join();
Logger::debug("TargetController thread joined");
}
2021-04-04 21:04:12 +01:00
}
void Application::startDebugServer() {
this->debugServer = std::make_unique<DebugServer::DebugServerComponent>(
this->debugServerConfig.value()
);
2021-04-04 21:04:12 +01:00
this->debugServerThread = std::thread(
&DebugServer::DebugServerComponent::run,
this->debugServer.get()
);
2021-04-04 21:04:12 +01:00
2022-07-09 14:09:05 +01:00
const auto dsStateChangeEvent = this->applicationEventListener->waitForEvent<
Events::DebugServerThreadStateChanged
>();
2021-04-04 21:04:12 +01:00
if (!dsStateChangeEvent.has_value() || dsStateChangeEvent->get()->getState() != ThreadState::READY) {
2022-08-27 17:56:55 +01:00
throw Exception("DebugServer failed to start up");
}
2021-04-04 21:04:12 +01:00
}
void Application::stopDebugServer() {
if (this->debugServer == nullptr) {
return;
}
2022-07-09 14:09:05 +01:00
const auto debugServerState = this->debugServer->getThreadState();
if (debugServerState == ThreadState::STARTING || debugServerState == ThreadState::READY) {
2022-03-20 17:37:36 +00:00
EventManager::triggerEvent(std::make_shared<Events::ShutdownDebugServer>());
this->applicationEventListener->waitForEvent<Events::DebugServerThreadStateChanged>(
std::chrono::milliseconds(5000)
);
}
if (this->debugServerThread.joinable()) {
Logger::debug("Joining DebugServer thread");
this->debugServerThread.join();
Logger::debug("DebugServer thread joined");
}
2021-04-04 21:04:12 +01:00
}
void Application::dispatchEvents() {
this->applicationEventListener->dispatchCurrentEvents();
}
void Application::checkBloomVersion() {
const auto currentVersionNumber = Application::VERSION;
auto* networkAccessManager = new QNetworkAccessManager(this);
auto queryVersionEndpointUrl = QUrl(QString::fromStdString(Services::PathService::homeDomainName() + "/latest-version"));
queryVersionEndpointUrl.setScheme("http");
queryVersionEndpointUrl.setQuery(QUrlQuery({
{"currentVersionNumber", QString::fromStdString(currentVersionNumber.toString())}
}));
QObject::connect(
networkAccessManager,
&QNetworkAccessManager::finished,
this,
[this, currentVersionNumber] (QNetworkReply* response) {
const auto jsonResponseObject = QJsonDocument::fromJson(response->readAll()).object();
const auto latestVersionNumber = VersionNumber(jsonResponseObject.value("latestVersionNumber").toString());
if (latestVersionNumber > currentVersionNumber) {
Logger::warning(
"Bloom v" + latestVersionNumber.toString()
+ " is available to download - upgrade via " + Services::PathService::homeDomainName()
);
}
}
);
networkAccessManager->get(QNetworkRequest(queryVersionEndpointUrl));
}
#ifndef EXCLUDE_INSIGHT
void Application::activateInsight() {
assert(!this->insight);
this->insight = std::make_unique<Insight>(
*(this->applicationEventListener),
this->projectConfig.value(),
this->environmentConfig.value(),
this->insightConfig.value(),
this->projectSettings.value().insightSettings,
&(this->qtApplication)
);
this->insight->activate();
}
void Application::onInsightActivationRequest(const Events::InsightActivationRequested&) {
if (this->insight) {
// Insight has already been activated
this->insight->showMainWindow();
return;
}
this->activateInsight();
}
#endif
2022-02-09 17:49:25 +00:00
void Application::onShutdownApplicationRequest(const Events::ShutdownApplication&) {
Logger::debug("ShutdownApplication event received.");
this->shutdown();
}
void Application::onTargetControllerThreadStateChanged(const Events::TargetControllerThreadStateChanged& event) {
if (event.getState() == ThreadState::STOPPED || event.getState() == ThreadState::SHUTDOWN_INITIATED) {
// TargetController has unexpectedly shutdown.
this->shutdown();
}
2021-04-04 21:04:12 +01:00
}
void Application::onDebugServerThreadStateChanged(const Events::DebugServerThreadStateChanged& event) {
if (event.getState() == ThreadState::STOPPED || event.getState() == ThreadState::SHUTDOWN_INITIATED) {
// DebugServer has unexpectedly shutdown - it must have encountered a fatal error.
this->shutdown();
}
2021-04-04 21:04:12 +01:00
}
void Application::onDebugSessionFinished(const Events::DebugSessionFinished& event) {
if (this->environmentConfig->shutdownPostDebugSession || Services::ProcessService::isManagedByClion()) {
this->shutdown();
}
}
2021-04-04 21:04:12 +01:00
}