Run clang-format on all cpp/h files

NO_CHANGELOG
This commit is contained in:
Ahmad Samir 2021-03-05 20:15:32 +02:00
parent cce6198bb9
commit c0274df69a
222 changed files with 3253 additions and 3770 deletions

View File

@ -13,8 +13,8 @@
#include <KConfigLoader> #include <KConfigLoader>
#include <QQmlEngine>
#include <QQmlComponent> #include <QQmlComponent>
#include <QQmlEngine>
void ConfigModelTest::configSchemeFromPackage() void ConfigModelTest::configSchemeFromPackage()
{ {
@ -37,7 +37,7 @@ void ConfigModelTest::configSchemeFromPackage()
QCOMPARE(configModel->get(0).toMap().value(QStringLiteral("icon")).toString(), QStringLiteral("plasma")); QCOMPARE(configModel->get(0).toMap().value(QStringLiteral("icon")).toString(), QStringLiteral("plasma"));
QCOMPARE(configModel->get(0).toMap().value(QStringLiteral("source")).toString(), QStringLiteral("ConfigGeneral.qml")); QCOMPARE(configModel->get(0).toMap().value(QStringLiteral("source")).toString(), QStringLiteral("ConfigGeneral.qml"));
QCOMPARE(configModel->get(0).toMap().value(QStringLiteral("pluginName")).toString(), QString()); QCOMPARE(configModel->get(0).toMap().value(QStringLiteral("pluginName")).toString(), QString());
QVERIFY(!configModel->get(0).toMap().value(QStringLiteral("kcm")).value<void*>()); QVERIFY(!configModel->get(0).toMap().value(QStringLiteral("kcm")).value<void *>());
delete component; delete component;
delete applet; delete applet;
@ -108,4 +108,3 @@ void ConfigModelTest::notEmptySourceWithApplet()
} }
QTEST_MAIN(ConfigModelTest) QTEST_MAIN(ConfigModelTest)

View File

@ -21,6 +21,4 @@ private Q_SLOTS:
void configSchemeFromPackage(); void configSchemeFromPackage();
void emptySourceWithApplet(); void emptySourceWithApplet();
void notEmptySourceWithApplet(); void notEmptySourceWithApplet();
}; };

View File

@ -5,16 +5,15 @@
*/ */
#include "coronatest.h" #include "coronatest.h"
#include <KSycoca>
#include <KActionCollection> #include <KActionCollection>
#include <QStandardPaths> #include <KSycoca>
#include <QAction> #include <QAction>
#include <QApplication> #include <QApplication>
#include <QSignalSpy>
#include <QRandomGenerator>
#include <QProcess> #include <QProcess>
Plasma::Applet *SimpleLoader::internalLoadApplet(const QString &name, uint appletId, #include <QRandomGenerator>
const QVariantList &args) #include <QSignalSpy>
#include <QStandardPaths>
Plasma::Applet *SimpleLoader::internalLoadApplet(const QString &name, uint appletId, const QVariantList &args)
{ {
Q_UNUSED(args) Q_UNUSED(args)
if (name == QLatin1String("simpleapplet")) { if (name == QLatin1String("simpleapplet")) {
@ -35,13 +34,13 @@ SimpleCorona::SimpleCorona(QObject *parent)
} }
SimpleCorona::~SimpleCorona() SimpleCorona::~SimpleCorona()
{} {
}
QRect SimpleCorona::screenGeometry(int screen) const QRect SimpleCorona::screenGeometry(int screen) const
{ {
//completely arbitrary, still not tested // completely arbitrary, still not tested
return QRect(100*screen, 100, 100, 100); return QRect(100 * screen, 100, 100, 100);
} }
int SimpleCorona::screenForContainment(const Plasma::Containment *c) const int SimpleCorona::screenForContainment(const Plasma::Containment *c) const
@ -52,10 +51,10 @@ int SimpleCorona::screenForContainment(const Plasma::Containment *c) const
return 0; return 0;
} }
SimpleApplet::SimpleApplet(QObject *parent , const QString &serviceId, uint appletId) SimpleApplet::SimpleApplet(QObject *parent, const QString &serviceId, uint appletId)
: Plasma::Applet(parent, serviceId, appletId) : Plasma::Applet(parent, serviceId, appletId)
{ {
//updateConstraints(Plasma::Types::UiReadyConstraint); // updateConstraints(Plasma::Types::UiReadyConstraint);
m_timer.setSingleShot(true); m_timer.setSingleShot(true);
m_timer.setInterval(QRandomGenerator::global()->bounded((500 + 1) - 100) + 100); m_timer.setInterval(QRandomGenerator::global()->bounded((500 + 1) - 100) + 100);
m_timer.start(); m_timer.start();
@ -64,11 +63,10 @@ SimpleApplet::SimpleApplet(QObject *parent , const QString &serviceId, uint appl
}); });
} }
SimpleContainment::SimpleContainment(QObject *parent, const QString &serviceId, uint appletId)
SimpleContainment::SimpleContainment(QObject *parent , const QString &serviceId, uint appletId)
: Plasma::Containment(parent, serviceId, appletId) : Plasma::Containment(parent, serviceId, appletId)
{ {
//updateConstraints(Plasma::Types::UiReadyConstraint); // updateConstraints(Plasma::Types::UiReadyConstraint);
m_timer.setSingleShot(true); m_timer.setSingleShot(true);
m_timer.setInterval(QRandomGenerator::global()->bounded((500 + 1) - 100) + 100); m_timer.setInterval(QRandomGenerator::global()->bounded((500 + 1) - 100) + 100);
m_timer.start(); m_timer.start();
@ -77,10 +75,10 @@ SimpleContainment::SimpleContainment(QObject *parent , const QString &serviceId,
}); });
} }
SimpleNoScreenContainment::SimpleNoScreenContainment(QObject *parent , const QString &serviceId, uint appletId) SimpleNoScreenContainment::SimpleNoScreenContainment(QObject *parent, const QString &serviceId, uint appletId)
: Plasma::Containment(parent, serviceId, appletId) : Plasma::Containment(parent, serviceId, appletId)
{ {
//This containment will *never* be isUiReady() // This containment will *never* be isUiReady()
} }
static void runKBuildSycoca() static void runKBuildSycoca()
@ -100,7 +98,6 @@ static void runKBuildSycoca()
QCOMPARE(proc.exitStatus(), QProcess::NormalExit); QCOMPARE(proc.exitStatus(), QProcess::NormalExit);
} }
void CoronaTest::initTestCase() void CoronaTest::initTestCase()
{ {
if (!KSycoca::isAvailable()) { if (!KSycoca::isAvailable()) {
@ -140,21 +137,18 @@ void CoronaTest::restore()
break; break;
} }
} }
} }
void CoronaTest::checkOrder() void CoronaTest::checkOrder()
{ {
QCOMPARE(m_corona->containments().count(), 3); QCOMPARE(m_corona->containments().count(), 3);
//check containments order // check containments order
QCOMPARE(m_corona->containments().at(0)->id(), (uint)1); QCOMPARE(m_corona->containments().at(0)->id(), (uint)1);
QCOMPARE(m_corona->containments().at(1)->id(), (uint)4); QCOMPARE(m_corona->containments().at(1)->id(), (uint)4);
QCOMPARE(m_corona->containments().at(2)->id(), (uint)5); QCOMPARE(m_corona->containments().at(2)->id(), (uint)5);
//check applets order // check applets order
QCOMPARE(m_corona->containments().at(0)->applets().count(), 2); QCOMPARE(m_corona->containments().at(0)->applets().count(), 2);
QCOMPARE(m_corona->containments().at(0)->applets().at(0)->id(), (uint)2); QCOMPARE(m_corona->containments().at(0)->applets().at(0)->id(), (uint)2);
QCOMPARE(m_corona->containments().at(0)->applets().at(1)->id(), (uint)3); QCOMPARE(m_corona->containments().at(0)->applets().at(1)->id(), (uint)3);
@ -177,9 +171,9 @@ void CoronaTest::addRemoveApplets()
m_corona->containments().at(0)->createApplet(QStringLiteral("invalid")); m_corona->containments().at(0)->createApplet(QStringLiteral("invalid"));
QCOMPARE(m_corona->containments().at(0)->applets().count(), 3); QCOMPARE(m_corona->containments().at(0)->applets().count(), 3);
//remove action present // remove action present
QVERIFY(m_corona->containments().at(0)->applets().at(0)->actions()->action(QStringLiteral("remove"))); QVERIFY(m_corona->containments().at(0)->applets().at(0)->actions()->action(QStringLiteral("remove")));
//kill an applet // kill an applet
m_corona->containments().at(0)->applets().at(0)->destroy(); m_corona->containments().at(0)->applets().at(0)->destroy();
QSignalSpy spy(m_corona->containments().at(0)->applets().at(0), SIGNAL(destroyed())); QSignalSpy spy(m_corona->containments().at(0)->applets().at(0), SIGNAL(destroyed()));
@ -187,11 +181,11 @@ void CoronaTest::addRemoveApplets()
QCOMPARE(m_corona->containments().at(0)->applets().count(), 2); QCOMPARE(m_corona->containments().at(0)->applets().count(), 2);
} }
//this test has to be the last, since systemimmutability // this test has to be the last, since systemimmutability
//can't be programmatically unlocked // can't be programmatically unlocked
void CoronaTest::immutability() void CoronaTest::immutability()
{ {
//immutability // immutability
QCOMPARE(m_corona->immutability(), Plasma::Types::Mutable); QCOMPARE(m_corona->immutability(), Plasma::Types::Mutable);
m_corona->setImmutability(Plasma::Types::UserImmutable); m_corona->setImmutability(Plasma::Types::UserImmutable);
QCOMPARE(m_corona->immutability(), Plasma::Types::UserImmutable); QCOMPARE(m_corona->immutability(), Plasma::Types::UserImmutable);
@ -229,7 +223,7 @@ void CoronaTest::immutability()
} }
} }
//can't unlock systemimmutable // can't unlock systemimmutable
m_corona->setImmutability(Plasma::Types::Mutable); m_corona->setImmutability(Plasma::Types::Mutable);
QCOMPARE(m_corona->immutability(), Plasma::Types::SystemImmutable); QCOMPARE(m_corona->immutability(), Plasma::Types::SystemImmutable);
@ -244,4 +238,3 @@ void CoronaTest::immutability()
} }
QTEST_MAIN(CoronaTest) QTEST_MAIN(CoronaTest)

View File

@ -16,17 +16,15 @@
class SimpleLoader : public Plasma::PluginLoader class SimpleLoader : public Plasma::PluginLoader
{ {
protected: protected:
virtual Plasma::Applet *internalLoadApplet(const QString &name, uint appletId = 0, virtual Plasma::Applet *internalLoadApplet(const QString &name, uint appletId = 0, const QVariantList &args = QVariantList()) override;
const QVariantList &args = QVariantList()) override;
}; };
class SimpleCorona : public Plasma::Corona class SimpleCorona : public Plasma::Corona
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit SimpleCorona(QObject * parent = nullptr); explicit SimpleCorona(QObject *parent = nullptr);
~SimpleCorona(); ~SimpleCorona();
QRect screenGeometry(int) const override; QRect screenGeometry(int) const override;
@ -39,6 +37,7 @@ class SimpleApplet : public Plasma::Applet
public: public:
explicit SimpleApplet(QObject *parent = nullptr, const QString &serviceId = QString(), uint appletId = 0); explicit SimpleApplet(QObject *parent = nullptr, const QString &serviceId = QString(), uint appletId = 0);
private: private:
QTimer m_timer; QTimer m_timer;
}; };
@ -49,6 +48,7 @@ class SimpleContainment : public Plasma::Containment
public: public:
explicit SimpleContainment(QObject *parent = nullptr, const QString &serviceId = QString(), uint appletId = 0); explicit SimpleContainment(QObject *parent = nullptr, const QString &serviceId = QString(), uint appletId = 0);
private: private:
QTimer m_timer; QTimer m_timer;
}; };
@ -82,4 +82,3 @@ private:
}; };
#endif #endif

View File

@ -23,15 +23,15 @@ void DialogNativeTest::initTestCase()
m_panel = new QQuickView; m_panel = new QQuickView;
m_panel->setGeometry(0, 0, 50, 50); m_panel->setGeometry(0, 0, 50, 50);
m_panel->setFlags(Qt::FramelessWindowHint|Qt::WindowDoesNotAcceptFocus); m_panel->setFlags(Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus);
m_panel2 = new QQuickView; m_panel2 = new QQuickView;
m_panel2->setGeometry(100, 0, 50, 50); m_panel2->setGeometry(100, 0, 50, 50);
m_panel2->setFlags(Qt::FramelessWindowHint|Qt::WindowDoesNotAcceptFocus); m_panel2->setFlags(Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus);
m_panel3 = new QQuickView; m_panel3 = new QQuickView;
m_panel3->setGeometry(200, 0, 50, 50); m_panel3->setGeometry(200, 0, 50, 50);
m_panel3->setFlags(Qt::FramelessWindowHint|Qt::WindowDoesNotAcceptFocus); m_panel3->setFlags(Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus);
m_content = new QQuickItem; m_content = new QQuickItem;
m_content->setWidth(100); m_content->setWidth(100);

View File

@ -6,14 +6,12 @@
#ifndef DIALOGNATIVETEST_H #ifndef DIALOGNATIVETEST_H
#define DIALOGNATIVETEST_H #define DIALOGNATIVETEST_H
#include <QTest>
#include <QQuickView>
#include <QQuickItem> #include <QQuickItem>
#include <QQuickView>
#include <QTest>
#include "plasmaquick/dialog.h" #include "plasmaquick/dialog.h"
class DialogNativeTest : public QObject class DialogNativeTest : public QObject
{ {
Q_OBJECT Q_OBJECT
@ -37,4 +35,3 @@ private:
}; };
#endif #endif

View File

@ -8,39 +8,37 @@
#include <plasma.h> #include <plasma.h>
#include <QQmlEngine>
#include <QQmlContext> #include <QQmlContext>
#include <QQmlEngine>
#include <QSignalSpy> #include <QSignalSpy>
// this test checks that we don't set visible to true until after we set the window flags
//this test checks that we don't set visible to true until after we set the window flags
void DialogQmlTest::loadAndShow() void DialogQmlTest::loadAndShow()
{ {
QQmlEngine engine; QQmlEngine engine;
QByteArray dialogQml = QByteArray dialogQml =
"import QtQuick 2.0\n" "import QtQuick 2.0\n"
"import org.kde.plasma.core 2.0 as PlasmaCore\n" "import org.kde.plasma.core 2.0 as PlasmaCore\n"
"\n" "\n"
"PlasmaCore.Dialog {\n" "PlasmaCore.Dialog {\n"
" id: root\n" " id: root\n"
"\n" "\n"
" location: true && PlasmaCore.Types.TopEdge\n" " location: true && PlasmaCore.Types.TopEdge\n"
" visible: true && true\n" " visible: true && true\n"
" type: true && PlasmaCore.Dialog.Notification\n" " type: true && PlasmaCore.Dialog.Notification\n"
"\n" "\n"
" mainItem: Rectangle {\n" " mainItem: Rectangle {\n"
" width: 200\n" " width: 200\n"
" height: 200\n" " height: 200\n"
" }\n" " }\n"
"}\n"; "}\n";
//we use true && Value to force it to be a complex binding, which won't be evaluated in
//component.beginCreate
//the bug still appears without this, but we need to delay it in this test
//so we can connect to the visibleChanged signal
// we use true && Value to force it to be a complex binding, which won't be evaluated in
// component.beginCreate
// the bug still appears without this, but we need to delay it in this test
// so we can connect to the visibleChanged signal
QQmlComponent component(&engine); QQmlComponent component(&engine);
@ -48,13 +46,13 @@ void DialogQmlTest::loadAndShow()
component.setData(dialogQml, QUrl(QStringLiteral("test://dialogTest"))); component.setData(dialogQml, QUrl(QStringLiteral("test://dialogTest")));
spy.wait(); spy.wait();
PlasmaQuick::Dialog *dialog = qobject_cast< PlasmaQuick::Dialog* >(component.beginCreate(engine.rootContext())); PlasmaQuick::Dialog *dialog = qobject_cast<PlasmaQuick::Dialog *>(component.beginCreate(engine.rootContext()));
qDebug() << component.errorString(); qDebug() << component.errorString();
Q_ASSERT(dialog); Q_ASSERT(dialog);
m_dialogShown = false; m_dialogShown = false;
//this will be called during component.completeCreate // this will be called during component.completeCreate
auto c = connect(dialog, &QWindow::visibleChanged, [=]() { auto c = connect(dialog, &QWindow::visibleChanged, [=]() {
m_dialogShown = true; m_dialogShown = true;
QCOMPARE(dialog->type(), PlasmaQuick::Dialog::Notification); QCOMPARE(dialog->type(), PlasmaQuick::Dialog::Notification);
@ -64,12 +62,10 @@ void DialogQmlTest::loadAndShow()
component.completeCreate(); component.completeCreate();
QCOMPARE(m_dialogShown, true); QCOMPARE(m_dialogShown, true);
//disconnect on visible changed before we delete the dialog // disconnect on visible changed before we delete the dialog
disconnect(c); disconnect(c);
delete dialog; delete dialog;
} }
QTEST_MAIN(DialogQmlTest) QTEST_MAIN(DialogQmlTest)

View File

@ -10,18 +10,15 @@
#include "plasmaquick/dialog.h" #include "plasmaquick/dialog.h"
class DialogQmlTest : public QObject class DialogQmlTest : public QObject
{ {
Q_OBJECT Q_OBJECT
private Q_SLOTS: private Q_SLOTS:
void loadAndShow(); void loadAndShow();
private: private:
bool m_dialogShown; bool m_dialogShown;
}; };
#endif #endif

View File

@ -5,8 +5,8 @@
*/ */
#include "dialogstatetest.h" #include "dialogstatetest.h"
#include <QSignalSpy>
#include <KWindowSystem> #include <KWindowSystem>
#include <QSignalSpy>
void DialogStateTest::initTestCase() void DialogStateTest::initTestCase()
{ {

View File

@ -28,4 +28,3 @@ private:
}; };
#endif #endif

View File

@ -12,25 +12,25 @@
#include <QTimer> #include <QTimer>
DynamicTreeModel::DynamicTreeModel(QObject *parent) DynamicTreeModel::DynamicTreeModel(QObject *parent)
: QAbstractItemModel(parent), : QAbstractItemModel(parent)
nextId(1) , nextId(1)
{ {
} }
QModelIndex DynamicTreeModel::index(int row, int column, const QModelIndex &parent) const QModelIndex DynamicTreeModel::index(int row, int column, const QModelIndex &parent) const
{ {
// if (column != 0) // if (column != 0)
// return QModelIndex(); // return QModelIndex();
if (column < 0 || row < 0) { if (column < 0 || row < 0) {
return QModelIndex(); return QModelIndex();
} }
QList<QList<qint64> > childIdColumns = m_childItems.value(parent.internalId()); QList<QList<qint64>> childIdColumns = m_childItems.value(parent.internalId());
const qint64 grandParent = findParentId(parent.internalId()); const qint64 grandParent = findParentId(parent.internalId());
if (grandParent >= 0) { if (grandParent >= 0) {
QList<QList<qint64> > parentTable = m_childItems.value(grandParent); QList<QList<qint64>> parentTable = m_childItems.value(grandParent);
Q_ASSERT(parent.column() < parentTable.size()); Q_ASSERT(parent.column() < parentTable.size());
QList<qint64> parentSiblings = parentTable.at(parent.column()); QList<qint64> parentSiblings = parentTable.at(parent.column());
Q_ASSERT(parent.row() < parentSiblings.size()); Q_ASSERT(parent.row() < parentSiblings.size());
@ -53,7 +53,6 @@ QModelIndex DynamicTreeModel::index(int row, int column, const QModelIndex &pare
qint64 id = rowIds.at(row); qint64 id = rowIds.at(row);
return createIndex(row, column, reinterpret_cast<void *>(id)); return createIndex(row, column, reinterpret_cast<void *>(id));
} }
qint64 DynamicTreeModel::findParentId(qint64 searchId) const qint64 DynamicTreeModel::findParentId(qint64 searchId) const
@ -62,10 +61,10 @@ qint64 DynamicTreeModel::findParentId(qint64 searchId) const
return -1; return -1;
} }
QHashIterator<qint64, QList<QList<qint64> > > i(m_childItems); QHashIterator<qint64, QList<QList<qint64>>> i(m_childItems);
while (i.hasNext()) { while (i.hasNext()) {
i.next(); i.next();
QListIterator<QList<qint64> > j(i.value()); QListIterator<QList<qint64>> j(i.value());
while (j.hasNext()) { while (j.hasNext()) {
QList<qint64> l = j.next(); QList<qint64> l = j.next();
if (l.contains(searchId)) { if (l.contains(searchId)) {
@ -100,12 +99,11 @@ QModelIndex DynamicTreeModel::parent(const QModelIndex &index) const
int row = childList.indexOf(parentId); int row = childList.indexOf(parentId);
return createIndex(row, column, reinterpret_cast<void *>(parentId)); return createIndex(row, column, reinterpret_cast<void *>(parentId));
} }
int DynamicTreeModel::rowCount(const QModelIndex &index) const int DynamicTreeModel::rowCount(const QModelIndex &index) const
{ {
QList<QList<qint64> > cols = m_childItems.value(index.internalId()); QList<QList<qint64>> cols = m_childItems.value(index.internalId());
if (cols.size() == 0) { if (cols.size() == 0) {
return 0; return 0;
@ -120,7 +118,7 @@ int DynamicTreeModel::rowCount(const QModelIndex &index) const
int DynamicTreeModel::columnCount(const QModelIndex &index) const int DynamicTreeModel::columnCount(const QModelIndex &index) const
{ {
// Q_UNUSED(index); // Q_UNUSED(index);
return m_childItems.value(index.internalId()).size(); return m_childItems.value(index.internalId()).size();
} }
@ -146,9 +144,12 @@ void DynamicTreeModel::clear()
} }
ModelChangeCommand::ModelChangeCommand(DynamicTreeModel *model, QObject *parent) ModelChangeCommand::ModelChangeCommand(DynamicTreeModel *model, QObject *parent)
: QObject(parent), m_model(model), m_numCols(1), m_startRow(-1), m_endRow(-1) : QObject(parent)
, m_model(model)
, m_numCols(1)
, m_startRow(-1)
, m_endRow(-1)
{ {
} }
QModelIndex ModelChangeCommand::findIndex(QList<int> rows) QModelIndex ModelChangeCommand::findIndex(QList<int> rows)
@ -166,7 +167,6 @@ QModelIndex ModelChangeCommand::findIndex(QList<int> rows)
ModelInsertCommand::ModelInsertCommand(DynamicTreeModel *model, QObject *parent) ModelInsertCommand::ModelInsertCommand(DynamicTreeModel *model, QObject *parent)
: ModelChangeCommand(model, parent) : ModelChangeCommand(model, parent)
{ {
} }
void ModelInsertCommand::doCommand() void ModelInsertCommand::doCommand()
@ -179,13 +179,12 @@ void ModelInsertCommand::doCommand()
if (m_model->m_childItems[parentId].size() <= col) { if (m_model->m_childItems[parentId].size() <= col) {
m_model->m_childItems[parentId].append(QList<qint64>()); m_model->m_childItems[parentId].append(QList<qint64>());
} }
// QString name = QUuid::createUuid().toString(); // QString name = QUuid::createUuid().toString();
qint64 id = m_model->newId(); qint64 id = m_model->newId();
QString name = QString::number(id); QString name = QString::number(id);
m_model->m_items.insert(id, name); m_model->m_items.insert(id, name);
m_model->m_childItems[parentId][col].insert(row, id); m_model->m_childItems[parentId][col].insert(row, id);
} }
} }
m_model->endInsertRows(); m_model->endInsertRows();
@ -194,7 +193,6 @@ void ModelInsertCommand::doCommand()
ModelMoveCommand::ModelMoveCommand(DynamicTreeModel *model, QObject *parent) ModelMoveCommand::ModelMoveCommand(DynamicTreeModel *model, QObject *parent)
: ModelChangeCommand(model, parent) : ModelChangeCommand(model, parent)
{ {
} }
bool ModelMoveCommand::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow) bool ModelMoveCommand::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow)
{ {
@ -243,12 +241,10 @@ void ModelMoveCommand::emitPostSignal()
ModelResetCommand::ModelResetCommand(DynamicTreeModel *model, QObject *parent) ModelResetCommand::ModelResetCommand(DynamicTreeModel *model, QObject *parent)
: ModelMoveCommand(model, parent) : ModelMoveCommand(model, parent)
{ {
} }
ModelResetCommand::~ModelResetCommand() ModelResetCommand::~ModelResetCommand()
{ {
} }
bool ModelResetCommand::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow) bool ModelResetCommand::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow)
@ -270,12 +266,10 @@ void ModelResetCommand::emitPostSignal()
ModelResetCommandFixed::ModelResetCommandFixed(DynamicTreeModel *model, QObject *parent) ModelResetCommandFixed::ModelResetCommandFixed(DynamicTreeModel *model, QObject *parent)
: ModelMoveCommand(model, parent) : ModelMoveCommand(model, parent)
{ {
} }
ModelResetCommandFixed::~ModelResetCommandFixed() ModelResetCommandFixed::~ModelResetCommandFixed()
{ {
} }
bool ModelResetCommandFixed::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow) bool ModelResetCommandFixed::emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow)
@ -294,4 +288,3 @@ void ModelResetCommandFixed::emitPostSignal()
{ {
m_model->endResetModel(); m_model->endResetModel();
} }

View File

@ -42,7 +42,7 @@ protected Q_SLOTS:
private: private:
QHash<qint64, QString> m_items; QHash<qint64, QString> m_items;
QHash<qint64, QList<QList<qint64> > > m_childItems; QHash<qint64, QList<QList<qint64>>> m_childItems;
qint64 nextId; qint64 nextId;
qint64 newId() qint64 newId()
{ {
@ -59,17 +59,17 @@ private:
friend class ModelMoveCommand; friend class ModelMoveCommand;
friend class ModelResetCommand; friend class ModelResetCommand;
friend class ModelResetCommandFixed; friend class ModelResetCommandFixed;
}; };
class ModelChangeCommand : public QObject class ModelChangeCommand : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit ModelChangeCommand(DynamicTreeModel *model, QObject *parent = nullptr); explicit ModelChangeCommand(DynamicTreeModel *model, QObject *parent = nullptr);
virtual ~ModelChangeCommand() {} virtual ~ModelChangeCommand()
{
}
void setAncestorRowNumbers(QList<int> rowNumbers) void setAncestorRowNumbers(QList<int> rowNumbers)
{ {
@ -101,7 +101,6 @@ protected:
int m_numCols; int m_numCols;
int m_startRow; int m_startRow;
int m_endRow; int m_endRow;
}; };
typedef QList<ModelChangeCommand *> ModelChangeCommandList; typedef QList<ModelChangeCommand *> ModelChangeCommandList;
@ -111,9 +110,10 @@ class ModelInsertCommand : public ModelChangeCommand
Q_OBJECT Q_OBJECT
public: public:
explicit ModelInsertCommand(DynamicTreeModel *model, QObject *parent = nullptr); explicit ModelInsertCommand(DynamicTreeModel *model, QObject *parent = nullptr);
virtual ~ModelInsertCommand() {} virtual ~ModelInsertCommand()
{
}
virtual void doCommand(); virtual void doCommand();
}; };
@ -124,7 +124,9 @@ class ModelMoveCommand : public ModelChangeCommand
public: public:
ModelMoveCommand(DynamicTreeModel *model, QObject *parent); ModelMoveCommand(DynamicTreeModel *model, QObject *parent);
virtual ~ModelMoveCommand() {} virtual ~ModelMoveCommand()
{
}
virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow); virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow);
@ -160,7 +162,6 @@ public:
virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow); virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow);
virtual void emitPostSignal(); virtual void emitPostSignal();
}; };
/** /**
@ -176,7 +177,6 @@ public:
virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow); virtual bool emitPreSignal(const QModelIndex &srcParent, int srcStart, int srcEnd, const QModelIndex &destParent, int destRow);
virtual void emitPostSignal(); virtual void emitPostSignal();
}; };
#endif #endif

View File

@ -7,8 +7,6 @@
#include "framesvgtest.h" #include "framesvgtest.h"
#include <QStandardPaths> #include <QStandardPaths>
void FrameSvgTest::initTestCase() void FrameSvgTest::initTestCase()
{ {
QStandardPaths::setTestModeEnabled(true); QStandardPaths::setTestModeEnabled(true);
@ -37,25 +35,25 @@ void FrameSvgTest::margins()
void FrameSvgTest::contentsRect() void FrameSvgTest::contentsRect()
{ {
m_frameSvg->resizeFrame(QSize(100,100)); m_frameSvg->resizeFrame(QSize(100, 100));
QCOMPARE(m_frameSvg->contentsRect(), QRectF(26, 26, 48, 48)); QCOMPARE(m_frameSvg->contentsRect(), QRectF(26, 26, 48, 48));
} }
void FrameSvgTest::repaintBlocked() void FrameSvgTest::repaintBlocked()
{ {
//check the properties to be correct even if set during a repaint blocked transaction // check the properties to be correct even if set during a repaint blocked transaction
m_frameSvg->setRepaintBlocked(true); m_frameSvg->setRepaintBlocked(true);
QVERIFY(m_frameSvg->isRepaintBlocked()); QVERIFY(m_frameSvg->isRepaintBlocked());
m_frameSvg->setElementPrefix("prefix"); m_frameSvg->setElementPrefix("prefix");
m_frameSvg->setEnabledBorders(Plasma::FrameSvg::TopBorder|Plasma::FrameSvg::LeftBorder); m_frameSvg->setEnabledBorders(Plasma::FrameSvg::TopBorder | Plasma::FrameSvg::LeftBorder);
m_frameSvg->resizeFrame(QSizeF(100,100)); m_frameSvg->resizeFrame(QSizeF(100, 100));
m_frameSvg->setRepaintBlocked(false); m_frameSvg->setRepaintBlocked(false);
QCOMPARE(m_frameSvg->prefix(), QString("prefix")); QCOMPARE(m_frameSvg->prefix(), QString("prefix"));
QCOMPARE(m_frameSvg->enabledBorders(), Plasma::FrameSvg::TopBorder|Plasma::FrameSvg::LeftBorder); QCOMPARE(m_frameSvg->enabledBorders(), Plasma::FrameSvg::TopBorder | Plasma::FrameSvg::LeftBorder);
QCOMPARE(m_frameSvg->frameSize(), QSizeF(100,100)); QCOMPARE(m_frameSvg->frameSize(), QSizeF(100, 100));
} }
void FrameSvgTest::setTheme() void FrameSvgTest::setTheme()

View File

@ -8,11 +8,8 @@
#include <QTest> #include <QTest>
#include "plasma/framesvg.h" #include "plasma/framesvg.h"
class FrameSvgTest : public QObject class FrameSvgTest : public QObject
{ {
Q_OBJECT Q_OBJECT
@ -33,4 +30,3 @@ private:
}; };
#endif #endif

View File

@ -7,18 +7,18 @@
#include "iconitemtest.h" #include "iconitemtest.h"
#include <QIcon> #include <QIcon>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent> #include <QQmlComponent>
#include <QQmlContext>
#include <QQmlEngine>
#include <QQuickItemGrabResult> #include <QQuickItemGrabResult>
#include <QSignalSpy> #include <QSignalSpy>
#include <KIconLoader>
#include <KIconEngine> #include <KIconEngine>
#include <KIconLoader>
#include <KIconTheme> #include <KIconTheme>
#include "plasma/theme.h"
#include "plasma/svg.h" #include "plasma/svg.h"
#include "plasma/theme.h"
#include "utils.h" #include "utils.h"
@ -40,11 +40,11 @@ void IconItemTest::initTestCase()
Plasma::TestUtils::installPlasmaTheme("breeze-light"); Plasma::TestUtils::installPlasmaTheme("breeze-light");
Plasma::TestUtils::installPlasmaTheme("breeze-dark"); Plasma::TestUtils::installPlasmaTheme("breeze-dark");
qputenv("XDG_DATA_DIRS", qgetenv("XDG_DATA_DIRS") + ":" + QFINDTESTDATA("data").toLocal8Bit()); qputenv("XDG_DATA_DIRS", qgetenv("XDG_DATA_DIRS") + ":" + QFINDTESTDATA("data").toLocal8Bit());
QString configPath = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation); QString configPath = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
if(!QDir(configPath).mkpath(QStringLiteral("."))) { if (!QDir(configPath).mkpath(QStringLiteral("."))) {
qFatal("Failed to create test configuration directory."); qFatal("Failed to create test configuration directory.");
} }
@ -99,7 +99,7 @@ QQuickItem *IconItemTest::createIconItem()
spy.wait(); spy.wait();
} }
QQuickItem *item = qobject_cast<QQuickItem*>(component.create(m_view->engine()->rootContext())); QQuickItem *item = qobject_cast<QQuickItem *>(component.create(m_view->engine()->rootContext()));
Q_ASSERT(item && qstrcmp(item->metaObject()->className(), "IconItem") == 0); Q_ASSERT(item && qstrcmp(item->metaObject()->className(), "IconItem") == 0);
item->setParentItem(m_view->rootObject()); item->setParentItem(m_view->rootObject());
return item; return item;
@ -143,7 +143,7 @@ void IconItemTest::loadPixmap()
QCOMPARE(sourcePixmap, item->property("source").value<QPixmap>()); QCOMPARE(sourcePixmap, item->property("source").value<QPixmap>());
} }
//tests setting icon from a QImage // tests setting icon from a QImage
void IconItemTest::loadImage() void IconItemTest::loadImage()
{ {
QScopedPointer<QQuickItem> item(createIconItem()); QScopedPointer<QQuickItem> item(createIconItem());
@ -308,7 +308,7 @@ void IconItemTest::themeChange()
QQuickItem *item1 = createIconItem(); QQuickItem *item1 = createIconItem();
item1->setProperty("animated", false); item1->setProperty("animated", false);
item1->setProperty("source", "zoom-fit-height"); item1->setProperty("source", "zoom-fit-height");
Plasma::Svg *svg1 = item1->findChild<Plasma::Svg*>(); Plasma::Svg *svg1 = item1->findChild<Plasma::Svg *>();
changeTheme(svg1->theme(), "breeze-light"); changeTheme(svg1->theme(), "breeze-light");
QImage img1 = grabImage(item1); QImage img1 = grabImage(item1);
changeTheme(svg1->theme(), "breeze-dark"); changeTheme(svg1->theme(), "breeze-dark");
@ -321,7 +321,7 @@ void IconItemTest::themeChange()
item2->setProperty("width", 22); item2->setProperty("width", 22);
item2->setProperty("height", 22); item2->setProperty("height", 22);
item2->setProperty("source", "tst-plasma-framework-test-icon"); item2->setProperty("source", "tst-plasma-framework-test-icon");
Plasma::Svg *svg2 = item2->findChild<Plasma::Svg*>(); Plasma::Svg *svg2 = item2->findChild<Plasma::Svg *>();
changeTheme(svg2->theme(), "breeze-light"); changeTheme(svg2->theme(), "breeze-light");
img1 = grabImage(item2); img1 = grabImage(item2);
changeTheme(svg2->theme(), "breeze-dark"); changeTheme(svg2->theme(), "breeze-dark");
@ -335,7 +335,7 @@ void IconItemTest::qiconFromTheme()
QQuickItem *item1 = createIconItem(); QQuickItem *item1 = createIconItem();
QIcon icon1 = QIcon::fromTheme("konversation"); QIcon icon1 = QIcon::fromTheme("konversation");
item1->setProperty("source", icon1); item1->setProperty("source", icon1);
QVERIFY(item1->findChild<Plasma::Svg*>()); QVERIFY(item1->findChild<Plasma::Svg *>());
QVERIFY(!imageIsEmpty(grabImage(item1))); QVERIFY(!imageIsEmpty(grabImage(item1)));
QCOMPARE(icon1, item1->property("source").value<QIcon>()); QCOMPARE(icon1, item1->property("source").value<QIcon>());
@ -343,7 +343,7 @@ void IconItemTest::qiconFromTheme()
QQuickItem *item2 = createIconItem(); QQuickItem *item2 = createIconItem();
QIcon icon2 = QIcon::fromTheme("tst-plasma-framework-test-icon"); QIcon icon2 = QIcon::fromTheme("tst-plasma-framework-test-icon");
item2->setProperty("source", icon2); item2->setProperty("source", icon2);
QVERIFY(item2->findChild<Plasma::Svg*>()); QVERIFY(item2->findChild<Plasma::Svg *>());
QVERIFY(!imageIsEmpty(grabImage(item2))); QVERIFY(!imageIsEmpty(grabImage(item2)));
QCOMPARE(icon2, item2->property("source").value<QIcon>()); QCOMPARE(icon2, item2->property("source").value<QIcon>());
} }
@ -354,7 +354,7 @@ void IconItemTest::changeColorGroup()
QQuickItem *item = createIconItem(); QQuickItem *item = createIconItem();
item->setProperty("animated", false); item->setProperty("animated", false);
item->setProperty("source", "zoom-fit-height"); item->setProperty("source", "zoom-fit-height");
Plasma::Svg *svg = item->findChild<Plasma::Svg*>(); Plasma::Svg *svg = item->findChild<Plasma::Svg *>();
// not using "breeze" theme as that one follows system color scheme // not using "breeze" theme as that one follows system color scheme
// and that one might not have a complementary group or a broken one // and that one might not have a complementary group or a broken one
changeTheme(svg->theme(), "breeze-light"); changeTheme(svg->theme(), "breeze-light");
@ -533,4 +533,3 @@ void IconItemTest::roundToIconSize()
} }
QTEST_MAIN(IconItemTest) QTEST_MAIN(IconItemTest)

View File

@ -54,4 +54,3 @@ private:
QQuickView *m_view; QQuickView *m_view;
}; };

View File

@ -7,11 +7,11 @@
#include "plasmoidpackagetest.h" #include "plasmoidpackagetest.h"
#include "../config-plasma.h" #include "../config-plasma.h"
#include <KJob>
#include <QDir> #include <QDir>
#include <QFile> #include <QFile>
#include <kzip.h>
#include <KJob>
#include <QStandardPaths> #include <QStandardPaths>
#include <kzip.h>
#include <QDebug> #include <QDebug>
@ -246,7 +246,7 @@ void PlasmoidPackageTest::createAndInstallPackage()
KZip package(packagePath); KZip package(packagePath);
QVERIFY(package.open(QIODevice::ReadOnly)); QVERIFY(package.open(QIODevice::ReadOnly));
const KArchiveDirectory *dir = package.directory(); const KArchiveDirectory *dir = package.directory();
QVERIFY(dir);// QVERIFY(dir); //
QVERIFY(dir->entry("metadata.desktop")); QVERIFY(dir->entry("metadata.desktop"));
const KArchiveEntry *contentsEntry = dir->entry("contents"); const KArchiveEntry *contentsEntry = dir->entry("contents");
QVERIFY(contentsEntry); QVERIFY(contentsEntry);
@ -258,12 +258,12 @@ void PlasmoidPackageTest::createAndInstallPackage()
m_defaultPackageStructure = new Plasma::PackageStructure(this); m_defaultPackageStructure = new Plasma::PackageStructure(this);
Plasma::Package *p = new Plasma::Package(m_defaultPackageStructure); Plasma::Package *p = new Plasma::Package(m_defaultPackageStructure);
qDebug() << "Installing " << archivePath; qDebug() << "Installing " << archivePath;
//const QString packageRoot = "plasma/plasmoids/"; // const QString packageRoot = "plasma/plasmoids/";
//const QString servicePrefix = "plasma-applet-"; // const QString servicePrefix = "plasma-applet-";
KJob *job = p->install(archivePath, m_packageRoot); KJob *job = p->install(archivePath, m_packageRoot);
connect(job, SIGNAL(finished(KJob*)), SLOT(packageInstalled(KJob*))); connect(job, SIGNAL(finished(KJob *)), SLOT(packageInstalled(KJob *)));
//QVERIFY(p->isValid()); // QVERIFY(p->isValid());
delete p; delete p;
} }
@ -271,12 +271,12 @@ void PlasmoidPackageTest::packageInstalled(KJob *j)
{ {
qDebug() << "!!!!!!!!!!!!!!!!!!!! package installed" << (j->error() == KJob::NoError); qDebug() << "!!!!!!!!!!!!!!!!!!!! package installed" << (j->error() == KJob::NoError);
QVERIFY(j->error() == KJob::NoError); QVERIFY(j->error() == KJob::NoError);
//QVERIFY(p->path()); // QVERIFY(p->path());
Plasma::Package *p = new Plasma::Package(m_defaultPackageStructure); Plasma::Package *p = new Plasma::Package(m_defaultPackageStructure);
KJob *jj = p->uninstall("org.kde.microblog-qml", m_packageRoot); KJob *jj = p->uninstall("org.kde.microblog-qml", m_packageRoot);
//QObject::disconnect(j, SIGNAL(finished(KJob*)), this, SLOT(packageInstalled(KJob*))); // QObject::disconnect(j, SIGNAL(finished(KJob*)), this, SLOT(packageInstalled(KJob*)));
connect(jj, SIGNAL(finished(KJob*)), SLOT(packageInstalled(KJob*))); connect(jj, SIGNAL(finished(KJob *)), SLOT(packageInstalled(KJob *)));
} }
void PlasmoidPackageTest::packageUninstalled(KJob *j) void PlasmoidPackageTest::packageUninstalled(KJob *j)

View File

@ -40,4 +40,3 @@ private:
}; };
#endif #endif

View File

@ -6,15 +6,15 @@
#include "pluginloadertest.h" #include "pluginloadertest.h"
#include <qtest.h>
#include <QDebug> #include <QDebug>
#include <QSignalSpy> #include <QSignalSpy>
#include <qtest.h>
#include <KPluginInfo> #include <KPluginInfo>
#include <KPluginMetaData> #include <KPluginMetaData>
#include <plasma/pluginloader.h>
#include <plasma/dataengineconsumer.h> #include <plasma/dataengineconsumer.h>
#include <plasma/pluginloader.h>
QTEST_MAIN(PluginTest) QTEST_MAIN(PluginTest)
@ -26,9 +26,9 @@ PluginTest::PluginTest()
void PluginTest::listEngines() void PluginTest::listEngines()
{ {
QVector<KPluginMetaData> plugins = Plasma::PluginLoader::self()->listDataEngineMetaData(); QVector<KPluginMetaData> plugins = Plasma::PluginLoader::self()->listDataEngineMetaData();
// foreach (const KPluginInfo& info, plugins) { // foreach (const KPluginInfo& info, plugins) {
//qDebug() << " Found DataEngine: " << info.pluginName() << info.name(); // qDebug() << " Found DataEngine: " << info.pluginName() << info.name();
// } // }
qDebug() << " Found " << plugins.count() << " DataEngines"; qDebug() << " Found " << plugins.count() << " DataEngines";
// Switch to true in order to let tests pass, this test usually will only // Switch to true in order to let tests pass, this test usually will only
// work with plugins installed, but there aren't any in plasma-framework // work with plugins installed, but there aren't any in plasma-framework
@ -47,7 +47,7 @@ void PluginTest::listContainmentActions()
{ {
const QVector<KPluginMetaData> plugins = Plasma::PluginLoader::self()->listContainmentActionsMetaData(QStringLiteral("plasma-shell")); const QVector<KPluginMetaData> plugins = Plasma::PluginLoader::self()->listContainmentActionsMetaData(QStringLiteral("plasma-shell"));
qDebug() << "Categories: " << plugins.count(); qDebug() << "Categories: " << plugins.count();
//QVERIFY(plugins.count() > 0 || m_buildonly); // QVERIFY(plugins.count() > 0 || m_buildonly);
} }
void PluginTest::listContainmentsOfType() void PluginTest::listContainmentsOfType()
@ -55,12 +55,12 @@ void PluginTest::listContainmentsOfType()
const KPluginInfo::List plugins = Plasma::PluginLoader::listContainmentsOfType(QStringLiteral("Desktop")); const KPluginInfo::List plugins = Plasma::PluginLoader::listContainmentsOfType(QStringLiteral("Desktop"));
qDebug() << "Desktop Containments: " << plugins.count(); qDebug() << "Desktop Containments: " << plugins.count();
QVERIFY(plugins.count() > 0 || m_buildonly); QVERIFY(plugins.count() > 0 || m_buildonly);
} }
static const auto source = QStringLiteral("Europe/Sofia"); static const auto source = QStringLiteral("Europe/Sofia");
void EngineTest::dataUpdated(const QString &s, const Plasma::DataEngine::Data &data) { void EngineTest::dataUpdated(const QString &s, const Plasma::DataEngine::Data &data)
{
QVERIFY(source == s); QVERIFY(source == s);
QVERIFY(data["Timezone"] == source); QVERIFY(data["Timezone"] == source);
} }
@ -92,4 +92,3 @@ void PluginTest::loadDataEngine()
} }
#include "moc_pluginloadertest.cpp" #include "moc_pluginloadertest.cpp"

View File

@ -32,7 +32,9 @@ class EngineTest : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
EngineTest() {} EngineTest()
{
}
public Q_SLOTS: public Q_SLOTS:
void dataUpdated(const QString &name, const Plasma::DataEngine::Data &data); void dataUpdated(const QString &name, const Plasma::DataEngine::Data &data);

View File

@ -10,9 +10,9 @@
// KDE // KDE
// Qt // Qt
#include <QSignalSpy>
#include <QStandardItemModel> #include <QStandardItemModel>
#include <QStringListModel> #include <QStringListModel>
#include <QSignalSpy>
#include <QTest> #include <QTest>
using namespace Plasma; using namespace Plasma;
@ -25,7 +25,7 @@ void SortFilterModelTest::setModel()
QStandardItemModel model; QStandardItemModel model;
SortFilterModel filterModel; SortFilterModel filterModel;
QSignalSpy spy(&filterModel, SIGNAL(sourceModelChanged(QObject*))); QSignalSpy spy(&filterModel, SIGNAL(sourceModelChanged(QObject *)));
filterModel.setModel(&model); filterModel.setModel(&model);
QCOMPARE(spy.count(), 1); QCOMPARE(spy.count(), 1);
@ -102,4 +102,3 @@ void SortFilterModelTest::mapRowFromSource()
QCOMPARE(filterModel.mapRowFromSource(2), 1); QCOMPARE(filterModel.mapRowFromSource(2), 1);
QCOMPARE(filterModel.mapRowFromSource(-1), -1); QCOMPARE(filterModel.mapRowFromSource(-1), -1);
} }

View File

@ -6,9 +6,9 @@
#include "themetest.h" #include "themetest.h"
#include "../src/plasma/private/svg_p.h" #include "../src/plasma/private/svg_p.h"
#include <QStandardPaths>
#include <QApplication> #include <QApplication>
#include <QSignalSpy> #include <QSignalSpy>
#include <QStandardPaths>
#include <KIconLoader> #include <KIconLoader>
#include <KIconTheme> #include <KIconTheme>
@ -23,26 +23,23 @@
QString cacheIdHash(const Plasma::SvgPrivate::CacheId &id) QString cacheIdHash(const Plasma::SvgPrivate::CacheId &id)
{ {
static const uint seed = 0x9e3779b9; static const uint seed = 0x9e3779b9;
std::array<uint, 10> parts = { std::array<uint, 10> parts = {::qHash(id.width),
::qHash(id.width), ::qHash(id.height),
::qHash(id.height), ::qHash(id.elementName),
::qHash(id.elementName), ::qHash(id.filePath),
::qHash(id.filePath), ::qHash(id.status),
::qHash(id.status), ::qHash(id.devicePixelRatio),
::qHash(id.devicePixelRatio), ::qHash(id.scaleFactor),
::qHash(id.scaleFactor), ::qHash(id.colorGroup),
::qHash(id.colorGroup), ::qHash(id.extraFlags),
::qHash(id.extraFlags), ::qHash(id.lastModified)};
::qHash(id.lastModified)
};
return QString::number(qHashRange(parts.begin(), parts.end(), seed)); return QString::number(qHashRange(parts.begin(), parts.end(), seed));
} }
void ThemeTest::initTestCase() void ThemeTest::initTestCase()
{ {
// make our theme in search path // make our theme in search path
qputenv("XDG_DATA_DIRS", qputenv("XDG_DATA_DIRS", qgetenv("XDG_DATA_DIRS") + ":" + QFINDTESTDATA("data").toLocal8Bit());
qgetenv("XDG_DATA_DIRS") + ":" + QFINDTESTDATA("data").toLocal8Bit());
// set default icon theme to test-theme // set default icon theme to test-theme
QStandardPaths::setTestModeEnabled(true); QStandardPaths::setTestModeEnabled(true);
@ -50,13 +47,13 @@ void ThemeTest::initTestCase()
m_theme = new Plasma::Theme("testtheme", this); m_theme = new Plasma::Theme("testtheme", this);
QString configPath = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation); QString configPath = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
if(!QDir(configPath).mkpath(QStringLiteral("."))) { if (!QDir(configPath).mkpath(QStringLiteral("."))) {
qFatal("Failed to create test configuration directory."); qFatal("Failed to create test configuration directory.");
} }
QFile::remove(configPath); QFile::remove(configPath);
QIcon::setThemeSearchPaths(QStringList()<<QFINDTESTDATA("data/icons")); QIcon::setThemeSearchPaths(QStringList() << QFINDTESTDATA("data/icons"));
KConfigGroup plasmaConfig(KSharedConfig::openConfig("plasmarc"), "Theme"); KConfigGroup plasmaConfig(KSharedConfig::openConfig("plasmarc"), "Theme");
plasmaConfig.writeEntry("name", "default"); plasmaConfig.writeEntry("name", "default");
@ -70,7 +67,7 @@ void ThemeTest::initTestCase()
void ThemeTest::cleanupTestCase() void ThemeTest::cleanupTestCase()
{ {
// m_testIconsDir.removeRecursively(); // m_testIconsDir.removeRecursively();
delete m_svg; delete m_svg;
} }
@ -88,11 +85,20 @@ void ThemeTest::loadSvgIcon()
m_svg->setImagePath(iconPath); m_svg->setImagePath(iconPath);
QVERIFY(m_svg->isValid()); QVERIFY(m_svg->isValid());
m_svg->pixmap(); //trigger the SVG being loaded m_svg->pixmap(); // trigger the SVG being loaded
QFileInfo info(iconPath); QFileInfo info(iconPath);
QString cacheId = cacheIdHash(Plasma::SvgPrivate::CacheId{48, 48, iconPath, QString(), m_svg->status(), m_svg->devicePixelRatio(), m_svg->scaleFactor(), m_svg->colorGroup(), 0, static_cast<uint>(info.lastModified().toSecsSinceEpoch())}); QString cacheId = cacheIdHash(Plasma::SvgPrivate::CacheId{48,
48,
iconPath,
QString(),
m_svg->status(),
m_svg->devicePixelRatio(),
m_svg->scaleFactor(),
m_svg->colorGroup(),
0,
static_cast<uint>(info.lastModified().toSecsSinceEpoch())});
QPixmap result; QPixmap result;
QVERIFY(m_svg->theme()->findInCache(cacheId, result, info.lastModified().toSecsSinceEpoch())); QVERIFY(m_svg->theme()->findInCache(cacheId, result, info.lastModified().toSecsSinceEpoch()));
@ -102,12 +108,12 @@ void ThemeTest::loadSvgIcon()
KIconTheme::forceThemeForTests("test-theme-two"); KIconTheme::forceThemeForTests("test-theme-two");
// KIconloader needs changesto be emitted manually, ouch. // KIconloader needs changesto be emitted manually, ouch.
for (int i=0; i < KIconLoader::LastGroup; i++) { for (int i = 0; i < KIconLoader::LastGroup; i++) {
KIconLoader::emitChange(KIconLoader::Group(i)); KIconLoader::emitChange(KIconLoader::Group(i));
} }
spy.wait(); spy.wait();
//Svg emitting repaintNeeded when something changes in KIconLoader means the svg loaded an icon // Svg emitting repaintNeeded when something changes in KIconLoader means the svg loaded an icon
QVERIFY(spy.count() == 1); QVERIFY(spy.count() == 1);
QVERIFY(!m_svg->theme()->findInCache(cacheId, result)); QVERIFY(!m_svg->theme()->findInCache(cacheId, result));
@ -115,97 +121,53 @@ void ThemeTest::loadSvgIcon()
void ThemeTest::testColors() void ThemeTest::testColors()
{ {
QCOMPARE(m_theme->color(Plasma::Theme::TextColor, QCOMPARE(m_theme->color(Plasma::Theme::TextColor, Plasma::Theme::NormalColorGroup), QColor(49, 54, 59));
Plasma::Theme::NormalColorGroup), QColor(49,54,59)); QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, Plasma::Theme::NormalColorGroup), QColor(239, 240, 241));
QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, Plasma::Theme::NormalColorGroup), QColor(61, 174, 230));
Plasma::Theme::NormalColorGroup), QColor(239,240,241)); QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, Plasma::Theme::NormalColorGroup), QColor(61, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, Plasma::Theme::NormalColorGroup), QColor(30, 146, 255));
Plasma::Theme::NormalColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, Plasma::Theme::NormalColorGroup), QColor(61, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor, Plasma::Theme::NormalColorGroup), QColor(61, 174, 230));
Plasma::Theme::NormalColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor, Plasma::Theme::NormalColorGroup), QColor(252, 252, 252));
QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor, Plasma::Theme::NormalColorGroup), QColor(17, 209, 22));
Plasma::Theme::NormalColorGroup), QColor(30,146,255)); QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor, Plasma::Theme::NormalColorGroup), QColor(201, 206, 59));
QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor, Plasma::Theme::NormalColorGroup), QColor(237, 21, 21));
Plasma::Theme::NormalColorGroup), QColor(61,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor,
Plasma::Theme::NormalColorGroup), QColor(61,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor,
Plasma::Theme::NormalColorGroup), QColor(252,252,252));
QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor,
Plasma::Theme::NormalColorGroup), QColor(17,209,22));
QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor,
Plasma::Theme::NormalColorGroup), QColor(201,206,59));
QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor,
Plasma::Theme::NormalColorGroup), QColor(237,21,21));
QCOMPARE(m_theme->color(Plasma::Theme::TextColor, QCOMPARE(m_theme->color(Plasma::Theme::TextColor, Plasma::Theme::ButtonColorGroup), QColor(49, 54, 59));
Plasma::Theme::ButtonColorGroup), QColor(49,54,59)); QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, Plasma::Theme::ButtonColorGroup), QColor(239, 240, 241));
QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, Plasma::Theme::ButtonColorGroup), QColor(61, 174, 230));
Plasma::Theme::ButtonColorGroup), QColor(239,240,241)); QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, Plasma::Theme::ButtonColorGroup), QColor(61, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, Plasma::Theme::ButtonColorGroup), QColor(30, 146, 255));
Plasma::Theme::ButtonColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, Plasma::Theme::ButtonColorGroup), QColor(61, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor, Plasma::Theme::ButtonColorGroup), QColor(61, 174, 230));
Plasma::Theme::ButtonColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor, Plasma::Theme::ButtonColorGroup), QColor(252, 252, 252));
QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor, Plasma::Theme::ButtonColorGroup), QColor(17, 209, 23));
Plasma::Theme::ButtonColorGroup), QColor(30,146,255)); QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor, Plasma::Theme::ButtonColorGroup), QColor(201, 206, 60));
QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor, Plasma::Theme::ButtonColorGroup), QColor(237, 21, 22));
Plasma::Theme::ButtonColorGroup), QColor(61,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor,
Plasma::Theme::ButtonColorGroup), QColor(61,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor,
Plasma::Theme::ButtonColorGroup), QColor(252,252,252));
QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor,
Plasma::Theme::ButtonColorGroup), QColor(17,209,23));
QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor,
Plasma::Theme::ButtonColorGroup), QColor(201,206,60));
QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor,
Plasma::Theme::ButtonColorGroup), QColor(237,21,22));
QCOMPARE(m_theme->color(Plasma::Theme::TextColor, QCOMPARE(m_theme->color(Plasma::Theme::TextColor, Plasma::Theme::ViewColorGroup), QColor(49, 54, 59));
Plasma::Theme::ViewColorGroup), QColor(49,54,59)); QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, Plasma::Theme::ViewColorGroup), QColor(252, 252, 252));
QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, Plasma::Theme::ViewColorGroup), QColor(61, 174, 230));
Plasma::Theme::ViewColorGroup), QColor(252,252,252)); QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, Plasma::Theme::ViewColorGroup), QColor(61, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, Plasma::Theme::ViewColorGroup), QColor(30, 146, 255));
Plasma::Theme::ViewColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, Plasma::Theme::ViewColorGroup), QColor(61, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor, Plasma::Theme::ViewColorGroup), QColor(61, 174, 230));
Plasma::Theme::ViewColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor, Plasma::Theme::ViewColorGroup), QColor(252, 252, 252));
QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor, Plasma::Theme::ViewColorGroup), QColor(17, 209, 24));
Plasma::Theme::ViewColorGroup), QColor(30,146,255)); QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor, Plasma::Theme::ViewColorGroup), QColor(201, 206, 61));
QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor, Plasma::Theme::ViewColorGroup), QColor(237, 21, 23));
Plasma::Theme::ViewColorGroup), QColor(61,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor,
Plasma::Theme::ViewColorGroup), QColor(61,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor,
Plasma::Theme::ViewColorGroup), QColor(252,252,252));
QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor,
Plasma::Theme::ViewColorGroup), QColor(17,209,24));
QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor,
Plasma::Theme::ViewColorGroup), QColor(201,206,61));
QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor,
Plasma::Theme::ViewColorGroup), QColor(237,21,23));
QCOMPARE(m_theme->color(Plasma::Theme::TextColor, QCOMPARE(m_theme->color(Plasma::Theme::TextColor, Plasma::Theme::ComplementaryColorGroup), QColor(239, 240, 241));
Plasma::Theme::ComplementaryColorGroup), QColor(239,240,241)); QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, Plasma::Theme::ComplementaryColorGroup), QColor(49, 54, 59));
QCOMPARE(m_theme->color(Plasma::Theme::BackgroundColor, QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, Plasma::Theme::ComplementaryColorGroup), QColor(61, 174, 230));
Plasma::Theme::ComplementaryColorGroup), QColor(49,54,59)); QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, Plasma::Theme::ComplementaryColorGroup), QColor(71, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightColor, QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, Plasma::Theme::ComplementaryColorGroup), QColor(40, 146, 255));
Plasma::Theme::ComplementaryColorGroup), QColor(61,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, Plasma::Theme::ComplementaryColorGroup), QColor(71, 174, 230));
QCOMPARE(m_theme->color(Plasma::Theme::HoverColor, QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor, Plasma::Theme::ComplementaryColorGroup), QColor(71, 174, 230));
Plasma::Theme::ComplementaryColorGroup), QColor(71,174,230)); QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor, Plasma::Theme::ComplementaryColorGroup), QColor(252, 252, 252));
QCOMPARE(m_theme->color(Plasma::Theme::FocusColor, QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor, Plasma::Theme::ComplementaryColorGroup), QColor(17, 209, 25));
Plasma::Theme::ComplementaryColorGroup), QColor(40,146,255)); QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor, Plasma::Theme::ComplementaryColorGroup), QColor(201, 206, 62));
QCOMPARE(m_theme->color(Plasma::Theme::LinkColor, QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor, Plasma::Theme::ComplementaryColorGroup), QColor(237, 21, 24));
Plasma::Theme::ComplementaryColorGroup), QColor(71,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::VisitedLinkColor,
Plasma::Theme::ComplementaryColorGroup), QColor(71,174,230));
QCOMPARE(m_theme->color(Plasma::Theme::HighlightedTextColor,
Plasma::Theme::ComplementaryColorGroup), QColor(252,252,252));
QCOMPARE(m_theme->color(Plasma::Theme::PositiveTextColor,
Plasma::Theme::ComplementaryColorGroup), QColor(17,209,25));
QCOMPARE(m_theme->color(Plasma::Theme::NeutralTextColor,
Plasma::Theme::ComplementaryColorGroup), QColor(201,206,62));
QCOMPARE(m_theme->color(Plasma::Theme::NegativeTextColor,
Plasma::Theme::ComplementaryColorGroup), QColor(237,21,24));
} }
void ThemeTest::testCompositingChange() void ThemeTest::testCompositingChange()
@ -250,4 +212,3 @@ void ThemeTest::testCompositingChange()
} }
QTEST_MAIN(ThemeTest) QTEST_MAIN(ThemeTest)

View File

@ -8,8 +8,8 @@
#include <QTest> #include <QTest>
#include "plasma/theme.h"
#include "plasma/svg.h" #include "plasma/svg.h"
#include "plasma/theme.h"
class ThemeTest : public QObject class ThemeTest : public QObject
{ {
@ -30,4 +30,3 @@ private:
}; };
#endif #endif

View File

@ -6,20 +6,21 @@
#ifndef UTILS_H #ifndef UTILS_H
#define UTILS_H #define UTILS_H
#include <QString>
#include <QDir> #include <QDir>
#include <QStandardPaths> #include <QStandardPaths>
#include <QString>
#include <QTest> #include <QTest>
namespace Plasma { namespace Plasma
namespace TestUtils { {
namespace TestUtils
{
static void copyPath(const QString &src, const QString &dst) static void copyPath(const QString &src, const QString &dst)
{ {
QDir dir(src); QDir dir(src);
const auto dirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot); const auto dirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
for (const auto &d : dirList ) { for (const auto &d : dirList) {
QString dst_path = dst + QLatin1Char('/') + d; QString dst_path = dst + QLatin1Char('/') + d;
dir.mkpath(dst_path); dir.mkpath(dst_path);
copyPath(src + QLatin1Char('/') + d, dst_path); copyPath(src + QLatin1Char('/') + d, dst_path);
@ -49,12 +50,11 @@ static void installPlasmaTheme(const QString &theme = QStringLiteral("breeze"))
const QString colorsFile = QFINDTESTDATA("../src/desktoptheme/" + theme + "/colors"); const QString colorsFile = QFINDTESTDATA("../src/desktoptheme/" + theme + "/colors");
if (!colorsFile.isEmpty()) { if (!colorsFile.isEmpty()) {
QFile::copy(colorsFile, themePath.filePath("colors")); QFile::copy(colorsFile, themePath.filePath("colors"));
} }
} }
} //TestUtils } // TestUtils
} //Plasma } // Plasma
#endif #endif

View File

@ -4,8 +4,8 @@
SPDX-License-Identifier: BSD-2-Clause SPDX-License-Identifier: BSD-2-Clause
*/ */
#include <QUrl>
#include <QDebug> #include <QDebug>
#include <QUrl>
#include "customDataContainersEngine.h" #include "customDataContainersEngine.h"
@ -68,4 +68,3 @@ K_EXPORT_PLASMA_DATAENGINE_WITH_JSON(org.kde.examples.customDataContainers, Data
// include the moc file so the build system makes it for us // include the moc file so the build system makes it for us
#include "customDataContainersEngine.moc" #include "customDataContainersEngine.moc"

View File

@ -9,8 +9,8 @@
#include <kio/job.h> #include <kio/job.h>
HttpContainer::HttpContainer(const QUrl &url, QObject *parent) HttpContainer::HttpContainer(const QUrl &url, QObject *parent)
: Plasma::DataContainer(parent), : Plasma::DataContainer(parent)
m_url(url) , m_url(url)
{ {
// Since we are grabbing data over the network, we request a // Since we are grabbing data over the network, we request a
// backing store. This way, if the network is down or on first start // backing store. This way, if the network is down or on first start
@ -29,9 +29,8 @@ void HttpContainer::fetchUrl(bool reload)
m_data.clear(); m_data.clear();
KIO::TransferJob *job = KIO::get(m_url, reload ? KIO::Reload : KIO::NoReload, KIO::HideProgressInfo); KIO::TransferJob *job = KIO::get(m_url, reload ? KIO::Reload : KIO::NoReload, KIO::HideProgressInfo);
connect(job, SIGNAL(data(KIO::Job*,QByteArray)), connect(job, SIGNAL(data(KIO::Job *, QByteArray)), this, SLOT(data(KIO::Job *, QByteArray)));
this, SLOT(data(KIO::Job*,QByteArray))); connect(job, SIGNAL(finished(KJob *)), this, SLOT(fetchFinished(KJob *)));
connect(job, SIGNAL(finished(KJob*)), this, SLOT(fetchFinished(KJob*)));
if (m_job) { if (m_job) {
m_job.data()->kill(); m_job.data()->kill();
@ -76,5 +75,3 @@ void HttpContainer::fetchFinished(KJob *job)
m_data.clear(); m_data.clear();
} }
} }

View File

@ -6,12 +6,12 @@
#include "dataenginetracker.h" #include "dataenginetracker.h"
#include <QTime>
#include <QDebug> #include <QDebug>
#include <QTime>
DataEngineTracker::DataEngineTracker(Plasma::DataEngine *engine, QObject *parent) DataEngineTracker::DataEngineTracker(Plasma::DataEngine *engine, QObject *parent)
: QObject(parent), : QObject(parent)
m_engine(engine) , m_engine(engine)
{ {
connect(engine, SIGNAL(sourceAdded(QString)), this, SLOT(sourceAdded(QString))); connect(engine, SIGNAL(sourceAdded(QString)), this, SLOT(sourceAdded(QString)));
connect(engine, SIGNAL(sourceRemoved(QString)), this, SLOT(sourceRemoved(QString))); connect(engine, SIGNAL(sourceRemoved(QString)), this, SLOT(sourceRemoved(QString)));
@ -40,4 +40,3 @@ void DataEngineTracker::sourceRemoved(const QString &source)
} }
#include <dataenginetracker.moc> #include <dataenginetracker.moc>

View File

@ -28,4 +28,3 @@ private:
}; };
#endif #endif

View File

@ -28,7 +28,6 @@ SimpleEngine::SimpleEngine(QObject *parent, const QVariantList &args)
void SimpleEngine::init() void SimpleEngine::init()
{ {
// So now we will set up some sources. // So now we will set up some sources.
// Each DataEngine will, generally, be loaded once. Each DataEngine // Each DataEngine will, generally, be loaded once. Each DataEngine
// can provide multiple sets of data keyed by a string, called "Sources". // can provide multiple sets of data keyed by a string, called "Sources".
@ -59,4 +58,3 @@ K_EXPORT_PLASMA_DATAENGINE_WITH_JSON(org.kde.examples.simpleEngine, SimpleEngine
// include the moc file so the build system makes it for us // include the moc file so the build system makes it for us
#include "simpleEngine.moc" #include "simpleEngine.moc"

View File

@ -94,4 +94,3 @@ K_EXPORT_PLASMA_DATAENGINE_WITH_JSON(org.kde.examples.sourcesOnRequest, SourcesO
// include the moc file so the build system makes it for us // include the moc file so the build system makes it for us
#include "sourcesOnRequest.moc" #include "sourcesOnRequest.moc"

View File

@ -5,9 +5,9 @@
*/ */
#include "customcorona.h" #include "customcorona.h"
#include <QDebug>
#include <QAction>
#include <KActionCollection> #include <KActionCollection>
#include <QAction>
#include <QDebug>
#include <KPackage/Package> #include <KPackage/Package>
#include <KPackage/PackageLoader> #include <KPackage/PackageLoader>
@ -17,23 +17,27 @@ CustomCorona::CustomCorona(QObject *parent)
: Plasma::Corona(parent) : Plasma::Corona(parent)
{ {
KPackage::Package package = KPackage::PackageLoader::self()->loadPackage(QStringLiteral("Plasma/Shell")); KPackage::Package package = KPackage::PackageLoader::self()->loadPackage(QStringLiteral("Plasma/Shell"));
//applications that want to load a plasma scene would have to load their own shell.. TODO: have a simple shell in plasma-framework for this purpose? // applications that want to load a plasma scene would have to load their own shell.. TODO: have a simple shell in plasma-framework for this purpose?
package.setPath(QStringLiteral("org.kde.plasma.desktop")); package.setPath(QStringLiteral("org.kde.plasma.desktop"));
setKPackage(package); setKPackage(package);
qmlRegisterUncreatableType<PlasmaQuick::ContainmentView>("org.kde.plasma.shell", 2, 0, "Desktop", QStringLiteral("It is not possible to create objects of type Desktop")); qmlRegisterUncreatableType<PlasmaQuick::ContainmentView>("org.kde.plasma.shell",
2,
0,
"Desktop",
QStringLiteral("It is not possible to create objects of type Desktop"));
m_view = new PlasmaQuick::ContainmentView(this); m_view = new PlasmaQuick::ContainmentView(this);
m_view->setSource(package.fileUrl("views", QStringLiteral("Desktop.qml"))); m_view->setSource(package.fileUrl("views", QStringLiteral("Desktop.qml")));
m_view->show(); m_view->show();
load(); load();
} }
QRect CustomCorona::screenGeometry(int id) const QRect CustomCorona::screenGeometry(int id) const
{ {
Q_UNUSED(id); Q_UNUSED(id);
//TODO? // TODO?
return QRect(); return QRect();
} }
@ -56,10 +60,10 @@ void CustomCorona::load()
saveLayout(QStringLiteral("exampleplasmashell-appletsrc")); saveLayout(QStringLiteral("exampleplasmashell-appletsrc"));
} }
//don't let containments to be removed // don't let containments to be removed
for (auto c : containments()) { for (auto c : containments()) {
if (c->containmentType() == Plasma::Types::DesktopContainment) { if (c->containmentType() == Plasma::Types::DesktopContainment) {
//example of a shell without a wallpaper // example of a shell without a wallpaper
c->setWallpaper(QStringLiteral("null")); c->setWallpaper(QStringLiteral("null"));
m_view->setContainment(c); m_view->setContainment(c);
if (QAction *removeAction = c->actions()->action(QStringLiteral("remove"))) { if (QAction *removeAction = c->actions()->action(QStringLiteral("remove"))) {

View File

@ -5,8 +5,8 @@
*/ */
#include <QApplication> #include <QApplication>
#include <QCommandLineParser>
#include <QCommandLineOption> #include <QCommandLineOption>
#include <QCommandLineParser>
#include <KDBusService> #include <KDBusService>
#include <KLocalizedString> #include <KLocalizedString>

View File

@ -6,9 +6,8 @@
#include "test.h" #include "test.h"
#include <QDebug>
#include <KActionCollection> #include <KActionCollection>
#include <QDebug>
#include <Plasma/Containment> #include <Plasma/Containment>
@ -44,14 +43,14 @@ void ContextTest::init(const KConfigGroup &config)
QWidget *ContextTest::createConfigurationInterface(QWidget *parent) QWidget *ContextTest::createConfigurationInterface(QWidget *parent)
{ {
//m_currentText = m_text; // m_currentText = m_text;
QWidget *widget = new QWidget(parent); QWidget *widget = new QWidget(parent);
m_ui.setupUi(widget); m_ui.setupUi(widget);
m_ui.text->setText(m_text); m_ui.text->setText(m_text);
//FIXME this way or just get it on close? // FIXME this way or just get it on close?
//connect(m_ui.text, SIGNAL(changed(QColor)), this, SLOT(setColor(QColor))); // connect(m_ui.text, SIGNAL(changed(QColor)), this, SLOT(setColor(QColor)));
//connect(this, SIGNAL(settingsChanged(bool)), parent, SLOT(settingsChanged(bool))); // connect(this, SIGNAL(settingsChanged(bool)), parent, SLOT(settingsChanged(bool)));
return widget; return widget;
} }

View File

@ -8,8 +8,8 @@
#define CONTEXTTEST_HEADER #define CONTEXTTEST_HEADER
#include "ui_config.h" #include "ui_config.h"
#include <plasma/containmentactions.h>
#include <QString> #include <QString>
#include <plasma/containmentactions.h>
class ContextTest : public Plasma::ContainmentActions class ContextTest : public Plasma::ContainmentActions
{ {

View File

@ -23,7 +23,7 @@ Calendar::Calendar(QObject *parent)
m_daysModel->setSourceData(&m_dayList); m_daysModel->setSourceData(&m_dayList);
// m_dayHelper = new CalendarDayHelper(this); // m_dayHelper = new CalendarDayHelper(this);
// connect(m_dayHelper, SIGNAL(calendarChanged()), this, SLOT(updateData())); // connect(m_dayHelper, SIGNAL(calendarChanged()), this, SLOT(updateData()));
} }
QDateTime Calendar::displayedDate() const QDateTime Calendar::displayedDate() const
@ -100,8 +100,8 @@ void Calendar::setTypes(int types)
return; return;
} }
// m_types = static_cast<Types>(types); // m_types = static_cast<Types>(types);
// updateTypes(); // updateTypes();
Q_EMIT typesChanged(); Q_EMIT typesChanged();
} }
@ -239,7 +239,7 @@ void Calendar::updateData()
if (daysBeforeCurrentMonth > 0) { if (daysBeforeCurrentMonth > 0) {
QDate previousMonth = m_displayedDate.addMonths(-1); QDate previousMonth = m_displayedDate.addMonths(-1);
//QDate previousMonth(m_displayedDate.year(), m_displayedDate.month() - 1, 1); // QDate previousMonth(m_displayedDate.year(), m_displayedDate.month() - 1, 1);
for (int i = 0; i < daysBeforeCurrentMonth; i++) { for (int i = 0; i < daysBeforeCurrentMonth; i++) {
DayData day; DayData day;
day.isCurrent = false; day.isCurrent = false;
@ -259,7 +259,6 @@ void Calendar::updateData()
day.monthNumber = m_displayedDate.month(); day.monthNumber = m_displayedDate.month();
day.yearNumber = m_displayedDate.year(); day.yearNumber = m_displayedDate.year();
m_dayList << day; m_dayList << day;
} }
if (daysAfterCurrentMonth > 0) { if (daysAfterCurrentMonth > 0) {
@ -295,16 +294,16 @@ void Calendar::updateData()
Q_EMIT weeksModelChanged(); Q_EMIT weeksModelChanged();
m_daysModel->update(); m_daysModel->update();
// qDebug() << "---------------------------------------------------------------"; // qDebug() << "---------------------------------------------------------------";
// qDebug() << "Date obj: " << m_displayedDate; // qDebug() << "Date obj: " << m_displayedDate;
// qDebug() << "Month: " << m_displayedDate.month(); // qDebug() << "Month: " << m_displayedDate.month();
// qDebug() << "m_days: " << m_days; // qDebug() << "m_days: " << m_days;
// qDebug() << "m_weeks: " << m_weeks; // qDebug() << "m_weeks: " << m_weeks;
// qDebug() << "Days before this month: " << daysBeforeCurrentMonth; // qDebug() << "Days before this month: " << daysBeforeCurrentMonth;
// qDebug() << "Days after this month: " << daysAfterCurrentMonth; // qDebug() << "Days after this month: " << daysAfterCurrentMonth;
// qDebug() << "Days in current month: " << m_displayedDate.daysInMonth(); // qDebug() << "Days in current month: " << m_displayedDate.daysInMonth();
// qDebug() << "m_dayList size: " << m_dayList.count(); // qDebug() << "m_dayList size: " << m_dayList.count();
// qDebug() << "---------------------------------------------------------------"; // qDebug() << "---------------------------------------------------------------";
} }
void Calendar::nextDecade() void Calendar::nextDecade()

View File

@ -8,10 +8,10 @@
#ifndef CALENDAR_H #ifndef CALENDAR_H
#define CALENDAR_H #define CALENDAR_H
#include <QObject>
#include <QDate>
#include <QAbstractListModel> #include <QAbstractListModel>
#include <QDate>
#include <QJsonArray> #include <QJsonArray>
#include <QObject>
#include "daydata.h" #include "daydata.h"
#include "daysmodel.h" #include "daysmodel.h"
@ -112,7 +112,6 @@ class Calendar : public QObject
*/ */
Q_PROPERTY(QAbstractListModel *daysModel READ daysModel CONSTANT) Q_PROPERTY(QAbstractListModel *daysModel READ daysModel CONSTANT)
public: public:
enum Type { enum Type {
Holiday = 1, Holiday = 1,

View File

@ -10,8 +10,8 @@ CalendarData::CalendarData(QObject *parent)
: QObject(parent) : QObject(parent)
, m_types(Holiday | Event | Todo | Journal) , m_types(Holiday | Event | Todo | Journal)
{ {
// m_etmCalendar = new ETMCalendar(); // m_etmCalendar = new ETMCalendar();
// m_etmCalendar->setParent(this); //TODO: hit sergio // m_etmCalendar->setParent(this); //TODO: hit sergio
// EntityTreeModel *model = m_etmCalendar->entityTreeModel(); // EntityTreeModel *model = m_etmCalendar->entityTreeModel();
// model->setCollectionFetchStrategy(EntityTreeModel::InvisibleCollectionFetch); // model->setCollectionFetchStrategy(EntityTreeModel::InvisibleCollectionFetch);
@ -25,7 +25,7 @@ CalendarData::CalendarData(QObject *parent)
// m_filteredList = new DateTimeRangeFilterModel(this); // m_filteredList = new DateTimeRangeFilterModel(this);
// m_filteredList->setSourceModel(roleModel); // m_filteredList->setSourceModel(roleModel);
// updateTypes(); // updateTypes();
} }
QDate CalendarData::startDate() const QDate CalendarData::startDate() const
@ -40,7 +40,7 @@ void CalendarData::setStartDate(const QDate &dateTime)
} }
m_startDate = dateTime; m_startDate = dateTime;
// m_filteredList->setStartDate(m_startDate); // m_filteredList->setStartDate(m_startDate);
Q_EMIT startDateChanged(); Q_EMIT startDateChanged();
} }
@ -74,4 +74,3 @@ bool CalendarData::loading() const
{ {
return false; return false;
} }

View File

@ -7,9 +7,9 @@
#ifndef CALENDARDATA_H #ifndef CALENDARDATA_H
#define CALENDARDATA_H #define CALENDARDATA_H
#include <QObject>
#include <QFlags>
#include <QDate> #include <QDate>
#include <QFlags>
#include <QObject>
class QAbstractItemModel; class QAbstractItemModel;

View File

@ -5,14 +5,14 @@
*/ */
#include "calendarplugin.h" #include "calendarplugin.h"
#include "calendardata.h"
#include "calendar.h" #include "calendar.h"
#include "calendardata.h"
#include "eventdatadecorator.h" #include "eventdatadecorator.h"
#include "eventpluginsmanager.h" #include "eventpluginsmanager.h"
#include <QtQml>
#include <QQmlEngine>
#include <QAbstractListModel> #include <QAbstractListModel>
#include <QQmlEngine>
#include <QtQml>
static QObject *event_plugins_manager_provider(QQmlEngine *engine, QJSEngine *scriptEngine) static QObject *event_plugins_manager_provider(QQmlEngine *engine, QJSEngine *scriptEngine)
{ {
@ -30,6 +30,5 @@ void CalendarPlugin::registerTypes(const char *uri)
qmlRegisterAnonymousType<QAbstractItemModel>(uri, 1); qmlRegisterAnonymousType<QAbstractItemModel>(uri, 1);
qmlRegisterAnonymousType<QAbstractListModel>(uri, 1); qmlRegisterAnonymousType<QAbstractListModel>(uri, 1);
qmlRegisterSingletonType<EventPluginsManager>(uri, 2, 0, "EventPluginsManager", event_plugins_manager_provider); qmlRegisterSingletonType<EventPluginsManager>(uri, 2, 0, "EventPluginsManager", event_plugins_manager_provider);
qmlRegisterUncreatableType<EventDataDecorator>(uri, 2, 0, "EventDataDecorator", qmlRegisterUncreatableType<EventDataDecorator>(uri, 2, 0, "EventDataDecorator", QStringLiteral("Unabel to create EventDataDecorator from QML"));
QStringLiteral("Unabel to create EventDataDecorator from QML"));
} }

View File

@ -9,10 +9,10 @@ class DayData
{ {
public: public:
bool isCurrent; bool isCurrent;
// bool containsHolidayItems; // bool containsHolidayItems;
// bool containsEventItems; // bool containsEventItems;
// bool containsTodoItems; // bool containsTodoItems;
// bool containsJournalItems; // bool containsJournalItems;
int dayNumber; int dayNumber;
int monthNumber; int monthNumber;
int yearNumber; int yearNumber;

View File

@ -9,18 +9,17 @@
#include "eventdatadecorator.h" #include "eventdatadecorator.h"
#include "eventpluginsmanager.h" #include "eventpluginsmanager.h"
#include <QDebug>
#include <QByteArray> #include <QByteArray>
#include <QDebug>
#include <QDir> #include <QDir>
#include <QMetaObject> #include <QMetaObject>
DaysModel::DaysModel(QObject *parent) : DaysModel::DaysModel(QObject *parent)
QAbstractListModel(parent), : QAbstractListModel(parent)
m_pluginsManager(nullptr), , m_pluginsManager(nullptr)
m_lastRequestedEventsStartDate(QDate()), , m_lastRequestedEventsStartDate(QDate())
m_agendaNeedsUpdate(false) , m_agendaNeedsUpdate(false)
{ {
} }
DaysModel::~DaysModel() DaysModel::~DaysModel()
@ -50,7 +49,6 @@ int DaysModel::rowCount(const QModelIndex &parent) const
QVariant DaysModel::data(const QModelIndex &index, int role) const QVariant DaysModel::data(const QModelIndex &index, int role) const
{ {
if (index.isValid()) { if (index.isValid()) {
const DayData &currentData = m_data->at(index.row()); const DayData &currentData = m_data->at(index.row());
const QDate currentDate(currentData.yearNumber, currentData.monthNumber, currentData.dayNumber); const QDate currentDate(currentData.yearNumber, currentData.monthNumber, currentData.dayNumber);
@ -105,8 +103,7 @@ void DaysModel::onDataReady(const QMultiHash<QDate, CalendarEvents::EventData> &
} }
// only the containsEventItems roles may have changed // only the containsEventItems roles may have changed
Q_EMIT dataChanged(index(0, 0), index(m_data->count() - 1, 0), Q_EMIT dataChanged(index(0, 0), index(m_data->count() - 1, 0), {containsEventItems, containsMajorEventItems, containsMinorEventItems});
{containsEventItems, containsMajorEventItems, containsMinorEventItems});
Q_EMIT agendaUpdated(QDate::currentDate()); Q_EMIT agendaUpdated(QDate::currentDate());
} }
@ -131,8 +128,7 @@ void DaysModel::onEventModified(const CalendarEvents::EventData &data)
for (const QDate date : qAsConst(updatesList)) { for (const QDate date : qAsConst(updatesList)) {
const QModelIndex changedIndex = indexForDate(date); const QModelIndex changedIndex = indexForDate(date);
if (changedIndex.isValid()) { if (changedIndex.isValid()) {
Q_EMIT dataChanged(changedIndex, changedIndex, Q_EMIT dataChanged(changedIndex, changedIndex, {containsEventItems, containsMajorEventItems, containsMinorEventItems});
{containsEventItems, containsMajorEventItems, containsMinorEventItems});
} }
Q_EMIT agendaUpdated(date); Q_EMIT agendaUpdated(date);
} }
@ -158,14 +154,13 @@ void DaysModel::onEventRemoved(const QString &uid)
for (const QDate date : qAsConst(updatesList)) { for (const QDate date : qAsConst(updatesList)) {
const QModelIndex changedIndex = indexForDate(date); const QModelIndex changedIndex = indexForDate(date);
if (changedIndex.isValid()) { if (changedIndex.isValid()) {
Q_EMIT dataChanged(changedIndex, changedIndex, Q_EMIT dataChanged(changedIndex, changedIndex, {containsEventItems, containsMajorEventItems, containsMinorEventItems});
{containsEventItems, containsMajorEventItems, containsMinorEventItems});
} }
Q_EMIT agendaUpdated(date); Q_EMIT agendaUpdated(date);
} }
} }
QList<QObject*> DaysModel::eventsForDate(const QDate &date) QList<QObject *> DaysModel::eventsForDate(const QDate &date)
{ {
if (m_lastRequestedAgendaDate == date && !m_agendaNeedsUpdate) { if (m_lastRequestedAgendaDate == date && !m_agendaNeedsUpdate) {
return m_qmlData; return m_qmlData;
@ -231,7 +226,7 @@ bool DaysModel::hasMinorEventAtDate(const QDate &date) const
void DaysModel::setPluginsManager(QObject *manager) void DaysModel::setPluginsManager(QObject *manager)
{ {
EventPluginsManager *m = qobject_cast<EventPluginsManager*>(manager); EventPluginsManager *m = qobject_cast<EventPluginsManager *>(manager);
if (!m) { if (!m) {
return; return;
@ -244,27 +239,21 @@ void DaysModel::setPluginsManager(QObject *manager)
m_pluginsManager = m; m_pluginsManager = m;
connect(m_pluginsManager, &EventPluginsManager::dataReady, connect(m_pluginsManager, &EventPluginsManager::dataReady, this, &DaysModel::onDataReady);
this, &DaysModel::onDataReady); connect(m_pluginsManager, &EventPluginsManager::eventModified, this, &DaysModel::onEventModified);
connect(m_pluginsManager, &EventPluginsManager::eventModified, connect(m_pluginsManager, &EventPluginsManager::eventRemoved, this, &DaysModel::onEventRemoved);
this, &DaysModel::onEventModified); connect(m_pluginsManager, &EventPluginsManager::pluginsChanged, this, &DaysModel::update);
connect(m_pluginsManager, &EventPluginsManager::eventRemoved,
this, &DaysModel::onEventRemoved);
connect(m_pluginsManager, &EventPluginsManager::pluginsChanged,
this, &DaysModel::update);
QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection); QMetaObject::invokeMethod(this, "update", Qt::QueuedConnection);
} }
QHash<int, QByteArray> DaysModel::roleNames() const QHash<int, QByteArray> DaysModel::roleNames() const
{ {
return { return {{isCurrent, "isCurrent"},
{isCurrent, "isCurrent"}, {containsEventItems, "containsEventItems"},
{containsEventItems, "containsEventItems"}, {containsMajorEventItems, "containsMajorEventItems"},
{containsMajorEventItems, "containsMajorEventItems"}, {containsMinorEventItems, "containsMinorEventItems"},
{containsMinorEventItems, "containsMinorEventItems"}, {dayNumber, "dayNumber"},
{dayNumber, "dayNumber"}, {monthNumber, "monthNumber"},
{monthNumber, "monthNumber"}, {yearNumber, "yearNumber"}};
{yearNumber, "yearNumber"}
};
} }

View File

@ -22,12 +22,12 @@ class DaysModel : public QAbstractListModel
public: public:
enum Roles { enum Roles {
isCurrent = Qt::UserRole + 1, isCurrent = Qt::UserRole + 1,
//containsHolidayItems, // containsHolidayItems,
containsEventItems, containsEventItems,
containsMajorEventItems, containsMajorEventItems,
containsMinorEventItems, containsMinorEventItems,
//containsTodoItems, // containsTodoItems,
//containsJournalItems, // containsJournalItems,
dayNumber, dayNumber,
monthNumber, monthNumber,
yearNumber, yearNumber,
@ -41,7 +41,7 @@ public:
Q_INVOKABLE void setPluginsManager(QObject *manager); Q_INVOKABLE void setPluginsManager(QObject *manager);
Q_INVOKABLE QList<QObject*> eventsForDate(const QDate &date); Q_INVOKABLE QList<QObject *> eventsForDate(const QDate &date);
QHash<int, QByteArray> roleNames() const override; QHash<int, QByteArray> roleNames() const override;
@ -63,9 +63,9 @@ private:
EventPluginsManager *m_pluginsManager = nullptr; EventPluginsManager *m_pluginsManager = nullptr;
QList<DayData> *m_data = nullptr; QList<DayData> *m_data = nullptr;
QList<QObject*> m_qmlData; QList<QObject *> m_qmlData;
QDate m_lastRequestedAgendaDate; QDate m_lastRequestedAgendaDate;
QList<CalendarEvents::CalendarEventsPlugin*> m_eventPlugins; QList<CalendarEvents::CalendarEventsPlugin *> m_eventPlugins;
QMultiHash<QDate, CalendarEvents::EventData> m_eventsData; QMultiHash<QDate, CalendarEvents::EventData> m_eventsData;
QDate m_lastRequestedEventsStartDate; // this is always this+42 days QDate m_lastRequestedEventsStartDate; // this is always this+42 days
bool m_agendaNeedsUpdate; bool m_agendaNeedsUpdate;

View File

@ -9,8 +9,8 @@
#include <KLocalizedString> #include <KLocalizedString>
EventDataDecorator::EventDataDecorator(const CalendarEvents::EventData &data, QObject *parent) EventDataDecorator::EventDataDecorator(const CalendarEvents::EventData &data, QObject *parent)
: QObject(parent), : QObject(parent)
m_data(data) , m_data(data)
{ {
} }
@ -47,12 +47,12 @@ QString EventDataDecorator::description() const
QString EventDataDecorator::eventType() const QString EventDataDecorator::eventType() const
{ {
switch (m_data.type()) { switch (m_data.type()) {
case CalendarEvents::EventData::Holiday: case CalendarEvents::EventData::Holiday:
return i18nc("Agenda listview section title", "Holidays"); return i18nc("Agenda listview section title", "Holidays");
case CalendarEvents::EventData::Event: case CalendarEvents::EventData::Event:
return i18nc("Agenda listview section title", "Events"); return i18nc("Agenda listview section title", "Events");
case CalendarEvents::EventData::Todo: case CalendarEvents::EventData::Todo:
return i18nc("Agenda listview section title", "Todo"); return i18nc("Agenda listview section title", "Todo");
} }
return i18nc("Means 'Other calendar items'", "Other"); return i18nc("Means 'Other calendar items'", "Other");
} }

View File

@ -7,8 +7,8 @@
#ifndef EVENTDATADECORATOR_H #ifndef EVENTDATADECORATOR_H
#define EVENTDATADECORATOR_H #define EVENTDATADECORATOR_H
#include <QObject>
#include <QDateTime> #include <QDateTime>
#include <QObject>
#include <QString> #include <QString>
#include <CalendarEvents/CalendarEventsPlugin> #include <CalendarEvents/CalendarEventsPlugin>

View File

@ -8,12 +8,12 @@
#include <CalendarEvents/CalendarEventsPlugin> #include <CalendarEvents/CalendarEventsPlugin>
#include <QCoreApplication>
#include <QAbstractListModel> #include <QAbstractListModel>
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QJsonObject> #include <QJsonObject>
#include <QPluginLoader> #include <QPluginLoader>
#include <QDir>
#include <QDebug>
#include <KPluginLoader> #include <KPluginLoader>
#include <KPluginMetaData> #include <KPluginMetaData>
@ -22,7 +22,8 @@ class EventPluginsModel : public QAbstractListModel
{ {
Q_OBJECT Q_OBJECT
public: public:
EventPluginsModel(EventPluginsManager *manager) : QAbstractListModel(manager) EventPluginsModel(EventPluginsManager *manager)
: QAbstractListModel(manager)
{ {
m_manager = manager; m_manager = manager;
m_roles = QAbstractListModel::roleNames(); m_roles = QAbstractListModel::roleNames();
@ -64,28 +65,26 @@ public:
const EventPluginsManager::PluginData metadata = it.value(); const EventPluginsManager::PluginData metadata = it.value();
switch (role) { switch (role) {
case Qt::DisplayRole: case Qt::DisplayRole:
return metadata.name; return metadata.name;
case Qt::ToolTipRole: case Qt::ToolTipRole:
return metadata.desc; return metadata.desc;
case Qt::DecorationRole: case Qt::DecorationRole:
return metadata.icon; return metadata.icon;
case Qt::UserRole: case Qt::UserRole: {
{ // The currentPlugin path contains the full path including
// The currentPlugin path contains the full path including // the plugin filename, so it needs to be cut off from the last '/'
// the plugin filename, so it needs to be cut off from the last '/' const QStringRef pathRef = currentPlugin.leftRef(currentPlugin.lastIndexOf(QLatin1Char('/')));
const QStringRef pathRef = currentPlugin.leftRef(currentPlugin.lastIndexOf(QLatin1Char('/'))); const QString qmlFilePath = metadata.configUi;
const QString qmlFilePath = metadata.configUi; return QString(pathRef % QLatin1Char('/') % qmlFilePath);
return QString(pathRef % QLatin1Char('/') % qmlFilePath); }
} case Qt::UserRole + 1:
case Qt::UserRole + 1: return currentPlugin;
return currentPlugin; case Qt::EditRole:
case Qt::EditRole: return m_manager->m_enabledPlugins.contains(currentPlugin);
return m_manager->m_enabledPlugins.contains(currentPlugin);
} }
return QVariant(); return QVariant();
} }
bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override bool setData(const QModelIndex &index, const QVariant &value, int role = Qt::EditRole) override
@ -123,18 +122,12 @@ private:
EventPluginsManager::EventPluginsManager(QObject *parent) EventPluginsManager::EventPluginsManager(QObject *parent)
: QObject(parent) : QObject(parent)
{ {
auto plugins = KPluginLoader::findPlugins( auto plugins = KPluginLoader::findPlugins(QStringLiteral("plasmacalendarplugins"), [](const KPluginMetaData &md) {
QStringLiteral("plasmacalendarplugins"), return md.serviceTypes().contains(QLatin1String("PlasmaCalendar/Plugin"));
[](const KPluginMetaData &md) { });
return md.serviceTypes().contains(QLatin1String("PlasmaCalendar/Plugin"));
});
for (const KPluginMetaData &plugin : qAsConst(plugins)) { for (const KPluginMetaData &plugin : qAsConst(plugins)) {
m_availablePlugins.insert(plugin.fileName(), m_availablePlugins.insert(plugin.fileName(),
{ plugin.name(), {plugin.name(), plugin.description(), plugin.iconName(), plugin.value(QStringLiteral("X-KDE-PlasmaCalendar-ConfigUi"))});
plugin.description(),
plugin.iconName(),
plugin.value(QStringLiteral("X-KDE-PlasmaCalendar-ConfigUi"))
});
} }
// Fallback for legacy pre-KPlugin plugins so we can still load them // Fallback for legacy pre-KPlugin plugins so we can still load them
@ -160,11 +153,10 @@ EventPluginsManager::EventPluginsManager(QObject *parent)
if (loader.metaData().value(QStringLiteral("IID")) == QLatin1String("org.kde.CalendarEventsPlugin")) { if (loader.metaData().value(QStringLiteral("IID")) == QLatin1String("org.kde.CalendarEventsPlugin")) {
const auto md = loader.metaData().value(QStringLiteral("MetaData")).toObject(); const auto md = loader.metaData().value(QStringLiteral("MetaData")).toObject();
m_availablePlugins.insert(absolutePath, m_availablePlugins.insert(absolutePath,
{ md.value(QStringLiteral("Name")).toString(), {md.value(QStringLiteral("Name")).toString(),
md.value(QStringLiteral("Description")).toString(), md.value(QStringLiteral("Description")).toString(),
md.value(QStringLiteral("Icon")).toString(), md.value(QStringLiteral("Icon")).toString(),
md.value(QStringLiteral("ConfigUi")).toString() md.value(QStringLiteral("ConfigUi")).toString()});
});
} }
} }
} }
@ -229,19 +221,16 @@ void EventPluginsManager::loadPlugin(const QString &absolutePath)
QObject *obj = loader.instance(); QObject *obj = loader.instance();
if (obj) { if (obj) {
CalendarEvents::CalendarEventsPlugin *eventsPlugin = qobject_cast<CalendarEvents::CalendarEventsPlugin*>(obj); CalendarEvents::CalendarEventsPlugin *eventsPlugin = qobject_cast<CalendarEvents::CalendarEventsPlugin *>(obj);
if (eventsPlugin) { if (eventsPlugin) {
qDebug() << "Loading Calendar plugin" << eventsPlugin; qDebug() << "Loading Calendar plugin" << eventsPlugin;
eventsPlugin->setProperty("pluginPath", absolutePath); eventsPlugin->setProperty("pluginPath", absolutePath);
m_plugins << eventsPlugin; m_plugins << eventsPlugin;
// Connect the relay signals // Connect the relay signals
connect(eventsPlugin, &CalendarEvents::CalendarEventsPlugin::dataReady, connect(eventsPlugin, &CalendarEvents::CalendarEventsPlugin::dataReady, this, &EventPluginsManager::dataReady);
this, &EventPluginsManager::dataReady); connect(eventsPlugin, &CalendarEvents::CalendarEventsPlugin::eventModified, this, &EventPluginsManager::eventModified);
connect(eventsPlugin, &CalendarEvents::CalendarEventsPlugin::eventModified, connect(eventsPlugin, &CalendarEvents::CalendarEventsPlugin::eventRemoved, this, &EventPluginsManager::eventRemoved);
this, &EventPluginsManager::eventModified);
connect(eventsPlugin, &CalendarEvents::CalendarEventsPlugin::eventRemoved,
this, &EventPluginsManager::eventRemoved);
} else { } else {
// not our/valid plugin, so unload it // not our/valid plugin, so unload it
loader.unload(); loader.unload();
@ -251,12 +240,12 @@ void EventPluginsManager::loadPlugin(const QString &absolutePath)
} }
} }
QList<CalendarEvents::CalendarEventsPlugin*> EventPluginsManager::plugins() const QList<CalendarEvents::CalendarEventsPlugin *> EventPluginsManager::plugins() const
{ {
return m_plugins; return m_plugins;
} }
QAbstractListModel* EventPluginsManager::pluginsModel() const QAbstractListModel *EventPluginsManager::pluginsModel() const
{ {
return m_model; return m_model;
} }

View File

@ -7,11 +7,12 @@
#ifndef EVENTPLUGINSMANAGER_H #ifndef EVENTPLUGINSMANAGER_H
#define EVENTPLUGINSMANAGER_H #define EVENTPLUGINSMANAGER_H
#include <QObject>
#include <QMap> #include <QMap>
#include <QObject>
#include <QStringList> #include <QStringList>
namespace CalendarEvents { namespace CalendarEvents
{
class CalendarEventsPlugin; class CalendarEventsPlugin;
class EventData; class EventData;
} }
@ -28,8 +29,8 @@ public:
explicit EventPluginsManager(QObject *parent = nullptr); explicit EventPluginsManager(QObject *parent = nullptr);
~EventPluginsManager(); ~EventPluginsManager();
QList<CalendarEvents::CalendarEventsPlugin*> plugins() const; QList<CalendarEvents::CalendarEventsPlugin *> plugins() const;
QAbstractListModel* pluginsModel() const; QAbstractListModel *pluginsModel() const;
// This is a helper function to set which plugins // This is a helper function to set which plugins
// are enabled without needing to go through setEnabledPlugins // are enabled without needing to go through setEnabledPlugins
@ -55,7 +56,7 @@ private:
friend class EventPluginsModel; friend class EventPluginsModel;
EventPluginsModel *m_model = nullptr; EventPluginsModel *m_model = nullptr;
QList<CalendarEvents::CalendarEventsPlugin*> m_plugins; QList<CalendarEvents::CalendarEventsPlugin *> m_plugins;
struct PluginData { struct PluginData {
QString name; QString name;
QString desc; QString desc;
@ -67,4 +68,3 @@ private:
}; };
#endif #endif

View File

@ -8,9 +8,9 @@
#include "colorscope.h" #include "colorscope.h"
#include <QColor>
#include <QQmlContext> #include <QQmlContext>
#include <QQmlEngine> #include <QQmlEngine>
#include <QColor>
#include <QQuickWindow> #include <QQuickWindow>
#include <PlasmaQuick/AppletQuickItem> #include <PlasmaQuick/AppletQuickItem>
@ -20,11 +20,11 @@ QHash<QObject *, ColorScope *> ColorScope::s_attachedScopes = QHash<QObject *, C
QWeakPointer<Plasma::Theme> ColorScope::s_theme; QWeakPointer<Plasma::Theme> ColorScope::s_theme;
ColorScope::ColorScope(QQuickItem *parent, QObject *parentObject) ColorScope::ColorScope(QQuickItem *parent, QObject *parentObject)
: QQuickItem(parent), : QQuickItem(parent)
m_inherit(false), , m_inherit(false)
m_group(Plasma::Theme::NormalColorGroup), , m_group(Plasma::Theme::NormalColorGroup)
m_parent(parentObject), , m_parent(parentObject)
m_actualGroup(Plasma::Theme::NormalColorGroup) , m_actualGroup(Plasma::Theme::NormalColorGroup)
{ {
m_theme = s_theme.toStrongRef(); m_theme = s_theme.toStrongRef();
if (!m_theme) { if (!m_theme) {
@ -38,20 +38,17 @@ ColorScope::ColorScope(QQuickItem *parent, QObject *parentObject)
connect(this, &ColorScope::colorGroupChanged, this, &ColorScope::colorsChanged); connect(this, &ColorScope::colorGroupChanged, this, &ColorScope::colorsChanged);
if (parentObject && qobject_cast<QQuickItem *>(parentObject)) { if (parentObject && qobject_cast<QQuickItem *>(parentObject)) {
connect(static_cast<QQuickItem *>(parentObject), &QQuickItem::windowChanged, connect(static_cast<QQuickItem *>(parentObject), &QQuickItem::windowChanged, this, [this]() {
this, [this]() { findParentScope();
findParentScope(); checkColorGroupChanged();
checkColorGroupChanged(); });
});
connect(static_cast<QQuickItem *>(parentObject), &QQuickItem::parentChanged, connect(static_cast<QQuickItem *>(parentObject), &QQuickItem::parentChanged, this, [this]() {
this, [this]() { findParentScope();
findParentScope(); checkColorGroupChanged();
checkColorGroupChanged(); });
});
} else if (parent) { } else if (parent) {
connect(parent, &QQuickItem::parentChanged, connect(parent, &QQuickItem::parentChanged, this, &ColorScope::checkColorGroupChanged);
this, &ColorScope::checkColorGroupChanged);
} }
} }
@ -77,21 +74,19 @@ ColorScope *ColorScope::qmlAttachedProperties(QObject *object)
return s; return s;
} }
void ColorScope::setParentScope(ColorScope* parentScope) void ColorScope::setParentScope(ColorScope *parentScope)
{ {
if (parentScope == m_parentScope) if (parentScope == m_parentScope)
return; return;
if (m_parentScope) { if (m_parentScope) {
disconnect(m_parentScope.data(), &ColorScope::colorGroupChanged, disconnect(m_parentScope.data(), &ColorScope::colorGroupChanged, this, &ColorScope::checkColorGroupChanged);
this, &ColorScope::checkColorGroupChanged);
} }
m_parentScope = parentScope; m_parentScope = parentScope;
if (parentScope) { if (parentScope) {
connect(parentScope, &ColorScope::colorGroupChanged, connect(parentScope, &ColorScope::colorGroupChanged, this, &ColorScope::checkColorGroupChanged);
this, &ColorScope::checkColorGroupChanged);
} }
} }
@ -198,7 +193,7 @@ void ColorScope::setInherit(bool inherit)
void ColorScope::itemChange(ItemChange change, const ItemChangeData &value) void ColorScope::itemChange(ItemChange change, const ItemChangeData &value)
{ {
if (change == QQuickItem::ItemSceneChange) { if (change == QQuickItem::ItemSceneChange) {
//we have a window: create the representations if needed // we have a window: create the representations if needed
if (value.window) { if (value.window) {
findParentScope(); findParentScope();
checkColorGroupChanged(); checkColorGroupChanged();

View File

@ -7,12 +7,12 @@
#ifndef COLORSCOPE_H #ifndef COLORSCOPE_H
#define COLORSCOPE_H #define COLORSCOPE_H
#include <QQuickItem>
#include <QPointer>
#include <QSharedPointer>
#include <QVariant>
#include <Plasma/Plasma> #include <Plasma/Plasma>
#include <Plasma/Theme> #include <Plasma/Theme>
#include <QPointer>
#include <QQuickItem>
#include <QSharedPointer>
#include <QVariant>
class QQuickItem; class QQuickItem;
@ -61,7 +61,7 @@ class ColorScope : public QQuickItem
* Color of foreground objects with a "neutral message" connotation (usually yellow) * Color of foreground objects with a "neutral message" connotation (usually yellow)
*/ */
Q_PROPERTY(QColor neutralTextColor READ neutralTextColor NOTIFY colorsChanged) Q_PROPERTY(QColor neutralTextColor READ neutralTextColor NOTIFY colorsChanged)
/** /**
* Color of foreground objects with a "negative message" connotation (usually red) * Color of foreground objects with a "negative message" connotation (usually red)
*/ */
@ -79,7 +79,7 @@ class ColorScope : public QQuickItem
Q_PROPERTY(bool inherit READ inherit WRITE setInherit NOTIFY inheritChanged) Q_PROPERTY(bool inherit READ inherit WRITE setInherit NOTIFY inheritChanged)
public: public:
/// @cond INTERNAL_DOCS /// @cond INTERNAL_DOCS
explicit ColorScope(QQuickItem *parent = nullptr, QObject *parentObject = nullptr); explicit ColorScope(QQuickItem *parent = nullptr, QObject *parentObject = nullptr);
~ColorScope() override; ~ColorScope() override;
@ -101,7 +101,7 @@ public:
////NEEDED BY QML TO CREATE ATTACHED PROPERTIES ////NEEDED BY QML TO CREATE ATTACHED PROPERTIES
static ColorScope *qmlAttachedProperties(QObject *object); static ColorScope *qmlAttachedProperties(QObject *object);
/// @endcond /// @endcond
ColorScope *findParentScope(); ColorScope *findParentScope();
void itemChange(ItemChange change, const ItemChangeData &value) override; void itemChange(ItemChange change, const ItemChangeData &value) override;
@ -113,7 +113,7 @@ Q_SIGNALS:
private: private:
void checkColorGroupChanged(); void checkColorGroupChanged();
void setParentScope(ColorScope * parentScope); void setParentScope(ColorScope *parentScope);
bool m_inherit; bool m_inherit;
Plasma::Theme::ColorGroup m_group; Plasma::Theme::ColorGroup m_group;
@ -126,7 +126,6 @@ private:
static QWeakPointer<Plasma::Theme> s_theme; static QWeakPointer<Plasma::Theme> s_theme;
QSharedPointer<Plasma::Theme> m_theme; QSharedPointer<Plasma::Theme> m_theme;
}; };
QML_DECLARE_TYPEINFO(ColorScope, QML_HAS_ATTACHED_PROPERTIES) QML_DECLARE_TYPEINFO(ColorScope, QML_HAS_ATTACHED_PROPERTIES)

View File

@ -18,16 +18,16 @@
#include <plasma/framesvg.h> #include <plasma/framesvg.h>
#include <plasma/svg.h> #include <plasma/svg.h>
#include "datasource.h" #include "colorscope.h"
#include "datamodel.h" #include "datamodel.h"
#include "datasource.h"
#include "dialog.h"
#include "framesvgitem.h" #include "framesvgitem.h"
#include "iconitem.h"
#include "quicktheme.h"
#include "serviceoperationstatus.h"
#include "svgitem.h" #include "svgitem.h"
#include "theme.h" #include "theme.h"
#include "dialog.h"
#include "iconitem.h"
#include "serviceoperationstatus.h"
#include "colorscope.h"
#include "quicktheme.h"
#include "tooltip.h" #include "tooltip.h"
#include "units.h" #include "units.h"
@ -63,7 +63,7 @@ void CoreBindingsPlugin::registerTypes(const char *uri)
Q_ASSERT(uri == QByteArray("org.kde.plasma.core")); Q_ASSERT(uri == QByteArray("org.kde.plasma.core"));
qmlRegisterUncreatableType<Plasma::Types>(uri, 2, 0, "Types", {}); qmlRegisterUncreatableType<Plasma::Types>(uri, 2, 0, "Types", {});
qmlRegisterSingletonType<Units>(uri, 2, 0, "Units", [](QQmlEngine *engine, QJSEngine*) -> QObject* { qmlRegisterSingletonType<Units>(uri, 2, 0, "Units", [](QQmlEngine *engine, QJSEngine *) -> QObject * {
engine->setObjectOwnership(&Units::instance(), QQmlEngine::CppOwnership); engine->setObjectOwnership(&Units::instance(), QQmlEngine::CppOwnership);
return &Units::instance(); return &Units::instance();
}); });
@ -73,8 +73,10 @@ void CoreBindingsPlugin::registerTypes(const char *uri)
qmlRegisterType<Plasma::SvgItem>(uri, 2, 0, "SvgItem"); qmlRegisterType<Plasma::SvgItem>(uri, 2, 0, "SvgItem");
qmlRegisterType<Plasma::FrameSvgItem>(uri, 2, 0, "FrameSvgItem"); qmlRegisterType<Plasma::FrameSvgItem>(uri, 2, 0, "FrameSvgItem");
//qmlRegisterType<ThemeProxy>(uri, 2, 0, "Theme"); // qmlRegisterType<ThemeProxy>(uri, 2, 0, "Theme");
qmlRegisterSingletonType<Plasma::QuickTheme>(uri, 2, 0, "Theme", [](QQmlEngine* engine, QJSEngine*) -> QObject* { return new Plasma::QuickTheme(engine); }); qmlRegisterSingletonType<Plasma::QuickTheme>(uri, 2, 0, "Theme", [](QQmlEngine *engine, QJSEngine *) -> QObject * {
return new Plasma::QuickTheme(engine);
});
qmlRegisterType<ColorScope>(uri, 2, 0, "ColorScope"); qmlRegisterType<ColorScope>(uri, 2, 0, "ColorScope");
qmlRegisterType<Plasma::DataSource>(uri, 2, 0, "DataSource"); qmlRegisterType<Plasma::DataSource>(uri, 2, 0, "DataSource");
@ -98,16 +100,16 @@ void CoreBindingsPlugin::registerTypes(const char *uri)
// qRegisterMetaType<Plasma::ServiceJob *>(); // qRegisterMetaType<Plasma::ServiceJob *>();
// For that also change all usages with those methods to use the fully namespaced type name // For that also change all usages with those methods to use the fully namespaced type name
// in the method signature. // in the method signature.
QT_WARNING_PUSH QT_WARNING_PUSH
QT_WARNING_DISABLE_CLANG("-Wdeprecated-declarations") QT_WARNING_DISABLE_CLANG("-Wdeprecated-declarations")
QT_WARNING_DISABLE_GCC("-Wdeprecated-declarations") QT_WARNING_DISABLE_GCC("-Wdeprecated-declarations")
// Do not to port these two for KF5 to // Do not to port these two for KF5 to
// qmlRegisterInterface<Plasma::T>(uri, 1); // qmlRegisterInterface<Plasma::T>(uri, 1);
// as this will incompatibly register with the fully namespaced name "Plasma::T", // as this will incompatibly register with the fully namespaced name "Plasma::T",
// not just the now explicitly passed alias name "T" // not just the now explicitly passed alias name "T"
qmlRegisterInterface<Plasma::Service>("Service"); qmlRegisterInterface<Plasma::Service>("Service");
qmlRegisterInterface<Plasma::ServiceJob>("ServiceJob"); qmlRegisterInterface<Plasma::ServiceJob>("ServiceJob");
QT_WARNING_POP QT_WARNING_POP
qmlRegisterType<ServiceOperationStatus>(uri, 2, 0, "ServiceOperationStatus"); qmlRegisterType<ServiceOperationStatus>(uri, 2, 0, "ServiceOperationStatus");
qmlRegisterAnonymousType<QAbstractItemModel>(uri, 1); qmlRegisterAnonymousType<QAbstractItemModel>(uri, 1);
@ -117,5 +119,3 @@ QT_WARNING_POP
qmlRegisterType<Plasma::WindowThumbnail>(uri, 2, 0, "WindowThumbnail"); qmlRegisterType<Plasma::WindowThumbnail>(uri, 2, 0, "WindowThumbnail");
} }

View File

@ -13,19 +13,15 @@
namespace Plasma namespace Plasma
{ {
SortFilterModel::SortFilterModel(QObject *parent) SortFilterModel::SortFilterModel(QObject *parent)
: QSortFilterProxyModel(parent) : QSortFilterProxyModel(parent)
{ {
setObjectName(QStringLiteral("SortFilterModel")); setObjectName(QStringLiteral("SortFilterModel"));
setDynamicSortFilter(true); setDynamicSortFilter(true);
connect(this, &QAbstractItemModel::rowsInserted, connect(this, &QAbstractItemModel::rowsInserted, this, &SortFilterModel::countChanged);
this, &SortFilterModel::countChanged); connect(this, &QAbstractItemModel::rowsRemoved, this, &SortFilterModel::countChanged);
connect(this, &QAbstractItemModel::rowsRemoved, connect(this, &QAbstractItemModel::modelReset, this, &SortFilterModel::countChanged);
this, &SortFilterModel::countChanged); connect(this, &SortFilterModel::countChanged, this, &SortFilterModel::syncRoleNames);
connect(this, &QAbstractItemModel::modelReset,
this, &SortFilterModel::countChanged);
connect(this, &SortFilterModel::countChanged, this, &SortFilterModel::syncRoleNames);
} }
SortFilterModel::~SortFilterModel() SortFilterModel::~SortFilterModel()
@ -49,10 +45,10 @@ void SortFilterModel::syncRoleNames()
setSortRole(m_sortRole); setSortRole(m_sortRole);
} }
QHash<int,QByteArray> SortFilterModel::roleNames() const QHash<int, QByteArray> SortFilterModel::roleNames() const
{ {
if (sourceModel()) { if (sourceModel()) {
return sourceModel()->roleNames(); return sourceModel()->roleNames();
} }
return {}; return {};
} }
@ -82,7 +78,7 @@ void SortFilterModel::setModel(QAbstractItemModel *model)
Q_EMIT sourceModelChanged(model); Q_EMIT sourceModelChanged(model);
} }
bool SortFilterModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const bool SortFilterModel::filterAcceptsRow(int source_row, const QModelIndex &source_parent) const
{ {
if (m_filterCallback.isCallable()) { if (m_filterCallback.isCallable()) {
QJSValueList args; QJSValueList args;
@ -132,7 +128,7 @@ QJSValue SortFilterModel::filterCallback() const
return m_filterCallback; return m_filterCallback;
} }
void SortFilterModel::setFilterCallback(const QJSValue& callback) void SortFilterModel::setFilterCallback(const QJSValue &callback)
{ {
if (m_filterCallback.strictlyEquals(callback)) { if (m_filterCallback.strictlyEquals(callback)) {
return; return;
@ -222,22 +218,19 @@ int SortFilterModel::mapRowFromSource(int row) const
} }
DataModel::DataModel(QObject *parent) DataModel::DataModel(QObject *parent)
: QAbstractItemModel(parent), : QAbstractItemModel(parent)
m_dataSource(nullptr), , m_dataSource(nullptr)
m_maxRoleId(Qt::UserRole + 1) , m_maxRoleId(Qt::UserRole + 1)
{ {
//There is one reserved role name: DataEngineSource // There is one reserved role name: DataEngineSource
m_roleNames[m_maxRoleId] = QByteArrayLiteral("DataEngineSource"); m_roleNames[m_maxRoleId] = QByteArrayLiteral("DataEngineSource");
m_roleIds[QStringLiteral("DataEngineSource")] = m_maxRoleId; m_roleIds[QStringLiteral("DataEngineSource")] = m_maxRoleId;
++m_maxRoleId; ++m_maxRoleId;
setObjectName(QStringLiteral("DataModel")); setObjectName(QStringLiteral("DataModel"));
connect(this, &QAbstractItemModel::rowsInserted, connect(this, &QAbstractItemModel::rowsInserted, this, &DataModel::countChanged);
this, &DataModel::countChanged); connect(this, &QAbstractItemModel::rowsRemoved, this, &DataModel::countChanged);
connect(this, &QAbstractItemModel::rowsRemoved, connect(this, &QAbstractItemModel::modelReset, this, &DataModel::countChanged);
this, &DataModel::countChanged);
connect(this, &QAbstractItemModel::modelReset,
this, &DataModel::countChanged);
} }
DataModel::~DataModel() DataModel::~DataModel()
@ -251,7 +244,7 @@ void DataModel::dataUpdated(const QString &sourceName, const QVariantMap &data)
} }
if (m_keyRoleFilter.isEmpty()) { if (m_keyRoleFilter.isEmpty()) {
//an item is represented by a source: keys are roles m_roleLevel == FirstLevel // an item is represented by a source: keys are roles m_roleLevel == FirstLevel
QVariantList list; QVariantList list;
if (!m_dataSource->data()->isEmpty()) { if (!m_dataSource->data()->isEmpty()) {
@ -270,12 +263,11 @@ void DataModel::dataUpdated(const QString &sourceName, const QVariantMap &data)
} }
setItems(QString(), list); setItems(QString(), list);
} else { } else {
//a key that matches the one we want exists and is a list of DataEngine::Data // a key that matches the one we want exists and is a list of DataEngine::Data
if (data.contains(m_keyRoleFilter) && if (data.contains(m_keyRoleFilter) && data.value(m_keyRoleFilter).canConvert<QVariantList>()) {
data.value(m_keyRoleFilter).canConvert<QVariantList>()) {
setItems(sourceName, data.value(m_keyRoleFilter).value<QVariantList>()); setItems(sourceName, data.value(m_keyRoleFilter).value<QVariantList>());
} else if (m_keyRoleFilterRE.isValid()) { } else if (m_keyRoleFilterRE.isValid()) {
//try to match the key we want with a regular expression if set // try to match the key we want with a regular expression if set
QVariantList list; QVariantList list;
QVariantMap::const_iterator i; QVariantMap::const_iterator i;
for (i = data.constBegin(); i != data.constEnd(); ++i) { for (i = data.constBegin(); i != data.constEnd(); ++i) {
@ -310,12 +302,9 @@ void DataModel::setDataSource(QObject *object)
dataUpdated(key, m_dataSource->data()->value(key).value<Plasma::DataEngine::Data>()); dataUpdated(key, m_dataSource->data()->value(key).value<Plasma::DataEngine::Data>());
} }
connect(m_dataSource, &DataSource::newData, connect(m_dataSource, &DataSource::newData, this, &DataModel::dataUpdated);
this, &DataModel::dataUpdated); connect(m_dataSource, &DataSource::sourceRemoved, this, &DataModel::removeSource);
connect(m_dataSource, &DataSource::sourceRemoved, connect(m_dataSource, &DataSource::sourceDisconnected, this, &DataModel::removeSource);
this, &DataModel::removeSource);
connect(m_dataSource, &DataSource::sourceDisconnected,
this, &DataModel::removeSource);
} }
QObject *DataModel::dataSource() const QObject *DataModel::dataSource() const
@ -373,18 +362,18 @@ void DataModel::setItems(const QString &sourceName, const QVariantList &list)
const int delta = list.length() - oldLength; const int delta = list.length() - oldLength;
const bool firstRun = m_items.isEmpty(); const bool firstRun = m_items.isEmpty();
//At what row number the first item associated to this source starts // At what row number the first item associated to this source starts
int sourceIndex = 0; int sourceIndex = 0;
QMap<QString, QVector<QVariant> >::const_iterator i; QMap<QString, QVector<QVariant>>::const_iterator i;
for (i = m_items.constBegin(); i != m_items.constEnd(); ++i) { for (i = m_items.constBegin(); i != m_items.constEnd(); ++i) {
if (i.key() == sourceName) { if (i.key() == sourceName) {
break; break;
} }
sourceIndex += i.value().count(); sourceIndex += i.value().count();
} }
//signal as inserted the rows at the end, all the other rows will signal a dataupdated. // signal as inserted the rows at the end, all the other rows will signal a dataupdated.
//better than a model reset because doesn't cause deletion and re-creation of every list item on a qml ListView, repeaters etc. // better than a model reset because doesn't cause deletion and re-creation of every list item on a qml ListView, repeaters etc.
//the first run it gets reset because otherwise setRoleNames gets broken // the first run it gets reset because otherwise setRoleNames gets broken
if (firstRun) { if (firstRun) {
beginResetModel(); beginResetModel();
} else if (delta > 0) { } else if (delta > 0) {
@ -392,7 +381,7 @@ void DataModel::setItems(const QString &sourceName, const QVariantList &list)
} else if (delta < 0) { } else if (delta < 0) {
beginRemoveRows(QModelIndex(), sourceIndex + list.length(), sourceIndex + oldLength - 1); beginRemoveRows(QModelIndex(), sourceIndex + list.length(), sourceIndex + oldLength - 1);
} }
//convert to vector, so data() will be O(1) // convert to vector, so data() will be O(1)
m_items[sourceName] = list.toVector(); m_items[sourceName] = list.toVector();
if (!list.isEmpty()) { if (!list.isEmpty()) {
@ -434,8 +423,7 @@ void DataModel::setItems(const QString &sourceName, const QVariantList &list)
} else if (delta < 0) { } else if (delta < 0) {
endRemoveRows(); endRemoveRows();
} }
Q_EMIT dataChanged(createIndex(sourceIndex, 0), Q_EMIT dataChanged(createIndex(sourceIndex, 0), createIndex(sourceIndex + qMin(list.length(), oldLength), 0));
createIndex(sourceIndex + qMin(list.length(), oldLength), 0));
} }
QHash<int, QByteArray> DataModel::roleNames() const QHash<int, QByteArray> DataModel::roleNames() const
@ -445,10 +433,10 @@ QHash<int, QByteArray> DataModel::roleNames() const
void DataModel::removeSource(const QString &sourceName) void DataModel::removeSource(const QString &sourceName)
{ {
//FIXME: find a way to remove only the proper things also in the case where sources are items // FIXME: find a way to remove only the proper things also in the case where sources are items
if (m_keyRoleFilter.isEmpty()) { if (m_keyRoleFilter.isEmpty()) {
//source name in the map, linear scan // source name in the map, linear scan
for (int i = 0; i < m_items.value(QString()).count(); ++i) { for (int i = 0; i < m_items.value(QString()).count(); ++i) {
if (m_items.value(QString())[i].value<QVariantMap>().value(QStringLiteral("DataEngineSource")) == sourceName) { if (m_items.value(QString())[i].value<QVariantMap>().value(QStringLiteral("DataEngineSource")) == sourceName) {
beginRemoveRows(QModelIndex(), i, i); beginRemoveRows(QModelIndex(), i, i);
@ -459,7 +447,7 @@ void DataModel::removeSource(const QString &sourceName)
} }
} else { } else {
if (m_items.contains(sourceName)) { if (m_items.contains(sourceName)) {
//At what row number the first item associated to this source starts // At what row number the first item associated to this source starts
int sourceIndex = 0; int sourceIndex = 0;
for (auto i = m_items.constBegin(); i != m_items.constEnd(); ++i) { for (auto i = m_items.constBegin(); i != m_items.constEnd(); ++i) {
if (i.key() == sourceName) { if (i.key() == sourceName) {
@ -468,7 +456,7 @@ void DataModel::removeSource(const QString &sourceName)
sourceIndex += i.value().count(); sourceIndex += i.value().count();
} }
//source name as key of the map // source name as key of the map
int count = m_items.value(sourceName).count(); int count = m_items.value(sourceName).count();
if (count > 0) { if (count > 0) {
@ -484,15 +472,14 @@ void DataModel::removeSource(const QString &sourceName)
QVariant DataModel::data(const QModelIndex &index, int role) const QVariant DataModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid() || index.column() > 0 || if (!index.isValid() || index.column() > 0 || index.row() < 0 || index.row() >= countItems()) {
index.row() < 0 || index.row() >= countItems()) {
return QVariant(); return QVariant();
} }
int count = 0; int count = 0;
int actualRow = 0; int actualRow = 0;
QString source; QString source;
QMap<QString, QVector<QVariant> >::const_iterator i; QMap<QString, QVector<QVariant>>::const_iterator i;
for (i = m_items.constBegin(); i != m_items.constEnd(); ++i) { for (i = m_items.constBegin(); i != m_items.constEnd(); ++i) {
const int oldCount = count; const int oldCount = count;
count += i.value().count(); count += i.value().count();
@ -504,8 +491,8 @@ QVariant DataModel::data(const QModelIndex &index, int role) const
} }
} }
//is it the reserved role: DataEngineSource ? // is it the reserved role: DataEngineSource ?
//also, if each source is an item DataEngineSource is a role between all the others, otherwise we know it from the role variable // also, if each source is an item DataEngineSource is a role between all the others, otherwise we know it from the role variable
if (!m_keyRoleFilter.isEmpty() && m_roleNames.value(role) == "DataEngineSource") { if (!m_keyRoleFilter.isEmpty() && m_roleNames.value(role) == "DataEngineSource") {
return source; return source;
} else { } else {
@ -540,8 +527,8 @@ QModelIndex DataModel::parent(const QModelIndex &child) const
int DataModel::rowCount(const QModelIndex &parent) const int DataModel::rowCount(const QModelIndex &parent) const
{ {
//this is not a tree // this is not a tree
//TODO: make it possible some day? // TODO: make it possible some day?
if (parent.isValid()) { if (parent.isValid()) {
return 0; return 0;
} }
@ -572,4 +559,3 @@ QVariantMap DataModel::get(int row) const
} }
} }

View File

@ -18,7 +18,6 @@ class QTimer;
namespace Plasma namespace Plasma
{ {
class DataSource; class DataSource;
class DataModel; class DataModel;
@ -134,7 +133,7 @@ Q_SIGNALS:
protected: protected:
int roleNameToId(const QString &name) const; int roleNameToId(const QString &name) const;
bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override; bool filterAcceptsRow(int source_row, const QModelIndex &source_parent) const override;
QHash<int, QByteArray> roleNames() const override; QHash<int, QByteArray> roleNames() const override;
protected Q_SLOTS: protected Q_SLOTS:
@ -167,8 +166,8 @@ class DataModel : public QAbstractItemModel
Q_PROPERTY(QString keyRoleFilter READ keyRoleFilter WRITE setKeyRoleFilter) Q_PROPERTY(QString keyRoleFilter READ keyRoleFilter WRITE setKeyRoleFilter)
/** /**
* it's a regular expression. If the DataSource is connected to more than one source, only inserts data from sources matching this filter expression in the model. * it's a regular expression. If the DataSource is connected to more than one source, only inserts data from sources matching this filter expression in the
* If we want to have a source watch all sources beginning with say "name:", the required regexp would be sourceFilter: "name:.*" * model. If we want to have a source watch all sources beginning with say "name:", the required regexp would be sourceFilter: "name:.*"
*/ */
Q_PROPERTY(QString sourceFilter READ sourceFilter WRITE setSourceFilter) Q_PROPERTY(QString sourceFilter READ sourceFilter WRITE setSourceFilter)
@ -196,12 +195,10 @@ public:
void setSourceFilter(const QString &key); void setSourceFilter(const QString &key);
QString sourceFilter() const; QString sourceFilter() const;
//Reimplemented // Reimplemented
QVariant data(const QModelIndex &index, int role) const override; QVariant data(const QModelIndex &index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
int role = Qt::DisplayRole) const override; QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
QModelIndex index(int row, int column,
const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &child) const override; QModelIndex parent(const QModelIndex &child) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override; int rowCount(const QModelIndex &parent = QModelIndex()) const override;
int columnCount(const QModelIndex &parent = QModelIndex()) const override; int columnCount(const QModelIndex &parent = QModelIndex()) const override;
@ -239,7 +236,7 @@ private:
QRegExp m_keyRoleFilterRE; QRegExp m_keyRoleFilterRE;
QString m_sourceFilter; QString m_sourceFilter;
QRegExp m_sourceFilterRE; QRegExp m_sourceFilterRE;
QMap<QString, QVector<QVariant> > m_items; QMap<QString, QVector<QVariant>> m_items;
QHash<int, QByteArray> m_roleNames; QHash<int, QByteArray> m_roleNames;
QHash<QString, int> m_roleIds; QHash<QString, int> m_roleIds;
int m_maxRoleId; int m_maxRoleId;

View File

@ -12,10 +12,10 @@
namespace Plasma namespace Plasma
{ {
DataSource::DataSource(QObject *parent) DataSource::DataSource(QObject *parent)
: QObject(parent), : QObject(parent)
m_ready(false), , m_ready(false)
m_interval(0), , m_interval(0)
m_intervalAlignment(Plasma::Types::NoAlignment) , m_intervalAlignment(Plasma::Types::NoAlignment)
{ {
m_models = new QQmlPropertyMap(this); m_models = new QQmlPropertyMap(this);
m_data = new QQmlPropertyMap(this); m_data = new QQmlPropertyMap(this);
@ -24,7 +24,6 @@ DataSource::DataSource(QObject *parent)
void DataSource::classBegin() void DataSource::classBegin()
{ {
} }
void DataSource::componentComplete() void DataSource::componentComplete()
@ -143,8 +142,8 @@ void DataSource::setupData()
return; return;
} }
// qDebug() << " loading engine " << m_engine; // qDebug() << " loading engine " << m_engine;
//FIXME: should all services be deleted just because we're changing the interval, etc? // FIXME: should all services be deleted just because we're changing the interval, etc?
qDeleteAll(m_services); qDeleteAll(m_services);
m_services.clear(); m_services.clear();
@ -156,7 +155,7 @@ void DataSource::setupData()
void DataSource::dataUpdated(const QString &sourceName, const Plasma::DataEngine::Data &data) void DataSource::dataUpdated(const QString &sourceName, const Plasma::DataEngine::Data &data)
{ {
//it can arrive also data we don't explicitly connected a source // it can arrive also data we don't explicitly connected a source
if (m_connectedSources.contains(sourceName)) { if (m_connectedSources.contains(sourceName)) {
m_data->insert(sourceName, data); m_data->insert(sourceName, data);
Q_EMIT dataChanged(); Q_EMIT dataChanged();
@ -174,8 +173,8 @@ void DataSource::modelChanged(const QString &sourceName, QAbstractItemModel *mod
} }
m_models->insert(sourceName, QVariant::fromValue(model)); m_models->insert(sourceName, QVariant::fromValue(model));
//FIXME: this will break in the case a second model is set // FIXME: this will break in the case a second model is set
connect(model, &QObject::destroyed, m_models, [ = ]() { connect(model, &QObject::destroyed, m_models, [=]() {
m_models->clear(sourceName); m_models->clear(sourceName);
}); });
} }
@ -185,7 +184,7 @@ void DataSource::removeSource(const QString &source)
m_data->clear(source); m_data->clear(source);
m_models->clear(source); m_models->clear(source);
//TODO: emit those signals as last thing // TODO: emit those signals as last thing
if (m_connectedSources.contains(source)) { if (m_connectedSources.contains(source)) {
m_connectedSources.removeAll(source); m_connectedSources.removeAll(source);
Q_EMIT sourceDisconnected(source); Q_EMIT sourceDisconnected(source);

View File

@ -11,13 +11,13 @@
#define DATASOURCE_H #define DATASOURCE_H
#include <QObject> #include <QObject>
#include <QQmlParserStatus>
#include <QQmlPropertyMap>
#include <QScopedPointer> #include <QScopedPointer>
#include <QtQml> #include <QtQml>
#include <QQmlPropertyMap>
#include <QQmlParserStatus>
#include <Plasma/DataEngineConsumer>
#include <Plasma/DataEngine> #include <Plasma/DataEngine>
#include <Plasma/DataEngineConsumer>
class QQmlPropertyMap; class QQmlPropertyMap;
@ -124,7 +124,7 @@ public:
* The user has to be connected to its source, so the source name has to be present in the connectedSources property. * The user has to be connected to its source, so the source name has to be present in the connectedSources property.
*/ */
Q_PROPERTY(QQmlPropertyMap *models READ models CONSTANT) Q_PROPERTY(QQmlPropertyMap *models READ models CONSTANT)
QQmlPropertyMap *models() const QQmlPropertyMap *models() const
{ {
return m_models; return m_models;
} }

View File

@ -6,15 +6,14 @@
#include "fadingnode_p.h" #include "fadingnode_p.h"
#include <QSGSimpleMaterialShader>
#include <QOpenGLContext> #include <QOpenGLContext>
#include <QOpenGLFunctions> #include <QOpenGLFunctions>
#include <QSGSimpleMaterialShader>
struct FadingMaterialState struct FadingMaterialState {
{ QSGTexture *source = nullptr;
QSGTexture *source = nullptr; QSGTexture *target = nullptr;
QSGTexture *target = nullptr; qreal progress;
qreal progress;
}; };
class FadingMaterialShader : public QSGSimpleMaterialShader<FadingMaterialState> class FadingMaterialShader : public QSGSimpleMaterialShader<FadingMaterialState>
@ -23,18 +22,18 @@ class FadingMaterialShader : public QSGSimpleMaterialShader<FadingMaterialState>
public: public:
FadingMaterialShader(); FadingMaterialShader();
using QSGSimpleMaterialShader<FadingMaterialState>::updateState; using QSGSimpleMaterialShader<FadingMaterialState>::updateState;
void updateState(const FadingMaterialState* newState, const FadingMaterialState* oldState) override; void updateState(const FadingMaterialState *newState, const FadingMaterialState *oldState) override;
QList<QByteArray> attributes() const override; QList<QByteArray> attributes() const override;
void initialize() override; void initialize() override;
private: private:
QOpenGLFunctions *glFuncs = nullptr; QOpenGLFunctions *glFuncs = nullptr;
int m_progressId = 0; int m_progressId = 0;
int m_sourceRectId = 0; int m_sourceRectId = 0;
int m_targetRectId = 0; int m_targetRectId = 0;
}; };
FadingMaterialShader::FadingMaterialShader() FadingMaterialShader::FadingMaterialShader()
{ {
setShaderSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/plasma-framework/shaders/fadingmaterial.frag")); setShaderSourceFile(QOpenGLShader::Fragment, QStringLiteral(":/plasma-framework/shaders/fadingmaterial.frag"));
@ -46,7 +45,7 @@ QList<QByteArray> FadingMaterialShader::attributes() const
return {QByteArrayLiteral("qt_Vertex"), QByteArrayLiteral("qt_MultiTexCoord0")}; return {QByteArrayLiteral("qt_Vertex"), QByteArrayLiteral("qt_MultiTexCoord0")};
} }
void FadingMaterialShader::updateState(const FadingMaterialState* newState, const FadingMaterialState* oldState) void FadingMaterialShader::updateState(const FadingMaterialState *newState, const FadingMaterialState *oldState)
{ {
if (!oldState || oldState->source != newState->source) { if (!oldState || oldState->source != newState->source) {
glFuncs->glActiveTexture(GL_TEXTURE0); glFuncs->glActiveTexture(GL_TEXTURE0);
@ -65,7 +64,7 @@ void FadingMaterialShader::updateState(const FadingMaterialState* newState, cons
} }
if (!oldState || oldState->progress != newState->progress) { if (!oldState || oldState->progress != newState->progress) {
program()->setUniformValue(m_progressId, (GLfloat) newState->progress); program()->setUniformValue(m_progressId, (GLfloat)newState->progress);
} }
} }
@ -75,7 +74,7 @@ void FadingMaterialShader::initialize()
// shader not linked, exit otherwise we crash, BUG: 336272 // shader not linked, exit otherwise we crash, BUG: 336272
return; return;
} }
QSGSimpleMaterialShader< FadingMaterialState >::initialize(); QSGSimpleMaterialShader<FadingMaterialState>::initialize();
glFuncs = QOpenGLContext::currentContext()->functions(); glFuncs = QOpenGLContext::currentContext()->functions();
program()->bind(); program()->bind();
program()->setUniformValue("u_src", 0); program()->setUniformValue("u_src", 0);
@ -86,10 +85,9 @@ void FadingMaterialShader::initialize()
m_targetRectId = program()->uniformLocation("u_target_rect"); m_targetRectId = program()->uniformLocation("u_target_rect");
} }
FadingNode::FadingNode(QSGTexture *source, QSGTexture *target)
FadingNode::FadingNode(QSGTexture *source, QSGTexture *target): : m_source(source)
m_source(source), , m_target(target)
m_target(target)
{ {
QSGSimpleMaterial<FadingMaterialState> *m = FadingMaterialShader::createMaterial(); QSGSimpleMaterial<FadingMaterialState> *m = FadingMaterialShader::createMaterial();
m->setFlag(QSGMaterial::Blending); m->setFlag(QSGMaterial::Blending);
@ -115,7 +113,7 @@ void FadingNode::setRect(const QRectF &bounds)
void FadingNode::setProgress(qreal progress) void FadingNode::setProgress(qreal progress)
{ {
QSGSimpleMaterial<FadingMaterialState> *m = static_cast<QSGSimpleMaterial<FadingMaterialState>*>(material()); QSGSimpleMaterial<FadingMaterialState> *m = static_cast<QSGSimpleMaterial<FadingMaterialState> *>(material());
m->state()->source = m_source.data(); m->state()->source = m_source.data();
m->state()->target = m_target.data(); m->state()->target = m_target.data();
m->state()->progress = progress; m->state()->progress = progress;

View File

@ -7,9 +7,9 @@
#ifndef FADINGNODE_H #ifndef FADINGNODE_H
#define FADINGNODE_H #define FADINGNODE_H
#include <QRectF>
#include <QSGGeometryNode> #include <QSGGeometryNode>
#include <QSGTexture> #include <QSGTexture>
#include <QRectF>
/** /**
* This node fades between two textures using a shader * This node fades between two textures using a shader
@ -29,6 +29,7 @@ public:
*/ */
void setProgress(qreal progress); void setProgress(qreal progress);
void setRect(const QRectF &bounds); void setRect(const QRectF &bounds);
private: private:
QScopedPointer<QSGTexture> m_source; QScopedPointer<QSGTexture> m_source;
QScopedPointer<QSGTexture> m_target; QScopedPointer<QSGTexture> m_target;

View File

@ -8,29 +8,28 @@
#include "framesvgitem.h" #include "framesvgitem.h"
#include <QQuickWindow> #include <QQuickWindow>
#include <QSGTexture>
#include <QSGGeometry> #include <QSGGeometry>
#include <QSGTexture>
#include <QDebug> #include <QDebug>
#include <QPainter> #include <QPainter>
#include <plasma/private/framesvg_p.h>
#include <plasma/private/framesvg_helpers.h> #include <plasma/private/framesvg_helpers.h>
#include <plasma/private/framesvg_p.h>
#include <QuickAddons/ManagedTextureNode>
#include <QuickAddons/ImageTexturesCache> #include <QuickAddons/ImageTexturesCache>
#include <QuickAddons/ManagedTextureNode>
#include <cmath> //floor() #include <cmath> //floor()
namespace Plasma namespace Plasma
{ {
Q_GLOBAL_STATIC(ImageTexturesCache, s_cache) Q_GLOBAL_STATIC(ImageTexturesCache, s_cache)
class FrameNode : public QSGNode class FrameNode : public QSGNode
{ {
public: public:
FrameNode(const QString& prefix, FrameSvg* svg) FrameNode(const QString &prefix, FrameSvg *svg)
: QSGNode() : QSGNode()
, leftWidth(0) , leftWidth(0)
, rightWidth(0) , rightWidth(0)
@ -47,9 +46,9 @@ public:
bottomHeight = svg->elementSize(prefix % QLatin1String("bottom")).height(); bottomHeight = svg->elementSize(prefix % QLatin1String("bottom")).height();
} }
QRect contentsRect(const QSize& size) const QRect contentsRect(const QSize &size) const
{ {
const QSize contentSize(size.width() - leftWidth - rightWidth, size.height() - topHeight - bottomHeight); const QSize contentSize(size.width() - leftWidth - rightWidth, size.height() - topHeight - bottomHeight);
return QRect(QPoint(leftWidth, topHeight), contentSize); return QRect(QPoint(leftWidth, topHeight), contentSize);
} }
@ -65,14 +64,14 @@ class FrameItemNode : public ManagedTextureNode
{ {
public: public:
enum FitMode { enum FitMode {
//render SVG at native resolution then stretch it in openGL // render SVG at native resolution then stretch it in openGL
FastStretch, FastStretch,
//on resize re-render the part of the frame from the SVG // on resize re-render the part of the frame from the SVG
Stretch, Stretch,
Tile, Tile,
}; };
FrameItemNode(FrameSvgItem* frameSvg, FrameSvg::EnabledBorders borders, FitMode fitMode, QSGNode* parent) FrameItemNode(FrameSvgItem *frameSvg, FrameSvg::EnabledBorders borders, FitMode fitMode, QSGNode *parent)
: ManagedTextureNode() : ManagedTextureNode()
, m_frameSvg(frameSvg) , m_frameSvg(frameSvg)
, m_border(borders) , m_border(borders)
@ -83,12 +82,12 @@ public:
if (m_fitMode == Tile) { if (m_fitMode == Tile) {
if (m_border == FrameSvg::TopBorder || m_border == FrameSvg::BottomBorder || m_border == FrameSvg::NoBorder) { if (m_border == FrameSvg::TopBorder || m_border == FrameSvg::BottomBorder || m_border == FrameSvg::NoBorder) {
static_cast<QSGTextureMaterial*>(material())->setHorizontalWrapMode(QSGTexture::Repeat); static_cast<QSGTextureMaterial *>(material())->setHorizontalWrapMode(QSGTexture::Repeat);
static_cast<QSGOpaqueTextureMaterial*>(opaqueMaterial())->setHorizontalWrapMode(QSGTexture::Repeat); static_cast<QSGOpaqueTextureMaterial *>(opaqueMaterial())->setHorizontalWrapMode(QSGTexture::Repeat);
} }
if (m_border == FrameSvg::LeftBorder || m_border == FrameSvg::RightBorder || m_border == FrameSvg::NoBorder) { if (m_border == FrameSvg::LeftBorder || m_border == FrameSvg::RightBorder || m_border == FrameSvg::NoBorder) {
static_cast<QSGTextureMaterial*>(material())->setVerticalWrapMode(QSGTexture::Repeat); static_cast<QSGTextureMaterial *>(material())->setVerticalWrapMode(QSGTexture::Repeat);
static_cast<QSGOpaqueTextureMaterial*>(opaqueMaterial())->setVerticalWrapMode(QSGTexture::Repeat); static_cast<QSGOpaqueTextureMaterial *>(opaqueMaterial())->setVerticalWrapMode(QSGTexture::Repeat);
} }
} }
@ -97,8 +96,8 @@ public:
m_elementNativeSize = m_frameSvg->frameSvg()->elementSize(elementId); m_elementNativeSize = m_frameSvg->frameSvg()->elementSize(elementId);
if (m_elementNativeSize.isEmpty()) { if (m_elementNativeSize.isEmpty()) {
//if the default element is empty, we can avoid the slower tiling path // if the default element is empty, we can avoid the slower tiling path
//this also avoids a divide by 0 error // this also avoids a divide by 0 error
m_fitMode = FastStretch; m_fitMode = FastStretch;
} }
@ -115,37 +114,37 @@ public:
setTexture(s_cache->loadTexture(m_frameSvg->window(), m_frameSvg->frameSvg()->image(size, elementId), options)); setTexture(s_cache->loadTexture(m_frameSvg->window(), m_frameSvg->frameSvg()->image(size, elementId), options));
} }
void reposition(const QRect& frameGeometry, QSize& fullSize) void reposition(const QRect &frameGeometry, QSize &fullSize)
{ {
QRect nodeRect = FrameSvgHelpers::sectionRect(m_border, frameGeometry, fullSize); QRect nodeRect = FrameSvgHelpers::sectionRect(m_border, frameGeometry, fullSize);
//ensure we're not passing a weird rectangle to updateTexturedRectGeometry // ensure we're not passing a weird rectangle to updateTexturedRectGeometry
if(!nodeRect.isValid() || nodeRect.isEmpty()) if (!nodeRect.isValid() || nodeRect.isEmpty())
nodeRect = QRect(); nodeRect = QRect();
//the position of the relevant texture within this texture ID. // the position of the relevant texture within this texture ID.
//for atlas' this will only be a small part of the texture // for atlas' this will only be a small part of the texture
QRectF textureRect; QRectF textureRect;
if (m_fitMode == Tile) { if (m_fitMode == Tile) {
textureRect = QRectF(0,0,1,1); //we can never be in an atlas for tiled images. textureRect = QRectF(0, 0, 1, 1); // we can never be in an atlas for tiled images.
//if tiling horizontally // if tiling horizontally
if (m_border == FrameSvg::TopBorder || m_border == FrameSvg::BottomBorder || m_border == FrameSvg::NoBorder) { if (m_border == FrameSvg::TopBorder || m_border == FrameSvg::BottomBorder || m_border == FrameSvg::NoBorder) {
// cmp. CSS3's border-image-repeat: "repeat", though with first tile not centered, but aligned to left // cmp. CSS3's border-image-repeat: "repeat", though with first tile not centered, but aligned to left
textureRect.setWidth((qreal) nodeRect.width() / m_elementNativeSize.width()); textureRect.setWidth((qreal)nodeRect.width() / m_elementNativeSize.width());
} }
//if tiling vertically // if tiling vertically
if (m_border == FrameSvg::LeftBorder || m_border == FrameSvg::RightBorder || m_border == FrameSvg::NoBorder) { if (m_border == FrameSvg::LeftBorder || m_border == FrameSvg::RightBorder || m_border == FrameSvg::NoBorder) {
// cmp. CSS3's border-image-repeat: "repeat", though with first tile not centered, but aligned to top // cmp. CSS3's border-image-repeat: "repeat", though with first tile not centered, but aligned to top
textureRect.setHeight((qreal) nodeRect.height() / m_elementNativeSize.height()); textureRect.setHeight((qreal)nodeRect.height() / m_elementNativeSize.height());
} }
} else if (m_fitMode == Stretch) { } else if (m_fitMode == Stretch) {
QString prefix = m_frameSvg->frameSvg()->actualPrefix(); QString prefix = m_frameSvg->frameSvg()->actualPrefix();
QString elementId = prefix + FrameSvgHelpers::borderToElementId(m_border); QString elementId = prefix + FrameSvgHelpers::borderToElementId(m_border);
//re-render the SVG at new size // re-render the SVG at new size
updateTexture(nodeRect.size(), elementId); updateTexture(nodeRect.size(), elementId);
textureRect = texture()->normalizedTextureSubRect(); textureRect = texture()->normalizedTextureSubRect();
} else if (texture()) { // for fast stretch. } else if (texture()) { // for fast stretch.
@ -157,7 +156,7 @@ public:
} }
private: private:
FrameSvgItem* m_frameSvg; FrameSvgItem *m_frameSvg;
FrameSvg::EnabledBorders m_border; FrameSvg::EnabledBorders m_border;
QSGNode *m_lastParent; QSGNode *m_lastParent;
QSize m_elementNativeSize; QSize m_elementNativeSize;
@ -165,19 +164,19 @@ private:
}; };
FrameSvgItemMargins::FrameSvgItemMargins(Plasma::FrameSvg *frameSvg, QObject *parent) FrameSvgItemMargins::FrameSvgItemMargins(Plasma::FrameSvg *frameSvg, QObject *parent)
: QObject(parent), : QObject(parent)
m_frameSvg(frameSvg), , m_frameSvg(frameSvg)
m_fixed(false), , m_fixed(false)
m_inset(false) , m_inset(false)
{ {
//qDebug() << "margins at: " << left() << top() << right() << bottom(); // qDebug() << "margins at: " << left() << top() << right() << bottom();
} }
qreal FrameSvgItemMargins::left() const qreal FrameSvgItemMargins::left() const
{ {
if (m_fixed) { if (m_fixed) {
return m_frameSvg->fixedMarginSize(Types::LeftMargin); return m_frameSvg->fixedMarginSize(Types::LeftMargin);
} else if(m_inset){ } else if (m_inset) {
return m_frameSvg->insetSize(Types::LeftMargin); return m_frameSvg->insetSize(Types::LeftMargin);
} else { } else {
return m_frameSvg->marginSize(Types::LeftMargin); return m_frameSvg->marginSize(Types::LeftMargin);
@ -188,7 +187,7 @@ qreal FrameSvgItemMargins::top() const
{ {
if (m_fixed) { if (m_fixed) {
return m_frameSvg->fixedMarginSize(Types::TopMargin); return m_frameSvg->fixedMarginSize(Types::TopMargin);
} else if(m_inset){ } else if (m_inset) {
return m_frameSvg->insetSize(Types::TopMargin); return m_frameSvg->insetSize(Types::TopMargin);
} else { } else {
return m_frameSvg->marginSize(Types::TopMargin); return m_frameSvg->marginSize(Types::TopMargin);
@ -199,7 +198,7 @@ qreal FrameSvgItemMargins::right() const
{ {
if (m_fixed) { if (m_fixed) {
return m_frameSvg->fixedMarginSize(Types::RightMargin); return m_frameSvg->fixedMarginSize(Types::RightMargin);
} else if(m_inset){ } else if (m_inset) {
return m_frameSvg->insetSize(Types::RightMargin); return m_frameSvg->insetSize(Types::RightMargin);
} else { } else {
return m_frameSvg->marginSize(Types::RightMargin); return m_frameSvg->marginSize(Types::RightMargin);
@ -210,7 +209,7 @@ qreal FrameSvgItemMargins::bottom() const
{ {
if (m_fixed) { if (m_fixed) {
return m_frameSvg->fixedMarginSize(Types::BottomMargin); return m_frameSvg->fixedMarginSize(Types::BottomMargin);
} else if(m_inset){ } else if (m_inset) {
return m_frameSvg->insetSize(Types::BottomMargin); return m_frameSvg->insetSize(Types::BottomMargin);
} else { } else {
return m_frameSvg->marginSize(Types::BottomMargin); return m_frameSvg->marginSize(Types::BottomMargin);
@ -270,13 +269,13 @@ bool FrameSvgItemMargins::isInset() const
} }
FrameSvgItem::FrameSvgItem(QQuickItem *parent) FrameSvgItem::FrameSvgItem(QQuickItem *parent)
: QQuickItem(parent), : QQuickItem(parent)
m_margins(nullptr), , m_margins(nullptr)
m_fixedMargins(nullptr), , m_fixedMargins(nullptr)
m_insetMargins(nullptr), , m_insetMargins(nullptr)
m_textureChanged(false), , m_textureChanged(false)
m_sizeChanged(false), , m_sizeChanged(false)
m_fastPath(true) , m_fastPath(true)
{ {
m_frameSvg = new Plasma::FrameSvg(this); m_frameSvg = new Plasma::FrameSvg(this);
setFlag(ItemHasContents, true); setFlag(ItemHasContents, true);
@ -293,9 +292,11 @@ FrameSvgItem::~FrameSvgItem()
class CheckMarginsChange class CheckMarginsChange
{ {
public: public:
CheckMarginsChange(QVector<qreal>& oldMargins, FrameSvgItemMargins *marginsObject) CheckMarginsChange(QVector<qreal> &oldMargins, FrameSvgItemMargins *marginsObject)
: m_oldMargins(oldMargins), m_marginsObject(marginsObject) : m_oldMargins(oldMargins)
{} , m_marginsObject(marginsObject)
{
}
~CheckMarginsChange() ~CheckMarginsChange()
{ {
@ -308,7 +309,7 @@ public:
} }
private: private:
QVector<qreal>& m_oldMargins; QVector<qreal> &m_oldMargins;
FrameSvgItemMargins *const m_marginsObject; FrameSvgItemMargins *const m_marginsObject;
}; };
@ -352,7 +353,7 @@ QString FrameSvgItem::imagePath() const
void FrameSvgItem::setPrefix(const QVariant &prefixes) void FrameSvgItem::setPrefix(const QVariant &prefixes)
{ {
QStringList prefixList; QStringList prefixList;
//is this a simple string? // is this a simple string?
if (prefixes.canConvert<QString>()) { if (prefixes.canConvert<QString>()) {
prefixList << prefixes.toString(); prefixList << prefixes.toString();
} else if (prefixes.canConvert<QStringList>()) { } else if (prefixes.canConvert<QStringList>()) {
@ -478,14 +479,12 @@ bool FrameSvgItem::hasElementPrefix(const QString &prefix) const
return m_frameSvg->hasElementPrefix(prefix); return m_frameSvg->hasElementPrefix(prefix);
} }
QRegion FrameSvgItem::mask() const QRegion FrameSvgItem::mask() const
{ {
return m_frameSvg->mask(); return m_frameSvg->mask();
} }
void FrameSvgItem::geometryChanged(const QRectF &newGeometry, void FrameSvgItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
const QRectF &oldGeometry)
{ {
const bool isComponentComplete = this->isComponentComplete(); const bool isComponentComplete = this->isComponentComplete();
if (isComponentComplete) { if (isComponentComplete) {
@ -512,7 +511,7 @@ void FrameSvgItem::doUpdate()
CheckMarginsChange checkFixedMargins(m_oldFixedMargins, m_fixedMargins); CheckMarginsChange checkFixedMargins(m_oldFixedMargins, m_fixedMargins);
CheckMarginsChange checkInsetMargins(m_oldInsetMargins, m_insetMargins); CheckMarginsChange checkInsetMargins(m_oldInsetMargins, m_insetMargins);
//if the theme changed, the available prefix may have changed as well // if the theme changed, the available prefix may have changed as well
applyPrefixes(); applyPrefixes();
if (implicitWidth() <= 0) { if (implicitWidth() <= 0) {
@ -525,12 +524,12 @@ void FrameSvgItem::doUpdate()
QString prefix = m_frameSvg->actualPrefix(); QString prefix = m_frameSvg->actualPrefix();
bool hasOverlay = !prefix.startsWith(QLatin1String("mask-")) && m_frameSvg->hasElement(prefix % QLatin1String("overlay")); bool hasOverlay = !prefix.startsWith(QLatin1String("mask-")) && m_frameSvg->hasElement(prefix % QLatin1String("overlay"));
bool hasComposeOverBorder = m_frameSvg->hasElement(prefix % QLatin1String("hint-compose-over-border")) && bool hasComposeOverBorder = m_frameSvg->hasElement(prefix % QLatin1String("hint-compose-over-border"))
m_frameSvg->hasElement(QLatin1String("mask-") % prefix % QLatin1String("center")); && m_frameSvg->hasElement(QLatin1String("mask-") % prefix % QLatin1String("center"));
m_fastPath = !hasOverlay && !hasComposeOverBorder; m_fastPath = !hasOverlay && !hasComposeOverBorder;
//software rendering (at time of writing Qt5.10) doesn't seem to like our tiling/stretching in the 9-tiles. // software rendering (at time of writing Qt5.10) doesn't seem to like our tiling/stretching in the 9-tiles.
//also when using QPainter it's arguably faster to create and cache pixmaps of the whole frame, which is what the slow path does // also when using QPainter it's arguably faster to create and cache pixmaps of the whole frame, which is what the slow path does
if (QQuickWindow::sceneGraphBackend() == QLatin1String("software")) { if (QQuickWindow::sceneGraphBackend() == QLatin1String("software")) {
m_fastPath = false; m_fastPath = false;
} }
@ -549,8 +548,7 @@ Plasma::FrameSvg *FrameSvgItem::frameSvg() const
QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *) QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaintNodeData *)
{ {
if (!window() || !m_frameSvg || if (!window() || !m_frameSvg || (!m_frameSvg->hasElementPrefix(m_frameSvg->actualPrefix()) && !m_frameSvg->hasElementPrefix(m_frameSvg->prefix()))) {
(!m_frameSvg->hasElementPrefix(m_frameSvg->actualPrefix()) && !m_frameSvg->hasElementPrefix(m_frameSvg->prefix()))) {
delete oldNode; delete oldNode;
return nullptr; return nullptr;
} }
@ -567,12 +565,12 @@ QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaint
QString prefix = m_frameSvg->actualPrefix(); QString prefix = m_frameSvg->actualPrefix();
oldNode = new FrameNode(prefix, m_frameSvg); oldNode = new FrameNode(prefix, m_frameSvg);
bool tileCenter = (m_frameSvg->hasElement(QStringLiteral("hint-tile-center")) bool tileCenter =
|| m_frameSvg->hasElement(prefix % QLatin1String("hint-tile-center"))); (m_frameSvg->hasElement(QStringLiteral("hint-tile-center")) || m_frameSvg->hasElement(prefix % QLatin1String("hint-tile-center")));
bool stretchBorders = (m_frameSvg->hasElement(QStringLiteral("hint-stretch-borders")) bool stretchBorders =
|| m_frameSvg->hasElement(prefix % QLatin1String("hint-stretch-borders"))); (m_frameSvg->hasElement(QStringLiteral("hint-stretch-borders")) || m_frameSvg->hasElement(prefix % QLatin1String("hint-stretch-borders")));
FrameItemNode::FitMode borderFitMode = stretchBorders ? FrameItemNode::Stretch : FrameItemNode::Tile; FrameItemNode::FitMode borderFitMode = stretchBorders ? FrameItemNode::Stretch : FrameItemNode::Tile;
FrameItemNode::FitMode centerFitMode = tileCenter ? FrameItemNode::Tile: FrameItemNode::Stretch; FrameItemNode::FitMode centerFitMode = tileCenter ? FrameItemNode::Tile : FrameItemNode::Stretch;
new FrameItemNode(this, FrameSvg::NoBorder, centerFitMode, oldNode); new FrameItemNode(this, FrameSvg::NoBorder, centerFitMode, oldNode);
if (enabledBorders() & (FrameSvg::TopBorder | FrameSvg::LeftBorder)) { if (enabledBorders() & (FrameSvg::TopBorder | FrameSvg::LeftBorder)) {
@ -594,7 +592,7 @@ QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaint
new FrameItemNode(this, FrameSvg::BottomBorder | FrameSvg::RightBorder, FrameItemNode::FastStretch, oldNode); new FrameItemNode(this, FrameSvg::BottomBorder | FrameSvg::RightBorder, FrameItemNode::FastStretch, oldNode);
} }
if (enabledBorders() & FrameSvg::LeftBorder) { if (enabledBorders() & FrameSvg::LeftBorder) {
new FrameItemNode(this, FrameSvg::LeftBorder, borderFitMode, oldNode); new FrameItemNode(this, FrameSvg::LeftBorder, borderFitMode, oldNode);
} }
if (enabledBorders() & FrameSvg::RightBorder) { if (enabledBorders() & FrameSvg::RightBorder) {
new FrameItemNode(this, FrameSvg::RightBorder, borderFitMode, oldNode); new FrameItemNode(this, FrameSvg::RightBorder, borderFitMode, oldNode);
@ -611,7 +609,7 @@ QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaint
} }
if (m_sizeChanged) { if (m_sizeChanged) {
FrameNode* frameNode = static_cast<FrameNode*>(oldNode); FrameNode *frameNode = static_cast<FrameNode *>(oldNode);
QSize frameSize(width(), height()); QSize frameSize(width(), height());
QRect geometry = frameNode->contentsRect(frameSize); QRect geometry = frameNode->contentsRect(frameSize);
QSGNode *node = oldNode->firstChild(); QSGNode *node = oldNode->firstChild();
@ -627,7 +625,7 @@ QSGNode *FrameSvgItem::updatePaintNode(QSGNode *oldNode, QQuickItem::UpdatePaint
if (!textureNode) { if (!textureNode) {
delete oldNode; delete oldNode;
textureNode = new ManagedTextureNode; textureNode = new ManagedTextureNode;
m_textureChanged = true; //force updating the texture on our newly created node m_textureChanged = true; // force updating the texture on our newly created node
oldNode = textureNode; oldNode = textureNode;
} }
textureNode->setFiltering(filtering); textureNode->setFiltering(filtering);
@ -667,7 +665,7 @@ void FrameSvgItem::updateDevicePixelRatio()
{ {
m_frameSvg->setScaleFactor(qMax<qreal>(1.0, floor(Units::instance().devicePixelRatio()))); m_frameSvg->setScaleFactor(qMax<qreal>(1.0, floor(Units::instance().devicePixelRatio())));
//devicepixelratio is always set integer in the svg, so needs at least 192dpi to double up. // devicepixelratio is always set integer in the svg, so needs at least 192dpi to double up.
//(it needs to be integer to have lines contained inside a svg piece to keep being pixel aligned) //(it needs to be integer to have lines contained inside a svg piece to keep being pixel aligned)
const auto newDevicePixelRation = qMax<qreal>(1.0, floor(window() ? window()->devicePixelRatio() : qApp->devicePixelRatio())); const auto newDevicePixelRation = qMax<qreal>(1.0, floor(window() ? window()->devicePixelRatio() : qApp->devicePixelRatio()));
@ -679,7 +677,6 @@ void FrameSvgItem::updateDevicePixelRatio()
void FrameSvgItem::applyPrefixes() void FrameSvgItem::applyPrefixes()
{ {
if (m_frameSvg->imagePath().isEmpty()) { if (m_frameSvg->imagePath().isEmpty()) {
return; return;
} }
@ -703,7 +700,7 @@ void FrameSvgItem::applyPrefixes()
} }
} }
if (!found) { if (!found) {
//this setElementPrefix is done to keep the same behavior as before, when it was a simple string // this setElementPrefix is done to keep the same behavior as before, when it was a simple string
m_frameSvg->setElementPrefix(m_prefixes.constLast()); m_frameSvg->setElementPrefix(m_prefixes.constLast());
} }
if (oldPrefix != m_frameSvg->prefix()) { if (oldPrefix != m_frameSvg->prefix()) {
@ -711,7 +708,7 @@ void FrameSvgItem::applyPrefixes()
} }
} }
void FrameSvgItem::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData & value) void FrameSvgItem::itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &value)
{ {
if (change == ItemSceneChange && value.window) { if (change == ItemSceneChange && value.window) {
updateDevicePixelRatio(); updateDevicePixelRatio();
@ -721,4 +718,3 @@ void FrameSvgItem::itemChange(QQuickItem::ItemChange change, const QQuickItem::I
} }
} // Plasma namespace } // Plasma namespace

View File

@ -7,8 +7,8 @@
#ifndef FRAMESVGITEM_P #ifndef FRAMESVGITEM_P
#define FRAMESVGITEM_P #define FRAMESVGITEM_P
#include <QQuickItem>
#include <QQmlParserStatus> #include <QQmlParserStatus>
#include <QQuickItem>
#include <Plasma/FrameSvg> #include <Plasma/FrameSvg>
@ -16,7 +16,6 @@
namespace Plasma namespace Plasma
{ {
class FrameSvg; class FrameSvg;
/** /**
@ -58,7 +57,6 @@ class FrameSvgItemMargins : public QObject
*/ */
Q_PROPERTY(qreal vertical READ vertical NOTIFY marginsChanged) Q_PROPERTY(qreal vertical READ vertical NOTIFY marginsChanged)
public: public:
FrameSvgItemMargins(Plasma::FrameSvg *frameSvg, QObject *parent = nullptr); FrameSvgItemMargins(Plasma::FrameSvg *frameSvg, QObject *parent = nullptr);
@ -90,7 +88,6 @@ private:
bool m_inset; bool m_inset;
}; };
/** /**
* @class FrameSvgItem * @class FrameSvgItem
* *
@ -222,8 +219,7 @@ public:
void setStatus(Plasma::Svg::Status status); void setStatus(Plasma::Svg::Status status);
Plasma::Svg::Status status() const; Plasma::Svg::Status status() const;
void geometryChanged(const QRectF &newGeometry, void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) override;
const QRectF &oldGeometry) override;
QRegion mask() const; QRegion mask() const;
@ -234,13 +230,13 @@ public:
QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *) override; QSGNode *updatePaintNode(QSGNode *, UpdatePaintNodeData *) override;
void itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData & data) override; void itemChange(QQuickItem::ItemChange change, const QQuickItem::ItemChangeData &data) override;
protected: protected:
void classBegin() override; void classBegin() override;
void componentComplete() override; void componentComplete() override;
/// @endcond /// @endcond
Q_SIGNALS: Q_SIGNALS:
void imagePathChanged(); void imagePathChanged();

View File

@ -11,23 +11,28 @@
#include <QPainter> #include <QPainter>
#include <QPalette> #include <QPalette>
#include <QPropertyAnimation> #include <QPropertyAnimation>
#include <QSGSimpleTextureNode>
#include <QQuickWindow> #include <QQuickWindow>
#include <QSGSimpleTextureNode>
#include <KIconLoader>
#include <KIconEffect> #include <KIconEffect>
#include <KIconLoader>
#include <KIconTheme> #include <KIconTheme>
#include "fadingnode_p.h" #include "fadingnode_p.h"
#include <QuickAddons/ManagedTextureNode>
#include "theme.h" #include "theme.h"
#include "units.h" #include "units.h"
#include <QuickAddons/ManagedTextureNode>
class IconItemSource class IconItemSource
{ {
public: public:
explicit IconItemSource(IconItem *iconItem) : m_iconItem(iconItem) {} explicit IconItemSource(IconItem *iconItem)
virtual ~IconItemSource() {} : m_iconItem(iconItem)
{
}
virtual ~IconItemSource()
{
}
virtual bool isValid() const = 0; virtual bool isValid() const = 0;
virtual const QSize size() const = 0; virtual const QSize size() const = 0;
@ -45,7 +50,10 @@ protected:
class NullSource : public IconItemSource class NullSource : public IconItemSource
{ {
public: public:
explicit NullSource(IconItem *iconItem) : IconItemSource(iconItem) {} explicit NullSource(IconItem *iconItem)
: IconItemSource(iconItem)
{
}
bool isValid() const override bool isValid() const override
{ {
@ -67,7 +75,8 @@ public:
class QIconSource : public IconItemSource class QIconSource : public IconItemSource
{ {
public: public:
explicit QIconSource(const QIcon &icon, IconItem *iconItem) : IconItemSource(iconItem) explicit QIconSource(const QIcon &icon, IconItem *iconItem)
: IconItemSource(iconItem)
{ {
m_icon = icon; m_icon = icon;
} }
@ -97,7 +106,8 @@ private:
class QImageSource : public IconItemSource class QImageSource : public IconItemSource
{ {
public: public:
explicit QImageSource(const QImage &imageIcon, IconItem *iconItem) : IconItemSource(iconItem) explicit QImageSource(const QImage &imageIcon, IconItem *iconItem)
: IconItemSource(iconItem)
{ {
m_imageIcon = imageIcon; m_imageIcon = imageIcon;
} }
@ -130,7 +140,8 @@ private:
class SvgSource : public IconItemSource class SvgSource : public IconItemSource
{ {
public: public:
explicit SvgSource(const QString &sourceString, IconItem* iconItem) : IconItemSource(iconItem) explicit SvgSource(const QString &sourceString, IconItem *iconItem)
: IconItemSource(iconItem)
{ {
m_svgIcon = new Plasma::Svg(iconItem); m_svgIcon = new Plasma::Svg(iconItem);
m_svgIcon->setColorGroup(iconItem->colorGroup()); m_svgIcon->setColorGroup(iconItem->colorGroup());
@ -149,17 +160,17 @@ public:
}); });
if (iconItem->usesPlasmaTheme()) { if (iconItem->usesPlasmaTheme()) {
//try as a svg icon from plasma theme // try as a svg icon from plasma theme
m_svgIcon->setImagePath(QLatin1String("icons/") + sourceString.section(QLatin1Char('-'), 0, 0)); m_svgIcon->setImagePath(QLatin1String("icons/") + sourceString.section(QLatin1Char('-'), 0, 0));
m_svgIcon->setContainsMultipleImages(true); m_svgIcon->setContainsMultipleImages(true);
} }
//success? // success?
if (iconItem->usesPlasmaTheme() && m_svgIcon->isValid() && m_svgIcon->hasElement(sourceString)) { if (iconItem->usesPlasmaTheme() && m_svgIcon->isValid() && m_svgIcon->hasElement(sourceString)) {
m_svgIconName = sourceString; m_svgIconName = sourceString;
//ok, svg not available from the plasma theme // ok, svg not available from the plasma theme
} else { } else {
//try to load from iconloader an svg with Plasma::Svg // try to load from iconloader an svg with Plasma::Svg
const auto *iconTheme = KIconLoader::global()->theme(); const auto *iconTheme = KIconLoader::global()->theme();
QString iconPath; QString iconPath;
if (iconTheme) { if (iconTheme) {
@ -175,13 +186,14 @@ public:
m_svgIcon->setImagePath(iconPath); m_svgIcon->setImagePath(iconPath);
m_svgIconName = sourceString; m_svgIconName = sourceString;
} else { } else {
//fail, cleanup // fail, cleanup
delete m_svgIcon; delete m_svgIcon;
} }
} }
} }
~SvgSource() { ~SvgSource()
{
if (m_svgIcon) { if (m_svgIcon) {
QObject::disconnect(m_iconItem, nullptr, m_svgIcon, nullptr); QObject::disconnect(m_iconItem, nullptr, m_svgIcon, nullptr);
} }
@ -196,13 +208,13 @@ public:
{ {
QSize s; QSize s;
if (m_svgIcon) { // FIXME: Check Svg::isValid()? Considered expensive by apidox. if (m_svgIcon) { // FIXME: Check Svg::isValid()? Considered expensive by apidox.
//resize() resets the icon to its implicit size, specified // resize() resets the icon to its implicit size, specified
m_svgIcon->resize(); m_svgIcon->resize();
//plasma theme icon, where one file contains multiple images // plasma theme icon, where one file contains multiple images
if (m_svgIcon->hasElement(m_svgIconName)) { if (m_svgIcon->hasElement(m_svgIconName)) {
s = m_svgIcon->elementSize(m_svgIconName); s = m_svgIcon->elementSize(m_svgIconName);
//normal icon: one image per file, page size is icon size // normal icon: one image per file, page size is icon size
} else { } else {
s = m_svgIcon->size(); s = m_svgIcon->size();
} }
@ -248,35 +260,32 @@ private:
}; };
IconItem::IconItem(QQuickItem *parent) IconItem::IconItem(QQuickItem *parent)
: QQuickItem(parent), : QQuickItem(parent)
m_iconItemSource(new NullSource(this)), , m_iconItemSource(new NullSource(this))
m_status(Plasma::Svg::Normal), , m_status(Plasma::Svg::Normal)
m_active(false), , m_active(false)
m_animated(true), , m_animated(true)
m_usesPlasmaTheme(true), , m_usesPlasmaTheme(true)
m_roundToIconSize(true), , m_roundToIconSize(true)
m_textureChanged(false), , m_textureChanged(false)
m_sizeChanged(false), , m_sizeChanged(false)
m_allowNextAnimation(false), , m_allowNextAnimation(false)
m_blockNextAnimation(false), , m_blockNextAnimation(false)
m_implicitHeightSetByUser(false), , m_implicitHeightSetByUser(false)
m_implicitWidthSetByUser(false), , m_implicitWidthSetByUser(false)
m_colorGroup(Plasma::Theme::NormalColorGroup), , m_colorGroup(Plasma::Theme::NormalColorGroup)
m_animValue(0) , m_animValue(0)
{ {
m_animation = new QPropertyAnimation(this); m_animation = new QPropertyAnimation(this);
connect(m_animation, &QPropertyAnimation::valueChanged, connect(m_animation, &QPropertyAnimation::valueChanged, this, &IconItem::valueChanged);
this, &IconItem::valueChanged); connect(m_animation, &QPropertyAnimation::finished, this, &IconItem::animationFinished);
connect(m_animation, &QPropertyAnimation::finished,
this, &IconItem::animationFinished);
m_animation->setTargetObject(this); m_animation->setTargetObject(this);
m_animation->setEasingCurve(QEasingCurve::InOutQuad); m_animation->setEasingCurve(QEasingCurve::InOutQuad);
m_animation->setDuration(250); //FIXME from theme m_animation->setDuration(250); // FIXME from theme
setFlag(ItemHasContents, true); setFlag(ItemHasContents, true);
connect(KIconLoader::global(), &KIconLoader::iconLoaderSettingsChanged, connect(KIconLoader::global(), &KIconLoader::iconLoaderSettingsChanged, this, &IconItem::updateImplicitSize);
this, &IconItem::updateImplicitSize);
connect(this, &IconItem::implicitWidthChanged, this, &IconItem::implicitWidthChanged2); connect(this, &IconItem::implicitWidthChanged, this, &IconItem::implicitWidthChanged2);
connect(this, &IconItem::implicitHeightChanged, this, &IconItem::implicitHeightChanged2); connect(this, &IconItem::implicitHeightChanged, this, &IconItem::implicitHeightChanged2);
@ -346,9 +355,7 @@ void IconItem::setSource(const QVariant &source)
} }
if (!localFile.isEmpty()) { if (!localFile.isEmpty()) {
if (sourceString.endsWith(QLatin1String(".svg")) || if (sourceString.endsWith(QLatin1String(".svg")) || sourceString.endsWith(QLatin1String(".svgz")) || sourceString.endsWith(QLatin1String(".ico"))) {
sourceString.endsWith(QLatin1String(".svgz")) ||
sourceString.endsWith(QLatin1String(".ico"))) {
QIcon icon = QIcon(localFile); QIcon icon = QIcon(localFile);
m_iconItemSource.reset(new QIconSource(icon, this)); m_iconItemSource.reset(new QIconSource(icon, this));
} else { } else {
@ -359,14 +366,14 @@ void IconItem::setSource(const QVariant &source)
m_iconItemSource.reset(new SvgSource(sourceString, this)); m_iconItemSource.reset(new SvgSource(sourceString, this));
if (!m_iconItemSource->isValid()) { if (!m_iconItemSource->isValid()) {
//if we started with a QIcon use that. // if we started with a QIcon use that.
QIcon icon = source.value<QIcon>(); QIcon icon = source.value<QIcon>();
if (icon.isNull()) { if (icon.isNull()) {
icon = QIcon::fromTheme(sourceString); icon = QIcon::fromTheme(sourceString);
} }
m_iconItemSource.reset(new QIconSource(icon, this)); m_iconItemSource.reset(new QIconSource(icon, this));
//since QIcon is rendered by KIconLoader, watch for when its configuration changes now and reload as needed. // since QIcon is rendered by KIconLoader, watch for when its configuration changes now and reload as needed.
connect(KIconLoader::global(), &KIconLoader::iconChanged, this, &IconItem::iconLoaderIconChanged); connect(KIconLoader::global(), &KIconLoader::iconChanged, this, &IconItem::iconLoaderIconChanged);
} }
} }
@ -412,7 +419,6 @@ Plasma::Theme::ColorGroup IconItem::colorGroup() const
return m_colorGroup; return m_colorGroup;
} }
void IconItem::setOverlays(const QStringList &overlays) void IconItem::setOverlays(const QStringList &overlays)
{ {
if (overlays == m_overlays) { if (overlays == m_overlays) {
@ -428,7 +434,6 @@ QStringList IconItem::overlays() const
return m_overlays; return m_overlays;
} }
bool IconItem::isActive() const bool IconItem::isActive() const
{ {
return m_active; return m_active;
@ -588,7 +593,7 @@ void IconItem::updatePolish()
loadPixmap(); loadPixmap();
} }
QSGNode* IconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData) QSGNode *IconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData)
{ {
Q_UNUSED(updatePaintNodeData) Q_UNUSED(updatePaintNodeData)
@ -598,7 +603,7 @@ QSGNode* IconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *update
} }
if (m_animation->state() == QAbstractAnimation::Running) { if (m_animation->state() == QAbstractAnimation::Running) {
FadingNode *animatingNode = dynamic_cast<FadingNode*>(oldNode); FadingNode *animatingNode = dynamic_cast<FadingNode *>(oldNode);
if (!animatingNode || m_textureChanged) { if (!animatingNode || m_textureChanged) {
delete oldNode; delete oldNode;
@ -623,7 +628,7 @@ QSGNode* IconItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *update
return animatingNode; return animatingNode;
} else { } else {
ManagedTextureNode *textureNode = dynamic_cast<ManagedTextureNode*>(oldNode); ManagedTextureNode *textureNode = dynamic_cast<ManagedTextureNode *>(oldNode);
if (!textureNode || m_textureChanged) { if (!textureNode || m_textureChanged) {
delete oldNode; delete oldNode;
@ -692,7 +697,7 @@ void IconItem::loadPixmap()
size = Units::roundToIconSize(size); size = Units::roundToIconSize(size);
} }
//final pixmap to paint // final pixmap to paint
QPixmap result; QPixmap result;
if (size <= 0) { if (size <= 0) {
m_iconPixmap = QPixmap(); m_iconPixmap = QPixmap();
@ -739,7 +744,7 @@ void IconItem::loadPixmap()
Q_EMIT paintedSizeChanged(); Q_EMIT paintedSizeChanged();
} }
//don't animate initial setting // don't animate initial setting
bool animated = (m_animated || m_allowNextAnimation) && !m_oldIconPixmap.isNull() && !m_sizeChanged && !m_blockNextAnimation; bool animated = (m_animated || m_allowNextAnimation) && !m_oldIconPixmap.isNull() && !m_sizeChanged && !m_blockNextAnimation;
if (QQuickWindow::sceneGraphBackend() == QLatin1String("software")) { if (QQuickWindow::sceneGraphBackend() == QLatin1String("software")) {
@ -775,14 +780,12 @@ void IconItem::itemChange(ItemChange change, const ItemChangeData &value)
connect(m_window.data(), &QWindow::visibleChanged, this, &IconItem::windowVisibleChanged); connect(m_window.data(), &QWindow::visibleChanged, this, &IconItem::windowVisibleChanged);
} }
schedulePixmapUpdate(); schedulePixmapUpdate();
} }
QQuickItem::itemChange(change, value); QQuickItem::itemChange(change, value);
} }
void IconItem::geometryChanged(const QRectF &newGeometry, void IconItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
const QRectF &oldGeometry)
{ {
if (newGeometry.size() != oldGeometry.size()) { if (newGeometry.size() != oldGeometry.size()) {
m_sizeChanged = true; m_sizeChanged = true;

View File

@ -9,11 +9,11 @@
#define ICONITEM_H #define ICONITEM_H
#include <QIcon> #include <QIcon>
#include <QQuickItem>
#include <QPixmap> #include <QPixmap>
#include <QPointer> #include <QPointer>
#include <QVariant> #include <QQuickItem>
#include <QTimer> #include <QTimer>
#include <QVariant>
#include <plasma/svg.h> #include <plasma/svg.h>
@ -51,8 +51,8 @@ class IconItem : public QQuickItem
Q_PROPERTY(Plasma::Theme::ColorGroup colorGroup READ colorGroup WRITE setColorGroup NOTIFY colorGroupChanged) Q_PROPERTY(Plasma::Theme::ColorGroup colorGroup READ colorGroup WRITE setColorGroup NOTIFY colorGroupChanged)
/** /**
* Specifies the overlay(s) for this icon * Specifies the overlay(s) for this icon
*/ */
Q_PROPERTY(QStringList overlays READ overlays WRITE setOverlays NOTIFY overlaysChanged) Q_PROPERTY(QStringList overlays READ overlays WRITE setOverlays NOTIFY overlaysChanged)
/** /**
@ -145,11 +145,10 @@ public:
void setImplicitWidth2(int height); void setImplicitWidth2(int height);
void updatePolish() override; void updatePolish() override;
QSGNode* updatePaintNode(QSGNode * oldNode, UpdatePaintNodeData * updatePaintNodeData) override; QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData) override;
void itemChange(ItemChange change, const ItemChangeData &value) override; void itemChange(ItemChange change, const ItemChangeData &value) override;
void geometryChanged(const QRectF &newGeometry, void geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) override;
const QRectF &oldGeometry) override;
void componentComplete() override; void componentComplete() override;
@ -180,9 +179,9 @@ private:
QSize paintedSize(const QSizeF &containerSize = QSizeF()) const; QSize paintedSize(const QSizeF &containerSize = QSizeF()) const;
void updateImplicitSize(); void updateImplicitSize();
//all the ways we can set an source. Only one of them will be valid // all the ways we can set an source. Only one of them will be valid
QScopedPointer<IconItemSource> m_iconItemSource; QScopedPointer<IconItemSource> m_iconItemSource;
//this contains the raw variant it was passed // this contains the raw variant it was passed
QVariant m_source; QVariant m_source;
Plasma::Svg::Status m_status; Plasma::Svg::Status m_status;
@ -205,7 +204,7 @@ private:
Plasma::Theme::ColorGroup m_colorGroup; Plasma::Theme::ColorGroup m_colorGroup;
//animation on pixmap change // animation on pixmap change
QPropertyAnimation *m_animation; QPropertyAnimation *m_animation;
qreal m_animValue; qreal m_animValue;

View File

@ -6,11 +6,8 @@
#include "quicktheme.h" #include "quicktheme.h"
namespace Plasma namespace Plasma
{ {
QuickTheme::QuickTheme(QObject *parent) QuickTheme::QuickTheme(QObject *parent)
: Theme(parent) : Theme(parent)
{ {
@ -191,7 +188,6 @@ QColor QuickTheme::complementaryNegativeTextColor() const
return Plasma::Theme::color(Plasma::Theme::TextColor, Plasma::Theme::ComplementaryColorGroup); return Plasma::Theme::color(Plasma::Theme::TextColor, Plasma::Theme::ComplementaryColorGroup);
} }
QColor QuickTheme::headerTextColor() const QColor QuickTheme::headerTextColor() const
{ {
return Plasma::Theme::color(Plasma::Theme::TextColor, Plasma::Theme::HeaderColorGroup); return Plasma::Theme::color(Plasma::Theme::TextColor, Plasma::Theme::HeaderColorGroup);

View File

@ -14,7 +14,6 @@
namespace Plasma namespace Plasma
{ {
/** /**
* @class QuickTheme plasma/theme.h <Plasma/Theme> * @class QuickTheme plasma/theme.h <Plasma/Theme>
* *
@ -85,8 +84,6 @@ public:
explicit QuickTheme(QObject *parent = nullptr); explicit QuickTheme(QObject *parent = nullptr);
~QuickTheme(); ~QuickTheme();
/** /**
* @return The theme's colorscheme's text color * @return The theme's colorscheme's text color
* @since 5.0 * @since 5.0
@ -291,7 +288,6 @@ public:
*/ */
QColor complementaryNegativeTextColor() const; QColor complementaryNegativeTextColor() const;
/** /**
* @return The theme's colorscheme's text color of "header" areas * @return The theme's colorscheme's text color of "header" areas
* @since 5.0 * @since 5.0
@ -347,4 +343,3 @@ Q_SIGNALS:
} // Plasma namespace } // Plasma namespace
#endif // multiple inclusion guard #endif // multiple inclusion guard

View File

@ -7,8 +7,8 @@
#include "serviceoperationstatus.h" #include "serviceoperationstatus.h"
ServiceOperationStatus::ServiceOperationStatus(QObject *parent) ServiceOperationStatus::ServiceOperationStatus(QObject *parent)
: QObject(parent), : QObject(parent)
m_enabled(false) , m_enabled(false)
{ {
} }
@ -26,8 +26,7 @@ void ServiceOperationStatus::setService(Plasma::Service *service)
disconnect(m_service.data(), nullptr, this, nullptr); disconnect(m_service.data(), nullptr, this, nullptr);
} }
if (service) { if (service) {
connect(service, &Plasma::Service::operationEnabledChanged, connect(service, &Plasma::Service::operationEnabledChanged, this, &ServiceOperationStatus::updateStatus);
this, &ServiceOperationStatus::updateStatus);
} }
m_service = service; m_service = service;
@ -84,4 +83,3 @@ void ServiceOperationStatus::updateStatus()
Q_EMIT enabledChanged(); Q_EMIT enabledChanged();
} }
} }

View File

@ -7,10 +7,10 @@
#include "svgitem.h" #include "svgitem.h"
#include <QQuickWindow>
#include <QSGTexture>
#include <QRectF>
#include <QDebug> #include <QDebug>
#include <QQuickWindow>
#include <QRectF>
#include <QSGTexture>
#include "plasma/svg.h" #include "plasma/svg.h"
@ -20,10 +20,9 @@
namespace Plasma namespace Plasma
{ {
SvgItem::SvgItem(QQuickItem *parent) SvgItem::SvgItem(QQuickItem *parent)
: QQuickItem(parent), : QQuickItem(parent)
m_textureChanged(false) , m_textureChanged(false)
{ {
setFlag(QQuickItem::ItemHasContents, true); setFlag(QQuickItem::ItemHasContents, true);
connect(&Units::instance(), &Units::devicePixelRatioChanged, this, &SvgItem::updateDevicePixelRatio); connect(&Units::instance(), &Units::devicePixelRatioChanged, this, &SvgItem::updateDevicePixelRatio);
@ -109,7 +108,7 @@ QSGNode *SvgItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updateP
return nullptr; return nullptr;
} }
//this is more than just an optimization, uploading a null image to QSGAtlasTexture causes a crash // this is more than just an optimization, uploading a null image to QSGAtlasTexture causes a crash
if (width() == 0.0 || height() == 0.0) { if (width() == 0.0 || height() == 0.0) {
delete oldNode; delete oldNode;
return nullptr; return nullptr;
@ -121,14 +120,14 @@ QSGNode *SvgItem::updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updateP
m_textureChanged = true; m_textureChanged = true;
} }
//TODO use a heuristic to work out when to redraw // TODO use a heuristic to work out when to redraw
//if !m_smooth and size is approximate simply change the textureNode.rect without // if !m_smooth and size is approximate simply change the textureNode.rect without
//updating the material // updating the material
if (m_textureChanged || textureNode->texture()->textureSize() != QSize(width(), height())) { if (m_textureChanged || textureNode->texture()->textureSize() != QSize(width(), height())) {
//despite having a valid size sometimes we still get a null QImage from Plasma::Svg // despite having a valid size sometimes we still get a null QImage from Plasma::Svg
//loading a null texture to an atlas fatals // loading a null texture to an atlas fatals
//Dave E fixed this in Qt in 5.3.something onwards but we need this for now // Dave E fixed this in Qt in 5.3.something onwards but we need this for now
if (m_image.isNull()) { if (m_image.isNull()) {
delete textureNode; delete textureNode;
return nullptr; return nullptr;
@ -160,7 +159,7 @@ void SvgItem::updateNeeded()
void SvgItem::updateDevicePixelRatio() void SvgItem::updateDevicePixelRatio()
{ {
if (m_svg) { if (m_svg) {
//devicepixelratio is always set integer in the svg, so needs at least 192dpi to double up. // devicepixelratio is always set integer in the svg, so needs at least 192dpi to double up.
//(it needs to be integer to have lines contained inside a svg piece to keep being pixel aligned) //(it needs to be integer to have lines contained inside a svg piece to keep being pixel aligned)
if (window()) { if (window()) {
m_svg.data()->setDevicePixelRatio(qMax<qreal>(1.0, floor(window()->devicePixelRatio()))); m_svg.data()->setDevicePixelRatio(qMax<qreal>(1.0, floor(window()->devicePixelRatio())));
@ -182,7 +181,7 @@ void SvgItem::updatePolish()
QQuickItem::updatePolish(); QQuickItem::updatePolish();
if (m_svg) { if (m_svg) {
//setContainsMultipleImages has to be done there since m_frameSvg can be shared with somebody else // setContainsMultipleImages has to be done there since m_frameSvg can be shared with somebody else
m_textureChanged = true; m_textureChanged = true;
m_svg.data()->setContainsMultipleImages(!m_elementID.isEmpty()); m_svg.data()->setContainsMultipleImages(!m_elementID.isEmpty());
m_image = m_svg.data()->image(QSize(width(), height()), m_elementID); m_image = m_svg.data()->image(QSize(width(), height()), m_elementID);
@ -199,4 +198,3 @@ void SvgItem::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeomet
} }
} // Plasma namespace } // Plasma namespace

View File

@ -7,14 +7,13 @@
#ifndef SVGITEM_P #ifndef SVGITEM_P
#define SVGITEM_P #define SVGITEM_P
#include <QQuickItem>
#include <QImage> #include <QImage>
#include <QQuickItem>
#include "units.h" #include "units.h"
namespace Plasma namespace Plasma
{ {
class Svg; class Svg;
/** /**
@ -48,7 +47,7 @@ class SvgItem : public QQuickItem
Q_PROPERTY(QSizeF naturalSize READ naturalSize NOTIFY naturalSizeChanged) Q_PROPERTY(QSizeF naturalSize READ naturalSize NOTIFY naturalSizeChanged)
public: public:
/// @cond INTERNAL_DOCS /// @cond INTERNAL_DOCS
explicit SvgItem(QQuickItem *parent = nullptr); explicit SvgItem(QQuickItem *parent = nullptr);
~SvgItem() override; ~SvgItem() override;
@ -62,7 +61,7 @@ public:
QSizeF naturalSize() const; QSizeF naturalSize() const;
QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData) override; QSGNode *updatePaintNode(QSGNode *oldNode, UpdatePaintNodeData *updatePaintNodeData) override;
/// @endcond /// @endcond
Q_SIGNALS: Q_SIGNALS:
void elementIdChanged(); void elementIdChanged();
@ -70,10 +69,10 @@ Q_SIGNALS:
void naturalSizeChanged(); void naturalSizeChanged();
protected Q_SLOTS: protected Q_SLOTS:
/// @cond INTERNAL_DOCS /// @cond INTERNAL_DOCS
void updateNeeded(); void updateNeeded();
void updateDevicePixelRatio(); void updateDevicePixelRatio();
/// @endcond /// @endcond
private: private:
void scheduleImageUpdate(); void scheduleImageUpdate();

View File

@ -9,26 +9,26 @@
#include "tooltip.h" #include "tooltip.h"
#include "tooltipdialog.h" #include "tooltipdialog.h"
#include <QQmlEngine>
#include <QDebug> #include <QDebug>
#include <QQmlEngine>
#include "framesvgitem.h" #include "framesvgitem.h"
#include <KWindowEffects>
#include <KDirWatch> #include <KDirWatch>
#include <KWindowEffects>
ToolTipDialog *ToolTip::s_dialog = nullptr; ToolTipDialog *ToolTip::s_dialog = nullptr;
int ToolTip::s_dialogUsers = 0; int ToolTip::s_dialogUsers = 0;
ToolTip::ToolTip(QQuickItem *parent) ToolTip::ToolTip(QQuickItem *parent)
: QQuickItem(parent), : QQuickItem(parent)
m_tooltipsEnabledGlobally(false), , m_tooltipsEnabledGlobally(false)
m_containsMouse(false), , m_containsMouse(false)
m_location(Plasma::Types::Floating), , m_location(Plasma::Types::Floating)
m_textFormat(Qt::AutoText), , m_textFormat(Qt::AutoText)
m_active(true), , m_active(true)
m_interactive(false), , m_interactive(false)
m_timeout(4000), , m_timeout(4000)
m_usingDialog(false) , m_usingDialog(false)
{ {
setAcceptHoverEvents(true); setAcceptHoverEvents(true);
setFiltersChildMouseEvents(true); setFiltersChildMouseEvents(true);
@ -331,7 +331,7 @@ void ToolTip::hoverEnterEvent(QHoverEvent *event)
// It need to be considered only when other items can deal with tooltip area // It need to be considered only when other items can deal with tooltip area
if (m_active) { if (m_active) {
tooltipDialogInstance()->keepalive(); tooltipDialogInstance()->keepalive();
//FIXME: showToolTip needs to be renamed in sync or something like that // FIXME: showToolTip needs to be renamed in sync or something like that
showToolTip(); showToolTip();
} }
} else { } else {

View File

@ -9,10 +9,10 @@
#ifndef TOOLTIPOBJECT_H #ifndef TOOLTIPOBJECT_H
#define TOOLTIPOBJECT_H #define TOOLTIPOBJECT_H
#include <QQuickItem>
#include <QPointer>
#include <QVariant>
#include <Plasma/Plasma> #include <Plasma/Plasma>
#include <QPointer>
#include <QQuickItem>
#include <QVariant>
class QQuickItem; class QQuickItem;
class ToolTipDialog; class ToolTipDialog;
@ -107,7 +107,8 @@ class ToolTip : public QQuickItem
/** /**
* if interactive is false (default), the tooltip will automatically hide * if interactive is false (default), the tooltip will automatically hide
* itself as soon as the mouse leaves the tooltiparea, if is true, if the mouse leaves tooltiparea and goes over the tooltip itself, the tooltip won't hide, so it will be possible to interact with tooltip contents * itself as soon as the mouse leaves the tooltiparea, if is true, if the mouse leaves tooltiparea and goes over the tooltip itself, the tooltip won't hide,
* so it will be possible to interact with tooltip contents
*/ */
Q_PROPERTY(bool interactive MEMBER m_interactive WRITE setInteractive NOTIFY interactiveChanged) Q_PROPERTY(bool interactive MEMBER m_interactive WRITE setInteractive NOTIFY interactiveChanged)
@ -118,7 +119,7 @@ class ToolTip : public QQuickItem
Q_PROPERTY(int timeout MEMBER m_timeout WRITE setTimeout) Q_PROPERTY(int timeout MEMBER m_timeout WRITE setTimeout)
public: public:
/// @cond INTERNAL_DOCS /// @cond INTERNAL_DOCS
explicit ToolTip(QQuickItem *parent = nullptr); explicit ToolTip(QQuickItem *parent = nullptr);
~ToolTip() override; ~ToolTip() override;
@ -151,7 +152,7 @@ public:
void setInteractive(bool interactive); void setInteractive(bool interactive);
void setTimeout(int timeout); void setTimeout(int timeout);
/// @endcond /// @endcond
public Q_SLOTS: public Q_SLOTS:
@ -167,13 +168,13 @@ public Q_SLOTS:
void hideToolTip(); void hideToolTip();
protected: protected:
/// @cond INTERNAL_DOCS /// @cond INTERNAL_DOCS
bool childMouseEventFilter(QQuickItem *item, QEvent *event) override; bool childMouseEventFilter(QQuickItem *item, QEvent *event) override;
void hoverEnterEvent(QHoverEvent *event) override; void hoverEnterEvent(QHoverEvent *event) override;
void hoverLeaveEvent(QHoverEvent *event) override; void hoverLeaveEvent(QHoverEvent *event) override;
ToolTipDialog *tooltipDialogInstance(); ToolTipDialog *tooltipDialogInstance();
/// @endcond /// @endcond
Q_SIGNALS: Q_SIGNALS:
void mainItemChanged(); void mainItemChanged();
@ -215,9 +216,9 @@ private:
int m_interval; int m_interval;
int m_timeout; int m_timeout;
//ToolTipDialog is not a Q_GLOBAL_STATIC because QQuickwindows as global static // ToolTipDialog is not a Q_GLOBAL_STATIC because QQuickwindows as global static
//are deleted too later after some stuff in the qml runtime has already been deleted, // are deleted too later after some stuff in the qml runtime has already been deleted,
//causing a crash on exit // causing a crash on exit
bool m_usingDialog : 1; bool m_usingDialog : 1;
static ToolTipDialog *s_dialog; static ToolTipDialog *s_dialog;
static int s_dialogUsers; static int s_dialogUsers;

View File

@ -6,20 +6,20 @@
#include "tooltipdialog.h" #include "tooltipdialog.h"
#include <QQmlEngine>
#include <QQuickItem>
#include <QDebug> #include <QDebug>
#include <QPlatformSurfaceEvent> #include <QPlatformSurfaceEvent>
#include <QQmlEngine>
#include <QQuickItem>
#include <kdeclarative/qmlobjectsharedengine.h>
#include <KWindowSystem> #include <KWindowSystem>
#include <kdeclarative/qmlobjectsharedengine.h>
ToolTipDialog::ToolTipDialog(QQuickItem *parent) ToolTipDialog::ToolTipDialog(QQuickItem *parent)
: Dialog(parent), : Dialog(parent)
m_qmlObject(nullptr), , m_qmlObject(nullptr)
m_hideTimeout(4000), , m_hideTimeout(4000)
m_interactive(false), , m_interactive(false)
m_owner(nullptr) , m_owner(nullptr)
{ {
setLocation(Plasma::Types::Floating); setLocation(Plasma::Types::Floating);
setType(Dialog::WindowType::Tooltip); setType(Dialog::WindowType::Tooltip);
@ -42,7 +42,7 @@ QQuickItem *ToolTipDialog::loadDefaultItem()
} }
if (!m_qmlObject->rootObject()) { if (!m_qmlObject->rootObject()) {
//HACK: search our own import // HACK: search our own import
const auto paths = m_qmlObject->engine()->importPathList(); const auto paths = m_qmlObject->engine()->importPathList();
for (const QString &path : paths) { for (const QString &path : paths) {
if (QFile::exists(path + QStringLiteral("/org/kde/plasma/core"))) { if (QFile::exists(path + QStringLiteral("/org/kde/plasma/core"))) {

View File

@ -9,8 +9,8 @@
#include "dialog.h" #include "dialog.h"
#include <QTimer>
#include <QQuickWindow> #include <QQuickWindow>
#include <QTimer>
#include <QVariant> #include <QVariant>
class QQuickItem; class QQuickItem;

View File

@ -8,20 +8,19 @@
#include "units.h" #include "units.h"
#include <QGuiApplication>
#include <QDebug> #include <QDebug>
#include <QtGlobal> #include <QFontMetrics>
#include <QGuiApplication>
#include <QQuickItem> #include <QQuickItem>
#include <QQuickWindow> #include <QQuickWindow>
#include <QScreen> #include <QScreen>
#include <QFontMetrics> #include <QtGlobal>
#include <cmath> #include <cmath>
#include <KIconLoader> #include <KIconLoader>
const int defaultLongDuration = 200; const int defaultLongDuration = 200;
SharedAppFilter::SharedAppFilter(QObject *parent) SharedAppFilter::SharedAppFilter(QObject *parent)
: QObject(parent) : QObject(parent)
{ {
@ -29,7 +28,8 @@ SharedAppFilter::SharedAppFilter(QObject *parent)
} }
SharedAppFilter::~SharedAppFilter() SharedAppFilter::~SharedAppFilter()
{} {
}
bool SharedAppFilter::eventFilter(QObject *watched, QEvent *event) bool SharedAppFilter::eventFilter(QObject *watched, QEvent *event)
{ {
@ -44,12 +44,12 @@ bool SharedAppFilter::eventFilter(QObject *watched, QEvent *event)
SharedAppFilter *Units::s_sharedAppFilter = nullptr; SharedAppFilter *Units::s_sharedAppFilter = nullptr;
Units::Units(QObject *parent) Units::Units(QObject *parent)
: QObject(parent), : QObject(parent)
m_gridUnit(-1), , m_gridUnit(-1)
m_devicePixelRatio(-1), , m_devicePixelRatio(-1)
m_smallSpacing(-1), , m_smallSpacing(-1)
m_largeSpacing(-1), , m_largeSpacing(-1)
m_longDuration(defaultLongDuration) // default base value for animations , m_longDuration(defaultLongDuration) // default base value for animations
{ {
if (!s_sharedAppFilter) { if (!s_sharedAppFilter) {
s_sharedAppFilter = new SharedAppFilter(); s_sharedAppFilter = new SharedAppFilter();
@ -64,18 +64,16 @@ Units::Units(QObject *parent)
QObject::connect(s_sharedAppFilter, &SharedAppFilter::fontChanged, this, &Units::updateSpacing); QObject::connect(s_sharedAppFilter, &SharedAppFilter::fontChanged, this, &Units::updateSpacing);
m_animationSpeedWatcher = KConfigWatcher::create(KSharedConfig::openConfig()); m_animationSpeedWatcher = KConfigWatcher::create(KSharedConfig::openConfig());
connect(m_animationSpeedWatcher.data(), &KConfigWatcher::configChanged, this, connect(m_animationSpeedWatcher.data(), &KConfigWatcher::configChanged, this, [this](const KConfigGroup &group, const QByteArrayList &names) {
[this](const KConfigGroup &group, const QByteArrayList &names) { if (group.name() == QLatin1String("KDE") && names.contains(QByteArrayLiteral("AnimationDurationFactor"))) {
if (group.name() == QLatin1String("KDE") && names.contains(QByteArrayLiteral("AnimationDurationFactor"))) { updateAnimationSpeed();
updateAnimationSpeed(); }
}
}); });
updateAnimationSpeed(); updateAnimationSpeed();
} }
Units::~Units() Units::~Units()
{ {
} }
Units &Units::instance() Units &Units::instance()
@ -105,7 +103,6 @@ void Units::updateAnimationSpeed()
} }
} }
void Units::iconLoaderSettingsChanged() void Units::iconLoaderSettingsChanged()
{ {
m_iconSizes->insert(QStringLiteral("desktop"), devicePixelIconSize(KIconLoader::global()->currentSize(KIconLoader::Desktop))); m_iconSizes->insert(QStringLiteral("desktop"), devicePixelIconSize(KIconLoader::global()->currentSize(KIconLoader::Desktop)));
@ -141,7 +138,7 @@ int Units::roundToIconSize(int size)
if (size <= 0) { if (size <= 0) {
return 0; return 0;
} else if (size < KIconLoader::SizeSmall) { } else if (size < KIconLoader::SizeSmall) {
return KIconLoader::SizeSmall/2; return KIconLoader::SizeSmall / 2;
} else if (size < KIconLoader::SizeSmallMedium) { } else if (size < KIconLoader::SizeSmallMedium) {
return KIconLoader::SizeSmall; return KIconLoader::SizeSmall;
@ -263,7 +260,7 @@ int Units::shortDuration() const
int Units::veryShortDuration() const int Units::veryShortDuration() const
{ {
return qRound(m_longDuration * 0.25); return qRound(m_longDuration * 0.25);
} }
int Units::veryLongDuration() const int Units::veryLongDuration() const
@ -272,4 +269,3 @@ int Units::veryLongDuration() const
} }
#include "moc_units.cpp" #include "moc_units.cpp"

View File

@ -19,7 +19,7 @@ class QQuickItem;
class SharedAppFilter : public QObject class SharedAppFilter : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
explicit SharedAppFilter(QObject *parent = nullptr); explicit SharedAppFilter(QObject *parent = nullptr);
~SharedAppFilter() override; ~SharedAppFilter() override;
@ -62,8 +62,8 @@ class Units : public QObject
* * desktop (DEPRECATED: use iconSizeHints instead) * * desktop (DEPRECATED: use iconSizeHints instead)
* *
*/ */
//note the iconSizeChanged signal indicates that one (or more) of these icons have changed // note the iconSizeChanged signal indicates that one (or more) of these icons have changed
//but the property map itself remains constant // but the property map itself remains constant
Q_PROPERTY(QQmlPropertyMap *iconSizes READ iconSizes CONSTANT) Q_PROPERTY(QQmlPropertyMap *iconSizes READ iconSizes CONSTANT)
/** /**
@ -77,8 +77,8 @@ class Units : public QObject
* * panel * * panel
* * desktop * * desktop
*/ */
//note the iconSizeHintsChanged signal indicates that one (or more) of these icons have changed // note the iconSizeHintsChanged signal indicates that one (or more) of these icons have changed
//but the property map itself remains constant // but the property map itself remains constant
Q_PROPERTY(QQmlPropertyMap *iconSizeHints READ iconSizeHints CONSTANT) Q_PROPERTY(QQmlPropertyMap *iconSizeHints READ iconSizeHints CONSTANT)
// layout hints // layout hints
@ -132,7 +132,7 @@ class Units : public QObject
Q_PROPERTY(int veryLongDuration READ veryLongDuration NOTIFY durationChanged) Q_PROPERTY(int veryLongDuration READ veryLongDuration NOTIFY durationChanged)
public: public:
/// @cond INTERNAL_DOCS /// @cond INTERNAL_DOCS
~Units(); ~Units();
@ -198,7 +198,7 @@ public:
* @since 5.78 * @since 5.78
*/ */
int veryShortDuration() const; int veryShortDuration() const;
/// @endcond /// @endcond
/** /**
* @return a size rounded tothe nearest inferior standard icon size. * @return a size rounded tothe nearest inferior standard icon size.
@ -222,10 +222,10 @@ private Q_SLOTS:
private: private:
Units(QObject *parent = nullptr); Units(QObject *parent = nullptr);
Units(Units const&) = delete; // Copy construct Units(Units const &) = delete; // Copy construct
Units(Units&&) = delete; // Move construct Units(Units &&) = delete; // Move construct
Units& operator=(Units const&) = delete; // Copy assign Units &operator=(Units const &) = delete; // Copy assign
Units& operator=(Units &&) = delete; // Move assign Units &operator=(Units &&) = delete; // Move assign
void updateDevicePixelRatio(); void updateDevicePixelRatio();
void updateAnimationSpeed(); void updateAnimationSpeed();
@ -248,5 +248,4 @@ private:
int m_longDuration; int m_longDuration;
}; };
#endif //UNITS_H #endif // UNITS_H

View File

@ -19,14 +19,13 @@
#include <xcb/composite.h> #include <xcb/composite.h>
#if HAVE_GLX #if HAVE_GLX
#include <GL/glx.h> #include <GL/glx.h>
typedef void (*glXBindTexImageEXT_func)(Display *dpy, GLXDrawable drawable, typedef void (*glXBindTexImageEXT_func)(Display *dpy, GLXDrawable drawable, int buffer, const int *attrib_list);
int buffer, const int *attrib_list);
typedef void (*glXReleaseTexImageEXT_func)(Display *dpy, GLXDrawable drawable, int buffer); typedef void (*glXReleaseTexImageEXT_func)(Display *dpy, GLXDrawable drawable, int buffer);
#endif #endif
#if HAVE_EGL #if HAVE_EGL
typedef EGLImageKHR(*eglCreateImageKHR_func)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *); typedef EGLImageKHR (*eglCreateImageKHR_func)(EGLDisplay, EGLContext, EGLenum, EGLClientBuffer, const EGLint *);
typedef EGLBoolean(*eglDestroyImageKHR_func)(EGLDisplay, EGLImageKHR); typedef EGLBoolean (*eglDestroyImageKHR_func)(EGLDisplay, EGLImageKHR);
typedef GLvoid(*glEGLImageTargetTexture2DOES_func)(GLenum, GLeglImageOES); typedef GLvoid (*glEGLImageTargetTexture2DOES_func)(GLenum, GLeglImageOES);
#endif // HAVE_EGL #endif // HAVE_EGL
#endif #endif
@ -34,17 +33,14 @@ typedef GLvoid(*glEGLImageTargetTexture2DOES_func)(GLenum, GLeglImageOES);
namespace Plasma namespace Plasma
{ {
#if HAVE_XCB_COMPOSITE #if HAVE_XCB_COMPOSITE
#if HAVE_GLX #if HAVE_GLX
class DiscardGlxPixmapRunnable : public QRunnable { class DiscardGlxPixmapRunnable : public QRunnable
{
public: public:
DiscardGlxPixmapRunnable( DiscardGlxPixmapRunnable(uint, QFunctionPointer, xcb_pixmap_t);
uint,
QFunctionPointer,
xcb_pixmap_t
);
void run() override; void run() override;
private: private:
uint m_texture; uint m_texture;
QFunctionPointer m_releaseTexImage; QFunctionPointer m_releaseTexImage;
@ -52,11 +48,12 @@ private:
}; };
DiscardGlxPixmapRunnable::DiscardGlxPixmapRunnable(uint texture, QFunctionPointer deleteFunction, xcb_pixmap_t pixmap) DiscardGlxPixmapRunnable::DiscardGlxPixmapRunnable(uint texture, QFunctionPointer deleteFunction, xcb_pixmap_t pixmap)
: QRunnable(), : QRunnable()
m_texture(texture), , m_texture(texture)
m_releaseTexImage(deleteFunction), , m_releaseTexImage(deleteFunction)
m_glxPixmap(pixmap) , m_glxPixmap(pixmap)
{} {
}
void DiscardGlxPixmapRunnable::run() void DiscardGlxPixmapRunnable::run()
{ {
@ -67,17 +64,15 @@ void DiscardGlxPixmapRunnable::run()
glDeleteTextures(1, &m_texture); glDeleteTextures(1, &m_texture);
} }
} }
#endif //HAVE_GLX #endif // HAVE_GLX
#if HAVE_EGL #if HAVE_EGL
class DiscardEglPixmapRunnable : public QRunnable { class DiscardEglPixmapRunnable : public QRunnable
{
public: public:
DiscardEglPixmapRunnable( DiscardEglPixmapRunnable(uint, QFunctionPointer, EGLImageKHR);
uint,
QFunctionPointer,
EGLImageKHR
);
void run() override; void run() override;
private: private:
uint m_texture; uint m_texture;
QFunctionPointer m_eglDestroyImageKHR; QFunctionPointer m_eglDestroyImageKHR;
@ -85,11 +80,12 @@ private:
}; };
DiscardEglPixmapRunnable::DiscardEglPixmapRunnable(uint texture, QFunctionPointer deleteFunction, EGLImageKHR image) DiscardEglPixmapRunnable::DiscardEglPixmapRunnable(uint texture, QFunctionPointer deleteFunction, EGLImageKHR image)
: QRunnable(), : QRunnable()
m_texture(texture), , m_texture(texture)
m_eglDestroyImageKHR(deleteFunction), , m_eglDestroyImageKHR(deleteFunction)
m_image(image) , m_image(image)
{} {
}
void DiscardEglPixmapRunnable::run() void DiscardEglPixmapRunnable::run()
{ {
@ -98,8 +94,8 @@ void DiscardEglPixmapRunnable::run()
glDeleteTextures(1, &m_texture); glDeleteTextures(1, &m_texture);
} }
} }
#endif//HAVE_EGL #endif // HAVE_EGL
#endif //HAVE_XCB_COMPOSITE #endif // HAVE_XCB_COMPOSITE
WindowTextureNode::WindowTextureNode() WindowTextureNode::WindowTextureNode()
: QSGSimpleTextureNode() : QSGSimpleTextureNode()
@ -219,22 +215,19 @@ void WindowThumbnail::releaseResources()
#if HAVE_XCB_COMPOSITE #if HAVE_XCB_COMPOSITE
#if HAVE_GLX && HAVE_EGL #if HAVE_GLX && HAVE_EGL
//only one (or none) should be set, but never both // only one (or none) should be set, but never both
Q_ASSERT(m_glxPixmap == XCB_PIXMAP_NONE || m_image == EGL_NO_IMAGE_KHR); Q_ASSERT(m_glxPixmap == XCB_PIXMAP_NONE || m_image == EGL_NO_IMAGE_KHR);
#endif #endif
#if HAVE_GLX || HAVE_EGL #if HAVE_GLX || HAVE_EGL
QQuickWindow::RenderStage m_renderStage = QQuickWindow::NoStage; QQuickWindow::RenderStage m_renderStage = QQuickWindow::NoStage;
#endif #endif
//data is deleted in the render thread (with relevant GLX calls) // data is deleted in the render thread (with relevant GLX calls)
//note runnable may be called *after* this is deleted // note runnable may be called *after* this is deleted
//but the pointer is held by the WindowThumbnail which is in the main thread // but the pointer is held by the WindowThumbnail which is in the main thread
#if HAVE_GLX #if HAVE_GLX
if (m_glxPixmap != XCB_PIXMAP_NONE) { if (m_glxPixmap != XCB_PIXMAP_NONE) {
window()->scheduleRenderJob(new DiscardGlxPixmapRunnable(m_texture, window()->scheduleRenderJob(new DiscardGlxPixmapRunnable(m_texture, m_releaseTexImage, m_glxPixmap), m_renderStage);
m_releaseTexImage,
m_glxPixmap),
m_renderStage);
m_glxPixmap = XCB_PIXMAP_NONE; m_glxPixmap = XCB_PIXMAP_NONE;
m_texture = 0; m_texture = 0;
@ -242,10 +235,7 @@ void WindowThumbnail::releaseResources()
#endif #endif
#if HAVE_EGL #if HAVE_EGL
if (m_image != EGL_NO_IMAGE_KHR) { if (m_image != EGL_NO_IMAGE_KHR) {
window()->scheduleRenderJob(new DiscardEglPixmapRunnable(m_texture, window()->scheduleRenderJob(new DiscardEglPixmapRunnable(m_texture, m_eglDestroyImageKHR, m_image), m_renderStage);
m_eglDestroyImageKHR,
m_image),
m_renderStage);
m_image = EGL_NO_IMAGE_KHR; m_image = EGL_NO_IMAGE_KHR;
m_texture = 0; m_texture = 0;
@ -254,8 +244,6 @@ void WindowThumbnail::releaseResources()
#endif #endif
} }
uint32_t WindowThumbnail::winId() const uint32_t WindowThumbnail::winId() const
{ {
return m_winId; return m_winId;
@ -434,13 +422,9 @@ bool WindowThumbnail::xcbWindowToTextureEGL(WindowTextureNode *textureNode)
xcb_connection_t *c = QX11Info::connection(); xcb_connection_t *c = QX11Info::connection();
auto geometryCookie = xcb_get_geometry_unchecked(c, m_pixmap); auto geometryCookie = xcb_get_geometry_unchecked(c, m_pixmap);
const EGLint attribs[] = { const EGLint attribs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE};
EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, m_image = ((eglCreateImageKHR_func)(
EGL_NONE m_eglCreateImageKHR))(eglGetCurrentDisplay(), EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR, (EGLClientBuffer)m_pixmap, attribs);
};
m_image = ((eglCreateImageKHR_func)(m_eglCreateImageKHR))(eglGetCurrentDisplay(), EGL_NO_CONTEXT,
EGL_NATIVE_PIXMAP_KHR,
(EGLClientBuffer)m_pixmap, attribs);
if (m_image == EGL_NO_IMAGE_KHR) { if (m_image == EGL_NO_IMAGE_KHR) {
qDebug() << "failed to create egl image"; qDebug() << "failed to create egl image";
@ -471,9 +455,8 @@ void WindowThumbnail::resolveEGLFunctions()
} }
auto *context = window()->openglContext(); auto *context = window()->openglContext();
QList<QByteArray> extensions = QByteArray(eglQueryString(display, EGL_EXTENSIONS)).split(' '); QList<QByteArray> extensions = QByteArray(eglQueryString(display, EGL_EXTENSIONS)).split(' ');
if (extensions.contains(QByteArrayLiteral("EGL_KHR_image")) || if (extensions.contains(QByteArrayLiteral("EGL_KHR_image"))
(extensions.contains(QByteArrayLiteral("EGL_KHR_image_base")) && || (extensions.contains(QByteArrayLiteral("EGL_KHR_image_base")) && extensions.contains(QByteArrayLiteral("EGL_KHR_image_pixmap")))) {
extensions.contains(QByteArrayLiteral("EGL_KHR_image_pixmap")))) {
if (context->hasExtension(QByteArrayLiteral("GL_OES_EGL_image"))) { if (context->hasExtension(QByteArrayLiteral("GL_OES_EGL_image"))) {
qDebug() << "Have EGL texture from pixmap"; qDebug() << "Have EGL texture from pixmap";
m_eglCreateImageKHR = context->getProcAddress(QByteArrayLiteral("eglCreateImageKHR")); m_eglCreateImageKHR = context->getProcAddress(QByteArrayLiteral("eglCreateImageKHR"));
@ -572,20 +555,18 @@ void WindowThumbnail::bindGLXTexture()
resetDamaged(); resetDamaged();
} }
struct FbConfigInfo struct FbConfigInfo {
{
GLXFBConfig fbConfig; GLXFBConfig fbConfig;
int textureFormat; int textureFormat;
}; };
struct GlxGlobalData struct GlxGlobalData {
{ GlxGlobalData()
GlxGlobalData() { {
xcb_connection_t * const conn = QX11Info::connection(); xcb_connection_t *const conn = QX11Info::connection();
// Fetch the render pict formats // Fetch the render pict formats
reply = xcb_render_query_pict_formats_reply(conn, reply = xcb_render_query_pict_formats_reply(conn, xcb_render_query_pict_formats_unchecked(conn), nullptr);
xcb_render_query_pict_formats_unchecked(conn), nullptr);
// Init the visual ID -> format ID hash table // Init the visual ID -> format ID hash table
for (auto screens = xcb_render_query_pict_formats_screens_iterator(reply); screens.rem; xcb_render_pictscreen_next(&screens)) { for (auto screens = xcb_render_query_pict_formats_screens_iterator(reply); screens.rem; xcb_render_pictscreen_next(&screens)) {
@ -621,7 +602,8 @@ struct GlxGlobalData
} }
} }
~GlxGlobalData() { ~GlxGlobalData()
{
qDeleteAll(visualFbConfigHash); qDeleteAll(visualFbConfigHash);
std::free(reply); std::free(reply);
} }
@ -663,31 +645,42 @@ FbConfigInfo *getConfig(xcb_visualid_t visual)
return nullptr; return nullptr;
} }
const int red_bits = qPopulationCount(direct->red_mask); const int red_bits = qPopulationCount(direct->red_mask);
const int green_bits = qPopulationCount(direct->green_mask); const int green_bits = qPopulationCount(direct->green_mask);
const int blue_bits = qPopulationCount(direct->blue_mask); const int blue_bits = qPopulationCount(direct->blue_mask);
const int alpha_bits = qPopulationCount(direct->alpha_mask); const int alpha_bits = qPopulationCount(direct->alpha_mask);
const int depth = visualDepth(visual); const int depth = visualDepth(visual);
const auto rgb_sizes = std::tie(red_bits, green_bits, blue_bits); const auto rgb_sizes = std::tie(red_bits, green_bits, blue_bits);
const int attribs[] = { const int attribs[] = {GLX_RENDER_TYPE,
GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_RGBA_BIT,
GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT | GLX_PIXMAP_BIT, GLX_DRAWABLE_TYPE,
GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR, GLX_WINDOW_BIT | GLX_PIXMAP_BIT,
GLX_X_RENDERABLE, True, GLX_X_VISUAL_TYPE,
GLX_CONFIG_CAVEAT, int(GLX_DONT_CARE), // The ARGB32 visual is marked non-conformant in Catalyst GLX_TRUE_COLOR,
GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT, int(GLX_DONT_CARE), GLX_X_RENDERABLE,
GLX_BUFFER_SIZE, red_bits + green_bits + blue_bits + alpha_bits, True,
GLX_RED_SIZE, red_bits, GLX_CONFIG_CAVEAT,
GLX_GREEN_SIZE, green_bits, int(GLX_DONT_CARE), // The ARGB32 visual is marked non-conformant in Catalyst
GLX_BLUE_SIZE, blue_bits, GLX_FRAMEBUFFER_SRGB_CAPABLE_EXT,
GLX_ALPHA_SIZE, alpha_bits, int(GLX_DONT_CARE),
GLX_STENCIL_SIZE, 0, GLX_BUFFER_SIZE,
GLX_DEPTH_SIZE, 0, red_bits + green_bits + blue_bits + alpha_bits,
0 GLX_RED_SIZE,
}; red_bits,
GLX_GREEN_SIZE,
green_bits,
GLX_BLUE_SIZE,
blue_bits,
GLX_ALPHA_SIZE,
alpha_bits,
GLX_STENCIL_SIZE,
0,
GLX_DEPTH_SIZE,
0,
0};
if (QByteArray((char *)glGetString(GL_RENDERER)).contains("llvmpipe")) { if (QByteArray((char *)glGetString(GL_RENDERER)).contains("llvmpipe")) {
return nullptr; return nullptr;
@ -710,22 +703,22 @@ FbConfigInfo *getConfig(xcb_visualid_t visual)
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
int red, green, blue; int red, green, blue;
glXGetFBConfigAttrib(dpy, configs[i], GLX_RED_SIZE, &red); glXGetFBConfigAttrib(dpy, configs[i], GLX_RED_SIZE, &red);
glXGetFBConfigAttrib(dpy, configs[i], GLX_GREEN_SIZE, &green); glXGetFBConfigAttrib(dpy, configs[i], GLX_GREEN_SIZE, &green);
glXGetFBConfigAttrib(dpy, configs[i], GLX_BLUE_SIZE, &blue); glXGetFBConfigAttrib(dpy, configs[i], GLX_BLUE_SIZE, &blue);
if (std::tie(red, green, blue) != rgb_sizes) if (std::tie(red, green, blue) != rgb_sizes)
continue; continue;
xcb_visualid_t visual; xcb_visualid_t visual;
glXGetFBConfigAttrib(dpy, configs[i], GLX_VISUAL_ID, (int *) &visual); glXGetFBConfigAttrib(dpy, configs[i], GLX_VISUAL_ID, (int *)&visual);
if (visualDepth(visual) != depth) if (visualDepth(visual) != depth)
continue; continue;
int bind_rgb, bind_rgba; int bind_rgb, bind_rgba;
glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &bind_rgba); glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGBA_EXT, &bind_rgba);
glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &bind_rgb); glXGetFBConfigAttrib(dpy, configs[i], GLX_BIND_TO_TEXTURE_RGB_EXT, &bind_rgb);
if (!bind_rgb && !bind_rgba) if (!bind_rgb && !bind_rgba)
continue; continue;
@ -737,7 +730,7 @@ FbConfigInfo *getConfig(xcb_visualid_t visual)
continue; continue;
int depth, stencil; int depth, stencil;
glXGetFBConfigAttrib(dpy, configs[i], GLX_DEPTH_SIZE, &depth); glXGetFBConfigAttrib(dpy, configs[i], GLX_DEPTH_SIZE, &depth);
glXGetFBConfigAttrib(dpy, configs[i], GLX_STENCIL_SIZE, &stencil); glXGetFBConfigAttrib(dpy, configs[i], GLX_STENCIL_SIZE, &stencil);
int texture_format; int texture_format;
@ -768,11 +761,10 @@ FbConfigInfo *getConfig(xcb_visualid_t visual)
const FBConfig &candidate = candidates.front(); const FBConfig &candidate = candidates.front();
info = new FbConfigInfo; info = new FbConfigInfo;
info->fbConfig = candidate.config; info->fbConfig = candidate.config;
info->textureFormat = candidate.format; info->textureFormat = candidate.format;
} }
return info; return info;
} }
@ -801,12 +793,7 @@ bool WindowThumbnail::loadGLXTexture()
glGenTextures(1, &m_texture); glGenTextures(1, &m_texture);
const int attrs[] = { const int attrs[] = {GLX_TEXTURE_FORMAT_EXT, info->textureFormat, GLX_MIPMAP_TEXTURE_EXT, false, GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT, XCB_NONE};
GLX_TEXTURE_FORMAT_EXT, info->textureFormat,
GLX_MIPMAP_TEXTURE_EXT, false,
GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
XCB_NONE
};
m_glxPixmap = glXCreatePixmap(QX11Info::display(), info->fbConfig, m_pixmap, attrs); m_glxPixmap = glXCreatePixmap(QX11Info::display(), info->fbConfig, m_pixmap, attrs);
@ -891,8 +878,6 @@ bool WindowThumbnail::startRedirecting()
#endif #endif
} }
void WindowThumbnail::setThumbnailAvailable(bool thumbnailAvailable) void WindowThumbnail::setThumbnailAvailable(bool thumbnailAvailable)
{ {
if (m_thumbnailAvailable != thumbnailAvailable) { if (m_thumbnailAvailable != thumbnailAvailable) {

View File

@ -12,9 +12,9 @@
// Qt // Qt
#include <QAbstractNativeEventFilter> #include <QAbstractNativeEventFilter>
#include <QSGSimpleTextureNode>
#include <QQuickItem>
#include <QPointer> #include <QPointer>
#include <QQuickItem>
#include <QSGSimpleTextureNode>
#include <QWindow> #include <QWindow>
// xcb // xcb
#if HAVE_XCB_COMPOSITE #if HAVE_XCB_COMPOSITE
@ -32,7 +32,6 @@ class KWindowInfo;
namespace Plasma namespace Plasma
{ {
class WindowTextureNode; class WindowTextureNode;
/** /**
@ -117,7 +116,7 @@ private:
xcb_damage_damage_t m_damage; xcb_damage_damage_t m_damage;
xcb_pixmap_t m_pixmap; xcb_pixmap_t m_pixmap;
/*The following must *only* be used from the render thread*/ /*The following must *only* be used from the render thread*/
uint m_texture; uint m_texture;
#if HAVE_GLX #if HAVE_GLX
bool windowToTextureGLX(WindowTextureNode *textureNode); bool windowToTextureGLX(WindowTextureNode *textureNode);
@ -152,6 +151,7 @@ public:
WindowTextureNode(); WindowTextureNode();
virtual ~WindowTextureNode(); virtual ~WindowTextureNode();
void reset(QSGTexture *texture); void reset(QSGTexture *texture);
private: private:
QScopedPointer<QSGTexture> m_texture; QScopedPointer<QSGTexture> m_texture;
}; };

View File

@ -6,8 +6,8 @@
#include "plasmacomponentsplugin.h" #include "plasmacomponentsplugin.h"
#include <QQmlEngine>
#include <QQmlContext> #include <QQmlContext>
#include <QQmlEngine>
#include <QQuickItem> #include <QQuickItem>
#include "qrangemodel.h" #include "qrangemodel.h"
@ -39,7 +39,7 @@ EngineBookKeeping *EngineBookKeeping::self()
QQmlEngine *EngineBookKeeping::engine() const QQmlEngine *EngineBookKeeping::engine() const
{ {
//for components creation, any engine will do, as long is valid // for components creation, any engine will do, as long is valid
if (m_engines.isEmpty()) { if (m_engines.isEmpty()) {
qWarning() << "No engines found, this should never happen"; qWarning() << "No engines found, this should never happen";
return nullptr; return nullptr;
@ -50,8 +50,7 @@ QQmlEngine *EngineBookKeeping::engine() const
void EngineBookKeeping::insertEngine(QQmlEngine *engine) void EngineBookKeeping::insertEngine(QQmlEngine *engine)
{ {
connect(engine, &QObject::destroyed, connect(engine, &QObject::destroyed, this, &EngineBookKeeping::engineDestroyed);
this, &EngineBookKeeping::engineDestroyed);
m_engines.insert(engine); m_engines.insert(engine);
} }
@ -81,4 +80,3 @@ void PlasmaComponentsPlugin::registerTypes(const char *uri)
} }
#include "moc_plasmacomponentsplugin.cpp" #include "moc_plasmacomponentsplugin.cpp"

View File

@ -29,7 +29,7 @@ private Q_SLOTS:
void engineDestroyed(QObject *deleted); void engineDestroyed(QObject *deleted);
private: private:
QSet <QQmlEngine *> m_engines; QSet<QQmlEngine *> m_engines;
}; };
class PlasmaComponentsPlugin : public QQmlExtensionPlugin class PlasmaComponentsPlugin : public QQmlExtensionPlugin

View File

@ -8,8 +8,8 @@
#include <QApplication> #include <QApplication>
#include <QDebug> #include <QDebug>
#include <QQuickWindow>
#include <QQuickItem> #include <QQuickItem>
#include <QQuickWindow>
#include <QScreen> #include <QScreen>
#include <QTimer> #include <QTimer>
#include <QVersionNumber> #include <QVersionNumber>
@ -18,10 +18,10 @@
#include "plasmacomponentsplugin.h" #include "plasmacomponentsplugin.h"
QMenuProxy::QMenuProxy(QObject *parent) QMenuProxy::QMenuProxy(QObject *parent)
: QObject(parent), : QObject(parent)
m_menu(nullptr), , m_menu(nullptr)
m_status(DialogStatus::Closed), , m_status(DialogStatus::Closed)
m_placement(Plasma::Types::LeftPosedTopAlignedPopup) , m_placement(Plasma::Types::LeftPosedTopAlignedPopup)
{ {
if (qobject_cast<QApplication *>(QCoreApplication::instance())) { if (qobject_cast<QApplication *>(QCoreApplication::instance())) {
m_menu = new QMenu(nullptr); m_menu = new QMenu(nullptr);
@ -32,9 +32,9 @@ QMenuProxy::QMenuProxy(QObject *parent)
KAcceleratorManager::manage(m_menu); KAcceleratorManager::manage(m_menu);
connect(m_menu, &QMenu::triggered, this, &QMenuProxy::itemTriggered); connect(m_menu, &QMenu::triggered, this, &QMenuProxy::itemTriggered);
connect(m_menu, &QMenu::aboutToHide, this, [ = ]() { connect(m_menu, &QMenu::aboutToHide, this, [=]() {
m_status = DialogStatus::Closed; m_status = DialogStatus::Closed;
Q_EMIT statusChanged(); Q_EMIT statusChanged();
}); });
} }
} }
@ -79,13 +79,13 @@ void QMenuProxy::setVisualParent(QObject *parent)
return; return;
} }
//if the old parent was a QAction, disconnect the menu from it // if the old parent was a QAction, disconnect the menu from it
QAction *action = qobject_cast<QAction *>(m_visualParent.data()); QAction *action = qobject_cast<QAction *>(m_visualParent.data());
if (action) { if (action) {
action->setMenu(nullptr); action->setMenu(nullptr);
m_menu->clear(); m_menu->clear();
} }
//if parent is a QAction, become a submenu // if parent is a QAction, become a submenu
action = qobject_cast<QAction *>(parent); action = qobject_cast<QAction *>(parent);
if (action) { if (action) {
action->setMenu(m_menu); action->setMenu(m_menu);
@ -179,7 +179,7 @@ bool QMenuProxy::event(QEvent *event)
case QEvent::ChildAdded: { case QEvent::ChildAdded: {
QChildEvent *ce = static_cast<QChildEvent *>(event); QChildEvent *ce = static_cast<QChildEvent *>(event);
QMenuItem *mi = qobject_cast<QMenuItem *>(ce->child()); QMenuItem *mi = qobject_cast<QMenuItem *>(ce->child());
//FIXME: linear complexity here // FIXME: linear complexity here
if (mi && !m_items.contains(mi)) { if (mi && !m_items.contains(mi)) {
if (mi->separator()) { if (mi->separator()) {
m_menu->addSection(mi->text()); m_menu->addSection(mi->text());
@ -195,7 +195,7 @@ bool QMenuProxy::event(QEvent *event)
QChildEvent *ce = static_cast<QChildEvent *>(event); QChildEvent *ce = static_cast<QChildEvent *>(event);
QMenuItem *mi = qobject_cast<QMenuItem *>(ce->child()); QMenuItem *mi = qobject_cast<QMenuItem *>(ce->child());
//FIXME: linear complexity here // FIXME: linear complexity here
if (mi) { if (mi) {
m_menu->removeAction(mi->action()); m_menu->removeAction(mi->action());
m_items.removeAll(mi); m_items.removeAll(mi);
@ -275,7 +275,6 @@ void QMenuProxy::itemTriggered(QAction *action)
Q_EMIT triggeredIndex(i); Q_EMIT triggeredIndex(i);
break; break;
} }
} }
} }
@ -293,7 +292,7 @@ void QMenuProxy::rebuildMenu()
} else { } else {
m_menu->addAction(item->action()); m_menu->addAction(item->action());
if (item->action()->menu()) { if (item->action()->menu()) {
//This ensures existence of the QWindow // This ensures existence of the QWindow
m_menu->winId(); m_menu->winId();
item->action()->menu()->winId(); item->action()->menu()->winId();
item->action()->menu()->windowHandle()->setTransientParent(m_menu->windowHandle()); item->action()->menu()->windowHandle()->setTransientParent(m_menu->windowHandle());
@ -377,48 +376,48 @@ void QMenuProxy::openRelative()
} }
}; };
switch(m_placement) { switch (m_placement) {
case Types::TopPosedLeftAlignedPopup: { case Types::TopPosedLeftAlignedPopup: {
pos = parentItem->mapToScene(QPointF(0, -m_menu->height())); pos = parentItem->mapToScene(QPointF(0, -m_menu->height()));
boundaryCorrection(-m_menu->width() + parentItem->width(), m_menu->height() + parentItem->height()); boundaryCorrection(-m_menu->width() + parentItem->width(), m_menu->height() + parentItem->height());
break; break;
} }
case Types::LeftPosedTopAlignedPopup: { case Types::LeftPosedTopAlignedPopup: {
pos = parentItem->mapToScene(QPointF(-m_menu->width(), 0)); pos = parentItem->mapToScene(QPointF(-m_menu->width(), 0));
boundaryCorrection(m_menu->width() + parentItem->width(), -m_menu->height() + parentItem->height()); boundaryCorrection(m_menu->width() + parentItem->width(), -m_menu->height() + parentItem->height());
break; break;
} }
case Types::TopPosedRightAlignedPopup: case Types::TopPosedRightAlignedPopup:
pos = parentItem->mapToScene(QPointF(parentItem->width() - m_menu->width(), -m_menu->height())); pos = parentItem->mapToScene(QPointF(parentItem->width() - m_menu->width(), -m_menu->height()));
boundaryCorrection(m_menu->width() - parentItem->width(), m_menu->height() + parentItem->height()); boundaryCorrection(m_menu->width() - parentItem->width(), m_menu->height() + parentItem->height());
break; break;
case Types::RightPosedTopAlignedPopup: { case Types::RightPosedTopAlignedPopup: {
pos = parentItem->mapToScene(QPointF(parentItem->width(), 0)); pos = parentItem->mapToScene(QPointF(parentItem->width(), 0));
boundaryCorrection(-m_menu->width() - parentItem->width(), -m_menu->height() + parentItem->height()); boundaryCorrection(-m_menu->width() - parentItem->width(), -m_menu->height() + parentItem->height());
break; break;
} }
case Types::LeftPosedBottomAlignedPopup: case Types::LeftPosedBottomAlignedPopup:
pos = parentItem->mapToScene(QPointF(-m_menu->width(), -m_menu->height() + parentItem->height())); pos = parentItem->mapToScene(QPointF(-m_menu->width(), -m_menu->height() + parentItem->height()));
boundaryCorrection(m_menu->width() + parentItem->width(), m_menu->height() - parentItem->height()); boundaryCorrection(m_menu->width() + parentItem->width(), m_menu->height() - parentItem->height());
break; break;
case Types::BottomPosedLeftAlignedPopup: { case Types::BottomPosedLeftAlignedPopup: {
pos = parentItem->mapToScene(QPointF(0, parentItem->height())); pos = parentItem->mapToScene(QPointF(0, parentItem->height()));
boundaryCorrection(-m_menu->width() + parentItem->width(), -m_menu->height() - parentItem->height()); boundaryCorrection(-m_menu->width() + parentItem->width(), -m_menu->height() - parentItem->height());
break; break;
} }
case Types::BottomPosedRightAlignedPopup: { case Types::BottomPosedRightAlignedPopup: {
pos = parentItem->mapToScene(QPointF(parentItem->width() - m_menu->width(), parentItem->height())); pos = parentItem->mapToScene(QPointF(parentItem->width() - m_menu->width(), parentItem->height()));
boundaryCorrection(m_menu->width() - parentItem->width(), -m_menu->height() - parentItem->height()); boundaryCorrection(m_menu->width() - parentItem->width(), -m_menu->height() - parentItem->height());
break; break;
} }
case Types::RightPosedBottomAlignedPopup: { case Types::RightPosedBottomAlignedPopup: {
pos = parentItem->mapToScene(QPointF(parentItem->width(), -m_menu->height() + parentItem->height())); pos = parentItem->mapToScene(QPointF(parentItem->width(), -m_menu->height() + parentItem->height()));
boundaryCorrection(-m_menu->width() - parentItem->width(), m_menu->height() - parentItem->height()); boundaryCorrection(-m_menu->width() - parentItem->width(), m_menu->height() - parentItem->height());
break; break;
} }
default: default:
open(); open();
return; return;
} }
openInternal(pos.toPoint()); openInternal(pos.toPoint());
@ -429,7 +428,7 @@ void QMenuProxy::openInternal(QPoint pos)
QQuickItem *parentItem = this->parentItem(); QQuickItem *parentItem = this->parentItem();
if (parentItem && parentItem->window()) { if (parentItem && parentItem->window()) {
//create the QWindow // create the QWindow
m_menu->winId(); m_menu->winId();
m_menu->windowHandle()->setTransientParent(parentItem->window()); m_menu->windowHandle()->setTransientParent(parentItem->window());
@ -441,14 +440,14 @@ void QMenuProxy::openInternal(QPoint pos)
} }
}; };
//pre 5.8.0 QQuickWindow code is "item->grabMouse(); sendEvent(item, mouseEvent)" // pre 5.8.0 QQuickWindow code is "item->grabMouse(); sendEvent(item, mouseEvent)"
//post 5.8.0 QQuickWindow code is sendEvent(item, mouseEvent); item->grabMouse() // post 5.8.0 QQuickWindow code is sendEvent(item, mouseEvent); item->grabMouse()
if (QVersionNumber::fromString(QString::fromLatin1(qVersion())) > QVersionNumber(5, 8, 0)) { if (QVersionNumber::fromString(QString::fromLatin1(qVersion())) > QVersionNumber(5, 8, 0)) {
QTimer::singleShot(0, this, ungrabMouseHack); QTimer::singleShot(0, this, ungrabMouseHack);
} else { } else {
ungrabMouseHack(); ungrabMouseHack();
} }
//end workaround // end workaround
} }
m_menu->popup(pos); m_menu->popup(pos);
@ -469,5 +468,3 @@ void QMenuProxy::close()
{ {
m_menu->hide(); m_menu->hide();
} }

View File

@ -7,13 +7,13 @@
#ifndef QMENU_PROXY_H #ifndef QMENU_PROXY_H
#define QMENU_PROXY_H #define QMENU_PROXY_H
#include <QObject>
#include <QMenu>
#include <QPointer>
#include <QQmlListProperty>
#include "qmenuitem.h"
#include "enums.h" #include "enums.h"
#include "plasma.h" #include "plasma.h"
#include "qmenuitem.h"
#include <QMenu>
#include <QObject>
#include <QPointer>
#include <QQmlListProperty>
class QDeclarativeItem; class QDeclarativeItem;
@ -66,7 +66,8 @@ class QMenuProxy : public QObject
Q_PROPERTY(QWindow *transientParent READ transientParent WRITE setTransientParent NOTIFY transientParentChanged) Q_PROPERTY(QWindow *transientParent READ transientParent WRITE setTransientParent NOTIFY transientParentChanged)
/** /**
* the visualParent is used to position the menu. it can be an item on the scene, like a button (that will open the menu on clicked) or another menuitem (in this case this will be a submenu) * the visualParent is used to position the menu. it can be an item on the scene, like a button (that will open the menu on clicked) or another menuitem (in
* this case this will be a submenu)
*/ */
Q_PROPERTY(QObject *visualParent READ visualParent WRITE setVisualParent NOTIFY visualParentChanged()) Q_PROPERTY(QObject *visualParent READ visualParent WRITE setVisualParent NOTIFY visualParentChanged())
Q_PROPERTY(DialogStatus::Status status READ status NOTIFY statusChanged) Q_PROPERTY(DialogStatus::Status status READ status NOTIFY statusChanged)
@ -181,5 +182,4 @@ private:
Plasma::Types::PopupPlacement m_placement; Plasma::Types::PopupPlacement m_placement;
}; };
#endif //QMENU_PROXY_H #endif // QMENU_PROXY_H

View File

@ -8,9 +8,9 @@
#include "qmenuitem.h" #include "qmenuitem.h"
QMenuItem::QMenuItem(QQuickItem *parent) QMenuItem::QMenuItem(QQuickItem *parent)
: QQuickItem(parent), : QQuickItem(parent)
m_action(nullptr), , m_action(nullptr)
m_section(false) , m_section(false)
{ {
setAction(new QAction(this)); setAction(new QAction(this));
} }
@ -141,6 +141,3 @@ void QMenuItem::updateAction()
m_action->setVisible(isVisible()); m_action->setVisible(isVisible());
m_action->setEnabled(isEnabled()); m_action->setEnabled(isEnabled());
} }

View File

@ -73,4 +73,3 @@ private:
}; };
#endif // QMENUITEM_H #endif // QMENUITEM_H

View File

@ -33,7 +33,6 @@
namespace Plasma namespace Plasma
{ {
QRangeModelPrivate::QRangeModelPrivate(QRangeModel *qq) QRangeModelPrivate::QRangeModelPrivate(QRangeModel *qq)
: q_ptr(qq) : q_ptr(qq)
{ {
@ -157,7 +156,8 @@ void QRangeModelPrivate::emitValueAndPositionIfChanged(const qreal oldValue, con
*/ */
QRangeModel::QRangeModel(QObject *parent) QRangeModel::QRangeModel(QObject *parent)
: QObject(parent), d_ptr(new QRangeModelPrivate(this)) : QObject(parent)
, d_ptr(new QRangeModelPrivate(this))
{ {
Q_D(QRangeModel); Q_D(QRangeModel);
d->init(); d->init();
@ -169,7 +169,8 @@ QRangeModel::QRangeModel(QObject *parent)
*/ */
QRangeModel::QRangeModel(QRangeModelPrivate &dd, QObject *parent) QRangeModel::QRangeModel(QRangeModelPrivate &dd, QObject *parent)
: QObject(parent), d_ptr(&dd) : QObject(parent)
, d_ptr(&dd)
{ {
Q_D(QRangeModel); Q_D(QRangeModel);
d->init(); d->init();
@ -518,4 +519,3 @@ void QRangeModel::toMaximum()
} }
} // Plasma namespace } // Plasma namespace

View File

@ -13,7 +13,6 @@
namespace Plasma namespace Plasma
{ {
class QRangeModelPrivate; class QRangeModelPrivate;
class QRangeModel : public QObject class QRangeModel : public QObject
@ -86,7 +85,6 @@ protected:
private: private:
Q_DISABLE_COPY(QRangeModel) Q_DISABLE_COPY(QRangeModel)
Q_DECLARE_PRIVATE(QRangeModel) Q_DECLARE_PRIVATE(QRangeModel)
}; };
} // Plasma namespace } // Plasma namespace

View File

@ -25,7 +25,6 @@
namespace Plasma namespace Plasma
{ {
class QRangeModelPrivate class QRangeModelPrivate
{ {
Q_DECLARE_PUBLIC(QRangeModel) Q_DECLARE_PUBLIC(QRangeModel)

View File

@ -30,4 +30,3 @@ QImage AppBackgroundProvider::requestImage(const QString &id, QSize *size, const
Q_UNUSED(requestedSize) Q_UNUSED(requestedSize)
return QImage(m_theme->backgroundPath(id % QStringLiteral(".png"))); return QImage(m_theme->backgroundPath(id % QStringLiteral(".png")));
} }

View File

@ -14,18 +14,18 @@ namespace Plasma
class Theme; class Theme;
} }
//TODO: should be possible to remove without significant breakages as is just an image provider // TODO: should be possible to remove without significant breakages as is just an image provider
/** /**
* image provider for textures used for applications * image provider for textures used for applications
* @deprecated don't use it * @deprecated don't use it
*/ */
class AppBackgroundProvider : public QQuickImageProvider class AppBackgroundProvider : public QQuickImageProvider
{ {
public: public:
AppBackgroundProvider(); AppBackgroundProvider();
~AppBackgroundProvider() override; ~AppBackgroundProvider() override;
QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override; QImage requestImage(const QString &id, QSize *size, const QSize &requestedSize) override;
private: private:
Plasma::Theme *m_theme; Plasma::Theme *m_theme;
}; };

View File

@ -61,7 +61,6 @@ QString FallbackComponent::filePath(const QString &key)
if (tmpPath.isAbsolute()) { if (tmpPath.isAbsolute()) {
resolved = m_basePath + path + key; resolved = m_basePath + path + key;
} else { } else {
resolved = QStandardPaths::locate(QStandardPaths::GenericDataLocation, m_basePath + QLatin1Char('/') + path + key); resolved = QStandardPaths::locate(QStandardPaths::GenericDataLocation, m_basePath + QLatin1Char('/') + path + key);
} }
@ -73,4 +72,3 @@ QString FallbackComponent::filePath(const QString &key)
return resolved; return resolved;
} }

View File

@ -7,8 +7,8 @@
#ifndef FALLBACKCOMPONENT_H #ifndef FALLBACKCOMPONENT_H
#define FALLBACKCOMPONENT_H #define FALLBACKCOMPONENT_H
#include <QObject>
#include <QCache> #include <QCache>
#include <QObject>
#include <QStringList> #include <QStringList>
/** /**
@ -38,13 +38,13 @@ public:
explicit FallbackComponent(QObject *parent = nullptr); explicit FallbackComponent(QObject *parent = nullptr);
/** /**
* This method must be called after the basePath and the candidates property * This method must be called after the basePath and the candidates property
* This method resolves a file path based on the base path and the candidates. * This method resolves a file path based on the base path and the candidates.
* it searches for a file named key under basepath/candidate/key, and returns * it searches for a file named key under basepath/candidate/key, and returns
* the path constructed with the first candidate that matches, if any. * the path constructed with the first candidate that matches, if any.
* *
* @param key the name of the file to search for * @param key the name of the file to search for
**/ **/
Q_INVOKABLE QString filePath(const QString &key = QString()); Q_INVOKABLE QString filePath(const QString &key = QString());
QString basePath() const; QString basePath() const;

View File

@ -9,8 +9,8 @@
#include "appbackgroundprovider_p.h" #include "appbackgroundprovider_p.h"
#include "fallbackcomponent.h" #include "fallbackcomponent.h"
#include <QtQml>
#include <QQmlEngine> #include <QQmlEngine>
#include <QtQml>
// #include <KSharedConfig> // #include <KSharedConfig>
// #include <KConfigGroup> // #include <KConfigGroup>
@ -26,5 +26,3 @@ void PlasmaExtraComponentsPlugin::registerTypes(const char *uri)
Q_ASSERT(uri == QByteArray("org.kde.plasma.extras")); Q_ASSERT(uri == QByteArray("org.kde.plasma.extras"));
qmlRegisterType<FallbackComponent>(uri, 2, 0, "FallbackComponent"); qmlRegisterType<FallbackComponent>(uri, 2, 0, "FallbackComponent");
} }

View File

@ -9,29 +9,23 @@
#include "utils/d_ptr_implementation.h" #include "utils/d_ptr_implementation.h"
#include <QDebug>
#include <QCoreApplication> #include <QCoreApplication>
#include <QDebug>
Application::Private::Private(Application *parent) Application::Private::Private(Application *parent)
: running(false) : running(false)
, q(parent) , q(parent)
{ {
connect( connect(&process, &QProcess::stateChanged, this, &Private::stateChanged);
&process, &QProcess::stateChanged, connect(&process, SIGNAL(error(QProcess::ProcessError)), this, SLOT(errorFound(QProcess::ProcessError)));
this, &Private::stateChanged
);
connect(
&process, SIGNAL(error(QProcess::ProcessError)),
this, SLOT(errorFound(QProcess::ProcessError))
);
process.setProcessChannelMode(QProcess::MergedChannels); process.setProcessChannelMode(QProcess::MergedChannels);
} }
void Application::Private::stateChanged(QProcess::ProcessState newState) void Application::Private::stateChanged(QProcess::ProcessState newState)
{ {
Q_UNUSED(newState) Q_UNUSED(newState)
//running = (newState != QProcess::NotRunning); // running = (newState != QProcess::NotRunning);
//q->runningChanged(running); // q->runningChanged(running);
} }
void Application::Private::errorFound(QProcess::ProcessError err) void Application::Private::errorFound(QProcess::ProcessError err)
@ -41,7 +35,8 @@ void Application::Private::errorFound(QProcess::ProcessError err)
} }
Application::Application(QObject *parent) Application::Application(QObject *parent)
: QObject(parent), d(this) : QObject(parent)
, d(this)
{ {
} }
@ -107,4 +102,3 @@ void Application::terminate()
{ {
d->process.terminate(); d->process.terminate();
} }

View File

@ -23,7 +23,7 @@
* } * }
* @endcode * @endcode
*/ */
class Application: public QObject class Application : public QObject
{ {
Q_OBJECT Q_OBJECT
@ -62,4 +62,3 @@ private:
}; };
#endif /* APPLICATION_H */ #endif /* APPLICATION_H */

View File

@ -11,7 +11,7 @@
#include <QProcess> #include <QProcess>
class Application::Private: public QObject class Application::Private : public QObject
{ {
Q_OBJECT Q_OBJECT
public: public:
@ -30,4 +30,3 @@ private:
}; };
#endif /* APPLICATION_P_H */ #endif /* APPLICATION_P_H */

View File

@ -21,7 +21,6 @@
class IconDialog::Private class IconDialog::Private
{ {
public: public:
utils::SharedSingleton<KIconDialog> dialog; utils::SharedSingleton<KIconDialog> dialog;
}; };
@ -56,4 +55,3 @@ void IconDialog::closeDialog()
IconDialog::~IconDialog() IconDialog::~IconDialog()
{ {
} }

View File

@ -28,7 +28,7 @@
* icon = iconDialog.openDialog() * icon = iconDialog.openDialog()
* @endcode * @endcode
*/ */
class IconDialog: public QObject class IconDialog : public QObject
{ {
Q_OBJECT Q_OBJECT
@ -44,4 +44,3 @@ private:
}; };
#endif /* ICONDIALOG_H */ #endif /* ICONDIALOG_H */

View File

@ -4,14 +4,14 @@
SPDX-License-Identifier: GPL-2.0-or-later SPDX-License-Identifier: GPL-2.0-or-later
*/ */
#include <QtQml>
#include <QQmlExtensionPlugin>
#include <QDebug> #include <QDebug>
#include <QQmlExtensionPlugin>
#include <QtQml>
#include "application.h" #include "application.h"
#include "icondialog.h" #include "icondialog.h"
class PlatformComponentsPlugin: public QQmlExtensionPlugin class PlatformComponentsPlugin : public QQmlExtensionPlugin
{ {
Q_OBJECT Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
@ -22,14 +22,13 @@ public:
{ {
} }
void registerTypes(const char *uri) override { void registerTypes(const char *uri) override
{
Q_ASSERT(QLatin1String(uri) == QLatin1String("org.kde.plasma.platformcomponents")); Q_ASSERT(QLatin1String(uri) == QLatin1String("org.kde.plasma.platformcomponents"));
qmlRegisterType<Application> (uri, 2, 0, "Application"); qmlRegisterType<Application>(uri, 2, 0, "Application");
qmlRegisterType<IconDialog> (uri, 2, 0, "IconDialog"); qmlRegisterType<IconDialog>(uri, 2, 0, "IconDialog");
} }
}; };
#include "platformextensionplugin.moc" #include "platformextensionplugin.moc"

View File

@ -11,8 +11,7 @@
namespace utils namespace utils
{ {
template<typename T>
template <typename T>
class d_ptr class d_ptr
{ {
private: private:
@ -21,19 +20,19 @@ private:
public: public:
d_ptr(); d_ptr();
template <typename ...Args> template<typename... Args>
d_ptr(Args &&...); d_ptr(Args &&...);
~d_ptr(); ~d_ptr();
T *operator->() const; T *operator->() const;
}; };
#define D_PTR \ #define D_PTR \
class Private; \ class Private; \
friend class Private; \ friend class Private; \
const ::utils::d_ptr<Private> d \ const ::utils::d_ptr<Private> d
} // namespace utils } // namespace utils
#endif #endif

View File

@ -11,20 +11,20 @@
namespace utils namespace utils
{ {
template<typename T>
template <typename T> d_ptr<T>::d_ptr()
d_ptr<T>::d_ptr() : d(new T()) : d(new T())
{ {
} }
template <typename T> template<typename T>
template <typename ...Args> template<typename... Args>
d_ptr<T>::d_ptr(Args &&... args) d_ptr<T>::d_ptr(Args &&...args)
: d(new T(std::forward<Args>(args)...)) : d(new T(std::forward<Args>(args)...))
{ {
} }
template <typename T> template<typename T>
d_ptr<T>::~d_ptr() d_ptr<T>::~d_ptr()
{ {
} }
@ -38,4 +38,3 @@ T *d_ptr<T>::operator->() const
} // namespace utils } // namespace utils
#endif #endif

View File

@ -11,8 +11,7 @@
namespace utils namespace utils
{ {
template<typename Target>
template <typename Target>
class SharedSingleton class SharedSingleton
{ {
public: public:
@ -39,10 +38,9 @@ private:
static std::weak_ptr<Target> s_instance; static std::weak_ptr<Target> s_instance;
}; };
template <typename Target> template<typename Target>
std::weak_ptr<Target> SharedSingleton<Target>::s_instance; std::weak_ptr<Target> SharedSingleton<Target>::s_instance;
} // namespace utils } // namespace utils
#endif /* SHARED_SINGLETON_P_H */ #endif /* SHARED_SINGLETON_P_H */

View File

@ -15,48 +15,47 @@
#include <cmath> #include <cmath>
#include <limits> #include <limits>
#include <QAbstractButton>
#include <QFile> #include <QFile>
#include <QList> #include <QList>
#include <QAbstractButton>
#include <QMessageBox> #include <QMessageBox>
#include <QMetaEnum> #include <QMetaEnum>
#include <KActionCollection> #include <KActionCollection>
#include <KAuthorized> #include <KAuthorized>
#include <KColorScheme> #include <KColorScheme>
#include <KConfigLoader>
#include <KDesktopFile> #include <KDesktopFile>
#include <QDebug>
#include <KGlobalAccel> #include <KGlobalAccel>
#include <KLocalizedString> #include <KLocalizedString>
#include <KService> #include <KService>
#include <KConfigLoader>
#include <KWindowSystem> #include <KWindowSystem>
#include <QDebug>
#include "containment.h" #include "containment.h"
#include "corona.h" #include "corona.h"
#include "package.h" #include "package.h"
#include "plasma.h" #include "plasma.h"
#include "scripting/appletscript.h"
#include "pluginloader.h" #include "pluginloader.h"
#include "scripting/appletscript.h"
#include "debug_p.h"
#include "private/associatedapplicationmanager_p.h" #include "private/associatedapplicationmanager_p.h"
#include "private/containment_p.h" #include "private/containment_p.h"
#include "private/package_p.h" #include "private/package_p.h"
#include "debug_p.h"
namespace Plasma namespace Plasma
{ {
static KPluginMetaData appletMetadataForDirectory(const QString &path) static KPluginMetaData appletMetadataForDirectory(const QString &path)
{ {
return QFile::exists(path + QLatin1String("/metadata.json")) return QFile::exists(path + QLatin1String("/metadata.json"))
? KPluginMetaData(path + QLatin1String("/metadata.json")) ? KPluginMetaData(path + QLatin1String("/metadata.json"))
: KPluginMetaData::fromDesktopFile(path + QLatin1String("/metadata.desktop"), { QStringLiteral("plasma-applet.desktop") }); : KPluginMetaData::fromDesktopFile(path + QLatin1String("/metadata.desktop"), {QStringLiteral("plasma-applet.desktop")});
} }
Applet::Applet(const KPluginMetaData &info, QObject *parent, uint appletId) Applet::Applet(const KPluginMetaData &info, QObject *parent, uint appletId)
: QObject(parent), : QObject(parent)
d(new AppletPrivate(info, appletId, this)) , d(new AppletPrivate(info, appletId, this))
{ {
qCDebug(LOG_PLASMA) << " From KPluginMetaData, valid? " << info.isValid(); qCDebug(LOG_PLASMA) << " From KPluginMetaData, valid? " << info.isValid();
// WARNING: do not access config() OR globalConfig() in this method! // WARNING: do not access config() OR globalConfig() in this method!
@ -66,13 +65,13 @@ Applet::Applet(const KPluginMetaData &info, QObject *parent, uint appletId)
} }
Applet::Applet(const KPluginInfo &info, QObject *parent, uint appletId) Applet::Applet(const KPluginInfo &info, QObject *parent, uint appletId)
: Applet(info.toMetaData(), parent, appletId) : Applet(info.toMetaData(), parent, appletId)
{ {
} }
Applet::Applet(QObject *parent, const QString &serviceID, uint appletId) Applet::Applet(QObject *parent, const QString &serviceID, uint appletId)
: QObject(parent), : QObject(parent)
d(new AppletPrivate(KPluginMetaData(serviceID), appletId, this)) , d(new AppletPrivate(KPluginMetaData(serviceID), appletId, this))
{ {
// WARNING: do not access config() OR globalConfig() in this method! // WARNING: do not access config() OR globalConfig() in this method!
// that requires a scene, which is not available at this point // that requires a scene, which is not available at this point
@ -81,8 +80,8 @@ Applet::Applet(QObject *parent, const QString &serviceID, uint appletId)
} }
Applet::Applet(QObject *parentObject, const QVariantList &args) Applet::Applet(QObject *parentObject, const QVariantList &args)
: QObject(nullptr), : QObject(nullptr)
d(new AppletPrivate(KPluginMetaData(), args.count() > 2 ? args[2].toInt() : 0, this)) , d(new AppletPrivate(KPluginMetaData(), args.count() > 2 ? args[2].toInt() : 0, this))
{ {
setParent(parentObject); setParent(parentObject);
if (!args.isEmpty()) { if (!args.isEmpty()) {
@ -113,8 +112,8 @@ Applet::Applet(QObject *parentObject, const QVariantList &args)
} }
Applet::Applet(const QString &packagePath, uint appletId) Applet::Applet(const QString &packagePath, uint appletId)
: QObject(nullptr), : QObject(nullptr)
d(new AppletPrivate(appletMetadataForDirectory(packagePath), appletId, this)) , d(new AppletPrivate(appletMetadataForDirectory(packagePath), appletId, this))
{ {
d->init(packagePath); d->init(packagePath);
d->setupPackage(); d->setupPackage();
@ -125,7 +124,7 @@ Applet::~Applet()
if (d->transient) { if (d->transient) {
d->resetConfigurationObject(); d->resetConfigurationObject();
} }
//let people know that i will die // let people know that i will die
Q_EMIT appletDeleted(this); Q_EMIT appletDeleted(this);
// ConfigLoader is deleted when AppletPrivate closes not Applet // ConfigLoader is deleted when AppletPrivate closes not Applet
@ -137,7 +136,7 @@ Applet::~Applet()
void Applet::init() void Applet::init()
{ {
//Don't implement anything here, it will be overridden by subclasses // Don't implement anything here, it will be overridden by subclasses
} }
uint Applet::id() const uint Applet::id() const
@ -156,7 +155,7 @@ void Applet::save(KConfigGroup &g) const
group = *d->mainConfigGroup(); group = *d->mainConfigGroup();
} }
//qCDebug(LOG_PLASMA) << "saving" << pluginName() << "to" << group.name(); // qCDebug(LOG_PLASMA) << "saving" << pluginName() << "to" << group.name();
// we call the dptr member directly for locked since isImmutable() // we call the dptr member directly for locked since isImmutable()
// also checks kiosk and parent containers // also checks kiosk and parent containers
group.writeEntry("immutability", (int)d->immutability); group.writeEntry("immutability", (int)d->immutability);
@ -180,7 +179,6 @@ void Applet::save(KConfigGroup &g) const
void Applet::restore(KConfigGroup &group) void Applet::restore(KConfigGroup &group)
{ {
setImmutability((Types::ImmutabilityType)group.readEntry("immutability", (int)Types::Mutable)); setImmutability((Types::ImmutabilityType)group.readEntry("immutability", (int)Types::Mutable));
KConfigGroup shortcutConfig(&group, "Shortcuts"); KConfigGroup shortcutConfig(&group, "Shortcuts");
@ -199,12 +197,11 @@ void Applet::restore(KConfigGroup &group)
} }
// local shortcut, if any // local shortcut, if any
//TODO: implement; the shortcut will need to be registered with the containment // TODO: implement; the shortcut will need to be registered with the containment
/* /*
#include "accessmanager.h" #include "accessmanager.h"
#include "authorizationmanager.h"
#include "private/plasmoidservice_p.h" #include "private/plasmoidservice_p.h"
#include "authorizationmanager.h"
#include "authorizationmanager.h"
shortcutText = shortcutConfig.readEntryUntranslated("local", QString()); shortcutText = shortcutConfig.readEntryUntranslated("local", QString());
if (!shortcutText.isEmpty()) { if (!shortcutText.isEmpty()) {
//TODO: implement; the shortcut //TODO: implement; the shortcut
@ -287,11 +284,11 @@ KConfigGroup Applet::globalConfig() const
void Applet::destroy() void Applet::destroy()
{ {
if (immutability() != Types::Mutable || d->transient || !d->started) { if (immutability() != Types::Mutable || d->transient || !d->started) {
return; //don't double delete return; // don't double delete
} }
d->setDestroyed(true); d->setDestroyed(true);
//FIXME: an animation on leave if !isContainment() would be good again .. which should be handled by the containment class // FIXME: an animation on leave if !isContainment() would be good again .. which should be handled by the containment class
d->cleanUpAndDelete(); d->cleanUpAndDelete();
} }
@ -336,12 +333,12 @@ void Applet::updateConstraints(Plasma::Types::Constraints constraints)
void Applet::constraintsEvent(Plasma::Types::Constraints constraints) void Applet::constraintsEvent(Plasma::Types::Constraints constraints)
{ {
//NOTE: do NOT put any code in here that reacts to constraints updates // NOTE: do NOT put any code in here that reacts to constraints updates
// as it will not get called for any applet that reimplements constraintsEvent // as it will not get called for any applet that reimplements constraintsEvent
// without calling the Applet:: version as well, which it shouldn't need to. // without calling the Applet:: version as well, which it shouldn't need to.
// INSTEAD put such code into flushPendingConstraintsEvents // INSTEAD put such code into flushPendingConstraintsEvents
Q_UNUSED(constraints) Q_UNUSED(constraints)
//qCDebug(LOG_PLASMA) << constraints << "constraints are FormFactor: " << formFactor() // qCDebug(LOG_PLASMA) << constraints << "constraints are FormFactor: " << formFactor()
// << ", Location: " << location(); // << ", Location: " << location();
if (d->script) { if (d->script) {
d->script->constraintsEvent(constraints); d->script->constraintsEvent(constraints);
@ -424,8 +421,7 @@ void Applet::setBackgroundHints(Plasma::Types::BackgroundHints hint)
Plasma::Types::BackgroundHints Applet::effectiveBackgroundHints() const Plasma::Types::BackgroundHints Applet::effectiveBackgroundHints() const
{ {
if (d->userBackgroundHintsInitialized if (d->userBackgroundHintsInitialized && (d->backgroundHints & Plasma::Types::ConfigurableBackground)) {
&& (d->backgroundHints & Plasma::Types::ConfigurableBackground)) {
return d->userBackgroundHints; return d->userBackgroundHints;
} else { } else {
return d->backgroundHints; return d->backgroundHints;
@ -458,7 +454,6 @@ void Applet::setUserBackgroundHints(Plasma::Types::BackgroundHints hint)
} }
} }
KPluginInfo Applet::pluginInfo() const KPluginInfo Applet::pluginInfo() const
{ {
return KPluginInfo(d->appletDescription); return KPluginInfo(d->appletDescription);
@ -478,7 +473,7 @@ Types::ImmutabilityType Applet::immutability() const
return Types::SystemImmutable; return Types::SystemImmutable;
} }
//Returning the more strict immutability between the applet immutability, Containment and Corona // Returning the more strict immutability between the applet immutability, Containment and Corona
Types::ImmutabilityType upperImmutability = Types::Mutable; Types::ImmutabilityType upperImmutability = Types::Mutable;
if (isContainment()) { if (isContainment()) {
@ -591,7 +586,7 @@ void Applet::flushPendingConstraintsEvents()
d->constraintsTimer.stop(); d->constraintsTimer.stop();
} }
//qCDebug(LOG_PLASMA) << "flushing constraints: " << d->pendingConstraints << "!!!!!!!!!!!!!!!!!!!!!!!!!!!"; // qCDebug(LOG_PLASMA) << "flushing constraints: " << d->pendingConstraints << "!!!!!!!!!!!!!!!!!!!!!!!!!!!";
Plasma::Types::Constraints c = d->pendingConstraints; Plasma::Types::Constraints c = d->pendingConstraints;
d->pendingConstraints = Types::NoConstraint; d->pendingConstraints = Types::NoConstraint;
@ -600,7 +595,7 @@ void Applet::flushPendingConstraintsEvents()
} }
if (c & Plasma::Types::StartupCompletedConstraint) { if (c & Plasma::Types::StartupCompletedConstraint) {
//common actions // common actions
bool unlocked = immutability() == Types::Mutable; bool unlocked = immutability() == Types::Mutable;
QAction *closeApplet = d->actions->action(QStringLiteral("remove")); QAction *closeApplet = d->actions->action(QStringLiteral("remove"));
if (closeApplet) { if (closeApplet) {
@ -611,7 +606,6 @@ void Applet::flushPendingConstraintsEvents()
QAction *configAction = d->actions->action(QStringLiteral("configure")); QAction *configAction = d->actions->action(QStringLiteral("configure"));
if (configAction) { if (configAction) {
if (d->hasConfigurationInterface) { if (d->hasConfigurationInterface) {
bool canConfig = unlocked || KAuthorized::authorize(QStringLiteral("plasma/allow_configure_when_locked")); bool canConfig = unlocked || KAuthorized::authorize(QStringLiteral("plasma/allow_configure_when_locked"));
configAction->setVisible(canConfig); configAction->setVisible(canConfig);
@ -642,8 +636,8 @@ void Applet::flushPendingConstraintsEvents()
action->setEnabled(canConfig); action->setEnabled(canConfig);
} }
//an immutable constraint will always happen at startup // an immutable constraint will always happen at startup
//make sure don't emit a change signal for nothing // make sure don't emit a change signal for nothing
if (d->oldImmutability != immutability()) { if (d->oldImmutability != immutability()) {
Q_EMIT immutabilityChanged(immutability()); Q_EMIT immutabilityChanged(immutability());
} }
@ -681,7 +675,7 @@ void Applet::flushPendingConstraintsEvents()
QList<QAction *> Applet::contextualActions() QList<QAction *> Applet::contextualActions()
{ {
//qCDebug(LOG_PLASMA) << "empty context actions"; // qCDebug(LOG_PLASMA) << "empty context actions";
return d->script ? d->script->contextualActions() : QList<QAction *>(); return d->script ? d->script->contextualActions() : QList<QAction *>();
} }
@ -695,7 +689,7 @@ Types::FormFactor Applet::formFactor() const
Containment *c = containment(); Containment *c = containment();
QObject *pw = qobject_cast<QObject *>(parent()); QObject *pw = qobject_cast<QObject *>(parent());
Plasma::Applet *parentApplet = qobject_cast<Plasma::Applet *>(pw); Plasma::Applet *parentApplet = qobject_cast<Plasma::Applet *>(pw);
//assumption: this loop is usually is -really- short or doesn't run at all // assumption: this loop is usually is -really- short or doesn't run at all
while (!parentApplet && pw && pw->parent()) { while (!parentApplet && pw && pw->parent()) {
pw = pw->parent(); pw = pw->parent();
parentApplet = qobject_cast<Plasma::Applet *>(pw); parentApplet = qobject_cast<Plasma::Applet *>(pw);
@ -742,8 +736,7 @@ void Applet::setGlobalShortcut(const QKeySequence &shortcut)
d->activationAction->setText(i18n("Activate %1 Widget", title())); d->activationAction->setText(i18n("Activate %1 Widget", title()));
d->activationAction->setObjectName(QStringLiteral("activate widget %1").arg(id())); // NO I18N d->activationAction->setObjectName(QStringLiteral("activate widget %1").arg(id())); // NO I18N
connect(d->activationAction, &QAction::triggered, this, &Applet::activated); connect(d->activationAction, &QAction::triggered, this, &Applet::activated);
connect(d->activationAction, SIGNAL(changed()), connect(d->activationAction, SIGNAL(changed()), this, SLOT(globalShortcutChanged()));
this, SLOT(globalShortcutChanged()));
} else if (d->activationAction->shortcut() == shortcut) { } else if (d->activationAction->shortcut() == shortcut) {
return; return;
} }
@ -898,13 +891,13 @@ void Applet::timerEvent(QTimerEvent *event)
bool Applet::isContainment() const bool Applet::isContainment() const
{ {
//HACK: this is a special case for the systray // HACK: this is a special case for the systray
//containment in an applet that is not a containment // containment in an applet that is not a containment
Applet *pa = qobject_cast<Applet *>(parent()); Applet *pa = qobject_cast<Applet *>(parent());
if (pa && !pa->isContainment()) { if (pa && !pa->isContainment()) {
return true; return true;
} }
//normal "acting as a containment" condition // normal "acting as a containment" condition
return qobject_cast<const Containment *>(this) && qobject_cast<Corona *>(parent()); return qobject_cast<const Containment *>(this) && qobject_cast<Corona *>(parent());
} }

View File

@ -9,16 +9,16 @@
#ifndef PLASMA_APPLET_H #ifndef PLASMA_APPLET_H
#define PLASMA_APPLET_H #define PLASMA_APPLET_H
#include <QObject>
#include <QKeySequence> #include <QKeySequence>
#include <QObject>
#include <QUrl> #include <QUrl>
#include <KConfigGroup> #include <KConfigGroup>
#include <KPluginInfo> #include <KPluginInfo>
#include <plasma/framesvg.h>
#include <plasma/plasma.h> #include <plasma/plasma.h>
#include <plasma/version.h> #include <plasma/version.h>
#include <plasma/framesvg.h>
#include <KPackage/Package> #include <KPackage/Package>
@ -27,7 +27,6 @@ class KConfigLoader;
namespace Plasma namespace Plasma
{ {
class AppletPrivate; class AppletPrivate;
class Containment; class Containment;
class DataEngine; class DataEngine;
@ -79,7 +78,7 @@ class PLASMA_EXPORT Applet : public QObject
Q_PROPERTY(Plasma::Types::BackgroundHints effectiveBackgroundHints READ effectiveBackgroundHints NOTIFY effectiveBackgroundHintsChanged FINAL) Q_PROPERTY(Plasma::Types::BackgroundHints effectiveBackgroundHints READ effectiveBackgroundHints NOTIFY effectiveBackgroundHintsChanged FINAL)
public: public:
//CONSTRUCTORS // CONSTRUCTORS
/** /**
* @param parent the QObject this applet is parented to * @param parent the QObject this applet is parented to
* @param serviceId the name of the .desktop file containing the * @param serviceId the name of the .desktop file containing the
@ -114,7 +113,7 @@ public:
~Applet() override; ~Applet() override;
//BOOKKEEPING // BOOKKEEPING
/** /**
* @return the id of this applet * @return the id of this applet
*/ */
@ -182,14 +181,14 @@ public:
*/ */
Types::ContainmentDisplayHints containmentDisplayHints() const; Types::ContainmentDisplayHints containmentDisplayHints() const;
//CONFIGURATION // CONFIGURATION
/** /**
* Returns the KConfigGroup to access the applets configuration. * Returns the KConfigGroup to access the applets configuration.
* *
* This config object will write to an instance * This config object will write to an instance
* specific config file named \<appletname\>\<instanceid\>rc * specific config file named \<appletname\>\<instanceid\>rc
* in the Plasma appdata directory. * in the Plasma appdata directory.
**/ **/
KConfigGroup config() const; KConfigGroup config() const;
/** /**
@ -259,7 +258,7 @@ public:
*/ */
void setUserConfiguring(bool configuring); void setUserConfiguring(bool configuring);
//UTILS // UTILS
#if PLASMA_ENABLE_DEPRECATED_SINCE(5, 6) #if PLASMA_ENABLE_DEPRECATED_SINCE(5, 6)
/** /**
* Accessor for the associated Package object if any. * Accessor for the associated Package object if any.
@ -290,7 +289,7 @@ public:
*/ */
void updateConstraints(Plasma::Types::Constraints constraints = Plasma::Types::AllConstraints); void updateConstraints(Plasma::Types::Constraints constraints = Plasma::Types::AllConstraints);
//METADATA // METADATA
#if PLASMA_ENABLE_DEPRECATED_SINCE(5, 28) #if PLASMA_ENABLE_DEPRECATED_SINCE(5, 28)
/** /**
* @return metadata information about this plugin * @return metadata information about this plugin
@ -406,12 +405,13 @@ public:
void setUserBackgroundHints(Plasma::Types::BackgroundHints hint); void setUserBackgroundHints(Plasma::Types::BackgroundHints hint);
/** /**
* The effective background hints the applet will have: it will follow userBackgroundHints only if backgroundHints has the Plasma::Types::ConfigurableBackground flag set * The effective background hints the applet will have: it will follow userBackgroundHints only if backgroundHints has the
* Plasma::Types::ConfigurableBackground flag set
* @since 5.65 * @since 5.65
*/ */
Plasma::Types::BackgroundHints effectiveBackgroundHints() const; Plasma::Types::BackgroundHints effectiveBackgroundHints() const;
//ACTIONS // ACTIONS
/** /**
* Returns a list of context-related QAction instances. * Returns a list of context-related QAction instances.
* *
@ -439,7 +439,7 @@ public:
*/ */
QKeySequence globalShortcut() const; QKeySequence globalShortcut() const;
// ASSOCIATED APPLICATION // ASSOCIATED APPLICATION
/** /**
* Sets an application associated to this applet, that will be * Sets an application associated to this applet, that will be
* regarded as a full view of what is represented in the applet * regarded as a full view of what is represented in the applet
@ -480,14 +480,14 @@ public:
*/ */
bool hasValidAssociatedApplication() const; bool hasValidAssociatedApplication() const;
//Completely UI-specific, remove or move to scriptengine // Completely UI-specific, remove or move to scriptengine
/** /**
* @return true if this plasmoid provides a GUI configuration * @return true if this plasmoid provides a GUI configuration
**/ **/
bool hasConfigurationInterface() const; bool hasConfigurationInterface() const;
Q_SIGNALS: Q_SIGNALS:
//BOOKEEPING // BOOKEEPING
/** /**
* Emitted when the immutability changes * Emitted when the immutability changes
* @since 4.4 * @since 4.4
@ -543,7 +543,7 @@ Q_SIGNALS:
*/ */
void effectiveBackgroundHintsChanged(); void effectiveBackgroundHintsChanged();
//CONFIGURATION // CONFIGURATION
/** /**
* Emitted when an applet has changed values in its configuration * Emitted when an applet has changed values in its configuration
* and wishes for them to be saved at the next save point. As this implies * and wishes for them to be saved at the next save point. As this implies
@ -559,7 +559,7 @@ Q_SIGNALS:
*/ */
void userConfiguringChanged(bool configuring); void userConfiguringChanged(bool configuring);
//ACTIONS // ACTIONS
/** /**
* Emitted just before the contextual actions are about to show * Emitted just before the contextual actions are about to show
* For instance just before the context menu containing the actions * For instance just before the context menu containing the actions
@ -573,7 +573,7 @@ Q_SIGNALS:
*/ */
void activated(); void activated();
//TODO: fix usage in containment, port to QObject::destroyed // TODO: fix usage in containment, port to QObject::destroyed
/** /**
* Emitted when the applet is deleted * Emitted when the applet is deleted
*/ */
@ -599,7 +599,7 @@ Q_SIGNALS:
void configurationRequiredChanged(bool needsConfig, const QString &reason); void configurationRequiredChanged(bool needsConfig, const QString &reason);
public Q_SLOTS: public Q_SLOTS:
//BOOKKEEPING // BOOKKEEPING
/** /**
* Call this method when the applet fails to launch properly. An * Call this method when the applet fails to launch properly. An
* optional reason can be provided. * optional reason can be provided.
@ -635,14 +635,14 @@ public Q_SLOTS:
*/ */
void setStatus(const Types::ItemStatus stat); void setStatus(const Types::ItemStatus stat);
//CONFIGURATION // CONFIGURATION
/** /**
* Called when applet configuration values have changed. * Called when applet configuration values have changed.
*/ */
//TODO KF6: make it not a slot anymore and protected // TODO KF6: make it not a slot anymore and protected
virtual void configChanged(); virtual void configChanged();
//UTILS // UTILS
/** /**
* Sends all pending constraints updates to the applet. Will usually * Sends all pending constraints updates to the applet. Will usually
* be called automatically, but can also be called manually if needed. * be called automatically, but can also be called manually if needed.
@ -661,19 +661,19 @@ public Q_SLOTS:
**/ **/
virtual void init(); virtual void init();
//ASSOCIATED APPLICATION // ASSOCIATED APPLICATION
/** /**
* Open the application associated to this applet, if it's not set * Open the application associated to this applet, if it's not set
* but some urls are, open those urls with the proper application * but some urls are, open those urls with the proper application
* for their mimetype * for their mimetype
* @see setAssociatedApplication() * @see setAssociatedApplication()
* @see setAssociatedApplicationUrls() * @see setAssociatedApplicationUrls()
* @since 4.4 * @since 4.4
*/ */
void runAssociatedApplication(); void runAssociatedApplication();
protected: protected:
//CONSTRUCTORS // CONSTRUCTORS
/** /**
* This constructor is to be used with the plugin loading systems * This constructor is to be used with the plugin loading systems
* found in KPluginInfo and KService. The argument list is expected * found in KPluginInfo and KService. The argument list is expected
@ -686,7 +686,7 @@ protected:
*/ */
Applet(QObject *parent, const QVariantList &args); Applet(QObject *parent, const QVariantList &args);
//CONFIGURATION // CONFIGURATION
/** /**
* When called, the Applet should write any information needed as part * When called, the Applet should write any information needed as part
* of the Applet's running state to the configuration object in config() * of the Applet's running state to the configuration object in config()
@ -722,7 +722,7 @@ protected:
*/ */
void setConfigurationRequired(bool needsConfiguring, const QString &reason = QString()); void setConfigurationRequired(bool needsConfiguring, const QString &reason = QString());
//UTILS // UTILS
/** /**
* Called when any of the constraints for the applet have been updated. These constraints * Called when any of the constraints for the applet have been updated. These constraints
* range from notifying when the applet has officially "started up" to when geometry changes * range from notifying when the applet has officially "started up" to when geometry changes
@ -743,7 +743,7 @@ protected:
*/ */
virtual void constraintsEvent(Plasma::Types::Constraints constraints); virtual void constraintsEvent(Plasma::Types::Constraints constraints);
//TODO: timerEvent should go into AppletPrivate // TODO: timerEvent should go into AppletPrivate
/** /**
* Reimplemented from QObject * Reimplemented from QObject
*/ */
@ -769,7 +769,7 @@ private:
AppletPrivate *const d; AppletPrivate *const d;
//Corona needs to access setLaunchErrorMessage and init // Corona needs to access setLaunchErrorMessage and init
friend class Corona; friend class Corona;
friend class CoronaPrivate; friend class CoronaPrivate;
friend class Containment; friend class Containment;
@ -787,12 +787,12 @@ private:
/** /**
* Register an applet when it is contained in a loadable module * Register an applet when it is contained in a loadable module
*/ */
#define K_EXPORT_PLASMA_APPLET(libname, classname) \ #define K_EXPORT_PLASMA_APPLET(libname, classname) \
K_PLUGIN_FACTORY(factory, registerPlugin<classname>();) \ K_PLUGIN_FACTORY(factory, registerPlugin<classname>();) \
K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION) K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION)
#define K_EXPORT_PLASMA_APPLET_WITH_JSON(libname, classname, jsonFile) \ #define K_EXPORT_PLASMA_APPLET_WITH_JSON(libname, classname, jsonFile) \
K_PLUGIN_FACTORY_WITH_JSON(factory, jsonFile, registerPlugin<classname>();) \ K_PLUGIN_FACTORY_WITH_JSON(factory, jsonFile, registerPlugin<classname>();) \
K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION) K_EXPORT_PLUGIN_VERSION(PLASMA_VERSION)
#endif // multiple inclusion guard #endif // multiple inclusion guard

View File

@ -13,23 +13,23 @@
#include "config-plasma.h" #include "config-plasma.h"
#include <QClipboard> #include <QClipboard>
#include <QContextMenuEvent>
#include <QDebug> #include <QDebug>
#include <QFile> #include <QFile>
#include <QContextMenuEvent>
#include <QMimeData> #include <QMimeData>
#include <QMimeDatabase>
#include <QPainter> #include <QPainter>
#include <QTemporaryFile> #include <QTemporaryFile>
#include <QMimeDatabase>
#include <KAuthorized> #include <KAuthorized>
#include <KLocalizedString>
#include <KConfigSkeleton>
#include <KConfigLoader> #include <KConfigLoader>
#include <KConfigSkeleton>
#include <KLocalizedString>
#include "containmentactions.h" #include "containmentactions.h"
#include "corona.h" #include "corona.h"
#include "pluginloader.h"
#include "debug_p.h" #include "debug_p.h"
#include "pluginloader.h"
#include "private/applet_p.h" #include "private/applet_p.h"
@ -37,12 +37,9 @@
namespace Plasma namespace Plasma
{ {
Containment::Containment(QObject *parent, const QString &serviceId, uint containmentId)
Containment::Containment(QObject *parent, : Applet(parent, serviceId, containmentId)
const QString &serviceId, , d(new ContainmentPrivate(this))
uint containmentId)
: Applet(parent, serviceId, containmentId),
d(new ContainmentPrivate(this))
{ {
// WARNING: do not access config() OR globalConfig() in this method! // WARNING: do not access config() OR globalConfig() in this method!
// that requires a scene, which is not available at this point // that requires a scene, which is not available at this point
@ -51,8 +48,8 @@ Containment::Containment(QObject *parent,
} }
Containment::Containment(QObject *parent, const QVariantList &args) Containment::Containment(QObject *parent, const QVariantList &args)
: Applet(parent, args), : Applet(parent, args)
d(new ContainmentPrivate(this)) , d(new ContainmentPrivate(this))
{ {
// WARNING: do not access config() OR globalConfig() in this method! // WARNING: do not access config() OR globalConfig() in this method!
// that requires a scene, which is not available at this point // that requires a scene, which is not available at this point
@ -60,8 +57,8 @@ Containment::Containment(QObject *parent, const QVariantList &args)
} }
Containment::Containment(const KPluginMetaData &md, uint appletId) Containment::Containment(const KPluginMetaData &md, uint appletId)
: Applet(md, nullptr, appletId), : Applet(md, nullptr, appletId)
d(new ContainmentPrivate(this)) , d(new ContainmentPrivate(this))
{ {
// WARNING: do not access config() OR globalConfig() in this method! // WARNING: do not access config() OR globalConfig() in this method!
// that requires a scene, which is not available at this point // that requires a scene, which is not available at this point
@ -80,8 +77,8 @@ void Containment::init()
static_cast<Applet *>(this)->d->setupScripting(); static_cast<Applet *>(this)->d->setupScripting();
if (d->type == Types::NoContainmentType) { if (d->type == Types::NoContainmentType) {
//setContainmentType(Plasma::Types::DesktopContainment); // setContainmentType(Plasma::Types::DesktopContainment);
//Try to determine the containment type. It must be done as soon as possible // Try to determine the containment type. It must be done as soon as possible
QString type = pluginMetaData().value(QStringLiteral("X-Plasma-ContainmentType")); QString type = pluginMetaData().value(QStringLiteral("X-Plasma-ContainmentType"));
if (type == QLatin1String("Panel")) { if (type == QLatin1String("Panel")) {
@ -90,18 +87,18 @@ void Containment::init()
setContainmentType(Plasma::Types::CustomContainment); setContainmentType(Plasma::Types::CustomContainment);
} else if (type == QLatin1String("CustomPanel")) { } else if (type == QLatin1String("CustomPanel")) {
setContainmentType(Plasma::Types::CustomPanelContainment); setContainmentType(Plasma::Types::CustomPanelContainment);
//default to desktop // default to desktop
} else { } else {
setContainmentType(Plasma::Types::DesktopContainment); setContainmentType(Plasma::Types::DesktopContainment);
} }
} }
//connect actions // connect actions
ContainmentPrivate::addDefaultActions(actions(), this); ContainmentPrivate::addDefaultActions(actions(), this);
bool unlocked = immutability() == Types::Mutable; bool unlocked = immutability() == Types::Mutable;
//fix the text of the actions that need title() // fix the text of the actions that need title()
//btw, do we really want to use title() when it's a desktopcontainment? // btw, do we really want to use title() when it's a desktopcontainment?
QAction *closeApplet = actions()->action(QStringLiteral("remove")); QAction *closeApplet = actions()->action(QStringLiteral("remove"));
if (closeApplet) { if (closeApplet) {
closeApplet->setText(i18nc("%1 is the name of the applet", "Remove %1", title())); closeApplet->setText(i18nc("%1 is the name of the applet", "Remove %1", title()));
@ -126,14 +123,14 @@ void Containment::init()
if (immutability() != Types::SystemImmutable && corona()) { if (immutability() != Types::SystemImmutable && corona()) {
QAction *lockDesktopAction = corona()->actions()->action(QStringLiteral("lock widgets")); QAction *lockDesktopAction = corona()->actions()->action(QStringLiteral("lock widgets"));
//keep a pointer so nobody notices it moved to corona // keep a pointer so nobody notices it moved to corona
if (lockDesktopAction) { if (lockDesktopAction) {
actions()->addAction(QStringLiteral("lock widgets"), lockDesktopAction); actions()->addAction(QStringLiteral("lock widgets"), lockDesktopAction);
} }
} }
//HACK: this is valid only in the systray case // HACK: this is valid only in the systray case
connect(this, &Containment::configureRequested, this, [=] (Plasma::Applet *a) { connect(this, &Containment::configureRequested, this, [=](Plasma::Applet *a) {
if (Plasma::Applet *p = qobject_cast<Plasma::Applet *>(parent())) { if (Plasma::Applet *p = qobject_cast<Plasma::Applet *>(parent())) {
Q_EMIT p->containment()->configureRequested(a); Q_EMIT p->containment()->configureRequested(a);
} }
@ -176,28 +173,28 @@ void Containment::restore(KConfigGroup &group)
KConfigGroup cfg = KConfigGroup(corona()->config(), "ActionPlugins"); KConfigGroup cfg = KConfigGroup(corona()->config(), "ActionPlugins");
cfg = KConfigGroup(&cfg, QString::number(containmentType())); cfg = KConfigGroup(&cfg, QString::number(containmentType()));
//qCDebug(LOG_PLASMA) << cfg.keyList(); // qCDebug(LOG_PLASMA) << cfg.keyList();
if (cfg.exists()) { if (cfg.exists()) {
const auto keyList = cfg.keyList(); const auto keyList = cfg.keyList();
for (const QString &key : keyList) { for (const QString &key : keyList) {
//qCDebug(LOG_PLASMA) << "loading" << key; // qCDebug(LOG_PLASMA) << "loading" << key;
setContainmentActions(key, cfg.readEntry(key, QString())); setContainmentActions(key, cfg.readEntry(key, QString()));
} }
} else { //shell defaults } else { // shell defaults
KConfigGroup defaultActionsCfg; KConfigGroup defaultActionsCfg;
switch (d->type) { switch (d->type) {
case Plasma::Types::PanelContainment: case Plasma::Types::PanelContainment:
/* fall through*/ /* fall through*/
case Plasma::Types::CustomPanelContainment: case Plasma::Types::CustomPanelContainment:
defaultActionsCfg = KConfigGroup(KSharedConfig::openConfig(corona()->kPackage().filePath("defaults")), "Panel"); defaultActionsCfg = KConfigGroup(KSharedConfig::openConfig(corona()->kPackage().filePath("defaults")), "Panel");
break; break;
case Plasma::Types::DesktopContainment: case Plasma::Types::DesktopContainment:
defaultActionsCfg = KConfigGroup(KSharedConfig::openConfig(corona()->kPackage().filePath("defaults")), "Desktop"); defaultActionsCfg = KConfigGroup(KSharedConfig::openConfig(corona()->kPackage().filePath("defaults")), "Desktop");
break; break;
default: default:
//for any other type of containment, there are no defaults // for any other type of containment, there are no defaults
break; break;
} }
if (defaultActionsCfg.isValid()) { if (defaultActionsCfg.isValid()) {
defaultActionsCfg = KConfigGroup(&defaultActionsCfg, "ContainmentActions"); defaultActionsCfg = KConfigGroup(&defaultActionsCfg, "ContainmentActions");
@ -233,7 +230,7 @@ void Containment::save(KConfigGroup &g) const
// locking is saved in Applet::save // locking is saved in Applet::save
Applet::save(group); Applet::save(group);
// group.writeEntry("screen", d->screen); // group.writeEntry("screen", d->screen);
group.writeEntry("lastScreen", d->lastScreen); group.writeEntry("lastScreen", d->lastScreen);
group.writeEntry("formfactor", (int)d->formFactor); group.writeEntry("formfactor", (int)d->formFactor);
group.writeEntry("location", (int)d->location); group.writeEntry("location", (int)d->location);
@ -257,7 +254,7 @@ void Containment::restoreContents(KConfigGroup &group)
{ {
KConfigGroup applets(&group, "Applets"); KConfigGroup applets(&group, "Applets");
//restore the applets ordered by id // restore the applets ordered by id
QStringList groups = applets.groupList(); QStringList groups = applets.groupList();
std::sort(groups.begin(), groups.end()); std::sort(groups.begin(), groups.end());
@ -265,7 +262,7 @@ void Containment::restoreContents(KConfigGroup &group)
// are added from left to right or top to bottom for a panel containment // are added from left to right or top to bottom for a panel containment
QList<KConfigGroup> appletConfigs; QList<KConfigGroup> appletConfigs;
for (const QString &appletGroup : qAsConst(groups)) { for (const QString &appletGroup : qAsConst(groups)) {
//qCDebug(LOG_PLASMA) << "reading from applet group" << appletGroup; // qCDebug(LOG_PLASMA) << "reading from applet group" << appletGroup;
KConfigGroup appletConfig(&applets, appletGroup); KConfigGroup appletConfig(&applets, appletGroup);
appletConfigs.append(appletConfig); appletConfigs.append(appletConfig);
} }
@ -284,7 +281,7 @@ void Containment::restoreContents(KConfigGroup &group)
d->createApplet(plugin, QVariantList(), appId); d->createApplet(plugin, QVariantList(), appId);
} }
//if there are no applets, none of them is "loading" // if there are no applets, none of them is "loading"
if (Containment::applets().isEmpty()) { if (Containment::applets().isEmpty()) {
d->appletsUiReady = true; d->appletsUiReady = true;
} }
@ -313,9 +310,9 @@ void Containment::setContainmentType(Plasma::Types::ContainmentType type)
Corona *Containment::corona() const Corona *Containment::corona() const
{ {
if(Plasma::Corona* corona = qobject_cast<Corona *>(parent())) { if (Plasma::Corona *corona = qobject_cast<Corona *>(parent())) {
return corona; return corona;
//case in which this containment is child of an applet, hello systray :) // case in which this containment is child of an applet, hello systray :)
} else { } else {
Plasma::Applet *parentApplet = qobject_cast<Plasma::Applet *>(parent()); Plasma::Applet *parentApplet = qobject_cast<Plasma::Applet *>(parent());
if (parentApplet && parentApplet->containment()) { if (parentApplet && parentApplet->containment()) {
@ -332,7 +329,7 @@ void Containment::setFormFactor(Types::FormFactor formFactor)
return; return;
} }
//qCDebug(LOG_PLASMA) << "switching FF to " << formFactor; // qCDebug(LOG_PLASMA) << "switching FF to " << formFactor;
d->formFactor = formFactor; d->formFactor = formFactor;
updateConstraints(Plasma::Types::FormFactorConstraint); updateConstraints(Plasma::Types::FormFactorConstraint);
@ -413,14 +410,14 @@ void Containment::addApplet(Applet *applet)
applet->setParent(this); applet->setParent(this);
// now move the old config to the new location // now move the old config to the new location
//FIXME: this doesn't seem to get the actual main config group containing plugin=, etc // FIXME: this doesn't seem to get the actual main config group containing plugin=, etc
KConfigGroup c = config().group("Applets").group(QString::number(applet->id())); KConfigGroup c = config().group("Applets").group(QString::number(applet->id()));
oldConfig.reparent(&c); oldConfig.reparent(&c);
applet->d->resetConfigurationObject(); applet->d->resetConfigurationObject();
disconnect(applet, &Applet::activated, currentContainment, &Applet::activated); disconnect(applet, &Applet::activated, currentContainment, &Applet::activated);
//change the group to its configloader, if any // change the group to its configloader, if any
//FIXME: this is very, very brutal // FIXME: this is very, very brutal
if (applet->configScheme()) { if (applet->configScheme()) {
const QString oldGroupPrefix = QStringLiteral("Containments") + QString::number(currentContainment->id()) + QStringLiteral("Applets"); const QString oldGroupPrefix = QStringLiteral("Containments") + QString::number(currentContainment->id()) + QStringLiteral("Applets");
const QString newGroupPrefix = QStringLiteral("Containments") + QString::number(id()) + QStringLiteral("Applets"); const QString newGroupPrefix = QStringLiteral("Containments") + QString::number(id()) + QStringLiteral("Applets");
@ -436,8 +433,8 @@ void Containment::addApplet(Applet *applet)
applet->setParent(this); applet->setParent(this);
} }
//make sure the applets are sorted by id // make sure the applets are sorted by id
auto position = std::lower_bound(d->applets.begin(), d->applets.end(), applet, [](Plasma::Applet *a1, Plasma::Applet *a2) { auto position = std::lower_bound(d->applets.begin(), d->applets.end(), applet, [](Plasma::Applet *a1, Plasma::Applet *a2) {
return a1->id() < a2->id(); return a1->id() < a2->id();
}); });
d->applets.insert(position, applet); d->applets.insert(position, applet);
@ -447,7 +444,7 @@ void Containment::addApplet(Applet *applet)
} }
connect(applet, &Applet::configNeedsSaving, this, &Applet::configNeedsSaving); connect(applet, &Applet::configNeedsSaving, this, &Applet::configNeedsSaving);
connect(applet, SIGNAL(appletDeleted(Plasma::Applet*)), this, SLOT(appletDeleted(Plasma::Applet*))); connect(applet, SIGNAL(appletDeleted(Plasma::Applet *)), this, SLOT(appletDeleted(Plasma::Applet *)));
connect(applet, SIGNAL(statusChanged(Plasma::Types::ItemStatus)), this, SLOT(checkStatus(Plasma::Types::ItemStatus))); connect(applet, SIGNAL(statusChanged(Plasma::Types::ItemStatus)), this, SLOT(checkStatus(Plasma::Types::ItemStatus)));
connect(applet, &Applet::activated, this, &Applet::activated); connect(applet, &Applet::activated, this, &Applet::activated);
connect(this, &Containment::containmentDisplayHintsChanged, applet, &Applet::containmentDisplayHintsChanged); connect(this, &Containment::containmentDisplayHintsChanged, applet, &Applet::containmentDisplayHintsChanged);
@ -466,7 +463,7 @@ void Containment::addApplet(Applet *applet)
applet->save(*applet->d->mainConfigGroup()); applet->save(*applet->d->mainConfigGroup());
Q_EMIT configNeedsSaving(); Q_EMIT configNeedsSaving();
} }
//FIXME: an on-appear animation would be nice to have again // FIXME: an on-appear animation would be nice to have again
} }
applet->updateConstraints(Plasma::Types::AllConstraints); applet->updateConstraints(Plasma::Types::AllConstraints);
@ -490,7 +487,7 @@ QList<Applet *> Containment::applets() const
int Containment::screen() const int Containment::screen() const
{ {
Q_ASSERT(corona()); Q_ASSERT(corona());
if (Corona* c = corona()) { if (Corona *c = corona()) {
return c->screenForContainment(this); return c->screenForContainment(this);
} else { } else {
return -1; return -1;
@ -534,9 +531,9 @@ void Containment::setContainmentActions(const QString &trigger, const QString &p
if (pluginName.isEmpty()) { if (pluginName.isEmpty()) {
cfg.deleteEntry(trigger); cfg.deleteEntry(trigger);
} else if (plugin) { } else if (plugin) {
//it already existed, just reload config // it already existed, just reload config
plugin->setContainment(this); //to be safe plugin->setContainment(this); // to be safe
//FIXME make a truly unique config group // FIXME make a truly unique config group
KConfigGroup pluginConfig = KConfigGroup(&cfg, trigger); KConfigGroup pluginConfig = KConfigGroup(&cfg, trigger);
plugin->restore(pluginConfig); plugin->restore(pluginConfig);
@ -550,7 +547,7 @@ void Containment::setContainmentActions(const QString &trigger, const QString &p
KConfigGroup pluginConfig = KConfigGroup(&cfg, trigger); KConfigGroup pluginConfig = KConfigGroup(&cfg, trigger);
plugin->restore(pluginConfig); plugin->restore(pluginConfig);
} else { } else {
//bad plugin... gets removed. is this a feature or a bug? // bad plugin... gets removed. is this a feature or a bug?
cfg.deleteEntry(trigger); cfg.deleteEntry(trigger);
} }
} }

View File

@ -14,7 +14,6 @@
namespace Plasma namespace Plasma
{ {
class DataEngine; class DataEngine;
class Package; class Package;
class Corona; class Corona;
@ -56,9 +55,7 @@ public:
* @param containmentId a unique id used to differentiate between multiple * @param containmentId a unique id used to differentiate between multiple
* instances of the same Applet type * instances of the same Applet type
*/ */
explicit Containment(QObject *parent = nullptr, explicit Containment(QObject *parent = nullptr, const QString &serviceId = QString(), uint containmentId = 0);
const QString &serviceId = QString(),
uint containmentId = 0);
/** /**
* This constructor is to be used with the plugin loading systems * This constructor is to be used with the plugin loading systems

View File

@ -7,22 +7,21 @@
#include "containmentactions.h" #include "containmentactions.h"
#include "containment.h" #include "containment.h"
#include "private/containmentactions_p.h"
#include "private/containment_p.h" #include "private/containment_p.h"
#include "private/containmentactions_p.h"
#include <QContextMenuEvent>
#include <QMetaEnum> #include <QMetaEnum>
#include <QMouseEvent> #include <QMouseEvent>
#include <QWheelEvent> #include <QWheelEvent>
#include <QContextMenuEvent>
#include <QDebug>
#include <KLocalizedString> #include <KLocalizedString>
#include <QDebug>
#include "version.h" #include "version.h"
namespace Plasma namespace Plasma
{ {
ContainmentActions::ContainmentActions(QObject *parentObject) ContainmentActions::ContainmentActions(QObject *parentObject)
: d(new ContainmentActionsPrivate({}, this)) : d(new ContainmentActionsPrivate({}, this))
{ {
@ -84,17 +83,17 @@ QWidget *ContainmentActions::createConfigurationInterface(QWidget *parent)
void ContainmentActions::configurationAccepted() void ContainmentActions::configurationAccepted()
{ {
//do nothing by default // do nothing by default
} }
void ContainmentActions::performNextAction() void ContainmentActions::performNextAction()
{ {
//do nothing by default, implement in subclasses // do nothing by default, implement in subclasses
} }
void ContainmentActions::performPreviousAction() void ContainmentActions::performPreviousAction()
{ {
//do nothing by default, implement in subclasses // do nothing by default, implement in subclasses
} }
QList<QAction *> ContainmentActions::contextualActions() QList<QAction *> ContainmentActions::contextualActions()

Some files were not shown because too many files have changed in this diff Show More