magpie/root.cpp

86 lines
2.4 KiB
C++

// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "root.h"
#include <QSettings>
Root::Root(const QUrl& root, int& argc, char* argv[]) :
QGuiApplication(argc, argv),
root(root),
engine(),
context(engine.rootContext()),
api()
{
std::cout << "Starting Magpie..." << std::endl;
setOrganizationName("macaw.me");
setOrganizationDomain("macaw.me");
setApplicationName("magpie");
setApplicationDisplayName("Magpie");
setApplicationVersion("0.0.1");
setDesktopFileName("magpie");
connect(&engine, &QQmlApplicationEngine::objectCreated,
this, &Root::onObjectCreated,
Qt::QueuedConnection
);
QSettings settings;
api.setAddress(settings.value("address").toUrl());
QString acc = settings.value("accessToken").toString();
QString ren = settings.value("renewToken").toString();
if (!acc.isEmpty() && !ren.isEmpty())
api.setTokens(acc, ren);
qRegisterMetaType<API>("API");
connect(&api, &API::addressChanged, this, &Root::onAPIAddressChanged);
connect(&api, &API::storeTokens, this, &Root::onStoreTokens);
qmlRegisterSingletonType<API>("magpie.API", 1, 0, "API", [this] (QQmlEngine *engine, QJSEngine *scriptEngine) {
return &api;
});
engine.addImportPath(":/");
engine.load(root);
if (engine.rootObjects().isEmpty())
throw std::runtime_error("Couldn't looad root qml object");
}
Root::~Root() {
}
bool Root::notify(QObject* receiver, QEvent* e) {
try {
return QGuiApplication::notify(receiver, e);
} catch (const std::exception& e) {
std::cout << "Caught an exception, error message:\n" << e.what() << std::endl;
} catch (const int& e) {
std::cout << "Caught int exception: " << e << std::endl;
} catch (...) {
std::cout << "Caught an exception" << std::endl;
}
std::cout << "Magpie is quiting..." << std::endl;
exit(1);
return false;
}
void Root::onObjectCreated(QObject* obj, const QUrl& objUrl) {
if (!obj && objUrl == root)
exit(-2);
}
void Root::onAPIAddressChanged(const QUrl& url) {
QSettings settings;
settings.setValue("address", url);
}
void Root::onStoreTokens(const QString& access, const QString& renew) {
QSettings settings;
settings.setValue("accessToken", access);
settings.setValue("renewToken", renew);
}