diff --git a/CMakeLists.txt b/CMakeLists.txt --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,7 @@ People DBusAddons Activities + ActivitiesStats ) find_package(LibKWorkspace CONFIG REQUIRED) @@ -141,7 +142,6 @@ plasma_install_package(layout-templates/org.kde.plasma.desktop.defaultPanel org.kde.plasma.desktop.defaultPanel layout-templates layout-template) add_subdirectory(doc) -add_subdirectory(libs) # add_subdirectory(runners) add_subdirectory(containments) add_subdirectory(toolboxes) diff --git a/applets/kicker/CMakeLists.txt b/applets/kicker/CMakeLists.txt --- a/applets/kicker/CMakeLists.txt +++ b/applets/kicker/CMakeLists.txt @@ -63,7 +63,7 @@ Qt5::Quick Qt5::X11Extras KF5::Activities - KF5::ActivitiesExperimentalStats + KF5::ActivitiesStats KF5::ConfigCore KF5::CoreAddons KF5::I18n diff --git a/applets/kicker/plugin/actionlist.cpp b/applets/kicker/plugin/actionlist.cpp --- a/applets/kicker/plugin/actionlist.cpp +++ b/applets/kicker/plugin/actionlist.cpp @@ -27,13 +27,13 @@ #include #include -#include -#include -#include +#include +#include +#include #include "containmentinterface.h" -namespace KAStats = KActivities::Experimental::Stats; +namespace KAStats = KActivities::Stats; using namespace KAStats; using namespace KAStats::Terms; diff --git a/applets/kicker/plugin/recentcontactsmodel.cpp b/applets/kicker/plugin/recentcontactsmodel.cpp --- a/applets/kicker/plugin/recentcontactsmodel.cpp +++ b/applets/kicker/plugin/recentcontactsmodel.cpp @@ -26,14 +26,14 @@ #include -#include -#include +#include +#include #include //FIXME TODO: Pretty include in KPeople broken. #include #include -namespace KAStats = KActivities::Experimental::Stats; +namespace KAStats = KActivities::Stats; using namespace KAStats; using namespace KAStats::Terms; diff --git a/applets/kicker/plugin/recentusagemodel.cpp b/applets/kicker/plugin/recentusagemodel.cpp --- a/applets/kicker/plugin/recentusagemodel.cpp +++ b/applets/kicker/plugin/recentusagemodel.cpp @@ -37,11 +37,11 @@ #include #include -#include -#include -#include +#include +#include +#include -namespace KAStats = KActivities::Experimental::Stats; +namespace KAStats = KActivities::Stats; using namespace KAStats; using namespace KAStats::Terms; diff --git a/applets/taskmanager/CMakeLists.txt b/applets/taskmanager/CMakeLists.txt --- a/applets/taskmanager/CMakeLists.txt +++ b/applets/taskmanager/CMakeLists.txt @@ -24,7 +24,7 @@ Qt5::Quick Qt5::Widgets KF5::Activities - KF5::ActivitiesExperimentalStats + KF5::ActivitiesStats KF5::I18n KF5::KIOCore KF5::KIOWidgets diff --git a/applets/taskmanager/plugin/backend.cpp b/applets/taskmanager/plugin/backend.cpp --- a/applets/taskmanager/plugin/backend.cpp +++ b/applets/taskmanager/plugin/backend.cpp @@ -43,11 +43,11 @@ #include #include -#include -#include -#include +#include +#include +#include -namespace KAStats = KActivities::Experimental::Stats; +namespace KAStats = KActivities::Stats; using namespace KAStats; using namespace KAStats::Terms; diff --git a/libs/CMakeLists.txt b/libs/CMakeLists.txt deleted file mode 100644 --- a/libs/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -# Temporary inclusion of kactivities-stats library to the repository -# until it matures enough to go to kactivities framework -add_subdirectory(kactivities-stats) diff --git a/libs/kactivities-stats/CMakeLists.txt b/libs/kactivities-stats/CMakeLists.txt deleted file mode 100644 --- a/libs/kactivities-stats/CMakeLists.txt +++ /dev/null @@ -1,34 +0,0 @@ -# vim:set softtabstop=3 shiftwidth=3 tabstop=3 expandtab: - -# Extra CMake stuff -find_package (ECM 1.8.0 REQUIRED NO_MODULE) -set (CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${ECM_MODULE_PATH} ${ECM_KDE_MODULE_DIR}) - -set (KACTIVITIES_CURRENT_ROOT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) -set (KACTIVITIES_INSTALL_EXPERIMENTAL_HEADERS FALSE) - -include (KDEInstallDirs) -include (KDECMakeSettings) -include (KDECompilerSettings) -include (GenerateExportHeader) -include (ECMGenerateHeaders) -include (ECMSetupVersion) -include (ECMPackageConfigHelpers) - -# libKActivitiesStats - -ecm_setup_version ( - ${KF5_VERSION} - VARIABLE_PREFIX KACTIVITIESEXPERIMENTALSTATS - VERSION_HEADER "${CMAKE_CURRENT_BINARY_DIR}/kactivitiesexperimentalstats_version.h" - PACKAGE_VERSION_FILE "${CMAKE_CURRENT_BINARY_DIR}/KF5ActivitiesExperimentalStatsConfigVersion.cmake" - SOVERSION 1 - ) - -set (CMAKECONFIG_INSTALL_DIR "${KDE_INSTALL_CMAKEPACKAGEDIR}/KF5ActivitiesExperimentalStats") - -add_subdirectory (src) - -# Write out the features -feature_summary (WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) - diff --git a/libs/kactivities-stats/KF5ActivitiesExperimentalStatsConfig.cmake.in b/libs/kactivities-stats/KF5ActivitiesExperimentalStatsConfig.cmake.in deleted file mode 100644 --- a/libs/kactivities-stats/KF5ActivitiesExperimentalStatsConfig.cmake.in +++ /dev/null @@ -1,5 +0,0 @@ -@PACKAGE_INIT@ - -find_dependency(Qt5Core @REQUIRED_QT_VERSION@) - -include("${CMAKE_CURRENT_LIST_DIR}/KF5ActivitiesExperimentalStatsLibraryTargets.cmake") diff --git a/libs/kactivities-stats/README b/libs/kactivities-stats/README deleted file mode 100644 --- a/libs/kactivities-stats/README +++ /dev/null @@ -1,6 +0,0 @@ -This is a COPY of the kactivities-stats library which resides in -kde:kactivities repo. - -Anything you do here will be overwritten automatically by the code -from the aforementioned branch. - diff --git a/libs/kactivities-stats/src/CMakeLists.txt b/libs/kactivities-stats/src/CMakeLists.txt deleted file mode 100644 --- a/libs/kactivities-stats/src/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -# vim:set softtabstop=3 shiftwidth=3 tabstop=3 expandtab: - -# The libraries do not depend on any compile-time features -add_subdirectory (lib) - diff --git a/libs/kactivities-stats/src/Messages.sh b/libs/kactivities-stats/src/Messages.sh deleted file mode 100644 --- a/libs/kactivities-stats/src/Messages.sh +++ /dev/null @@ -1,11 +0,0 @@ -#!/bin/sh - -# Invoke the extractrc script on all .ui, .rc, and .kcfg files in the sources. -# The results are stored in a pseudo .cpp file to be picked up by xgettext. -lst=`find . -name \*.rc -o -name \*.ui -o -name \*.kcfg` -if [ -n "$lst" ] ; then - $EXTRACTRC $lst >> rc.cpp -fi - -# Run xgettext to extract strings from all source files. -$XGETTEXT `find . -name \*.cpp -o -name \*.h -o -name \*.qml` -o $podir/kactivities-experimental-stats5.pot diff --git a/libs/kactivities-stats/src/common/database/Database.cpp b/libs/kactivities-stats/src/common/database/Database.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/common/database/Database.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Copyright 2014 Ivan Cukic - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License as - * published by the Free Software Foundation; either version 2 of - * the License or (at your option) version 3 or any later version - * accepted by the membership of KDE e.V. (or its successor approved - * by the membership of KDE e.V.), which shall act as a proxy - * defined in Section 14 of version 3 of the license. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -#include "Database.h" - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace Common { - -class Database::Private { -public: - QSqlDatabase database; -}; - -Database::Locker::Locker(Database &database) - : m_database(database.d->database) -{ - m_database.transaction(); -} - -Database::Locker::~Locker() -{ - m_database.commit(); -} - - -namespace { -#ifdef QT_DEBUG - QString lastExecutedQuery; -#endif - - std::mutex databases_mutex; - - struct DatabaseInfo { - Qt::HANDLE thread; - Database::OpenMode openMode; - }; - - bool operator<(const DatabaseInfo &left, const DatabaseInfo &right) - { - return - left.thread < right.thread ? true : - left.thread > right.thread ? false : - left.openMode < right.openMode; - } - - std::map> databases; -}; - -Database::Ptr Database::instance(Source source, OpenMode openMode) -{ - Q_UNUSED(source) // for the time being - - std::lock_guard lock(databases_mutex); - - // We are saving instances per thread and per read/write mode - DatabaseInfo info; - info.thread = QThread::currentThreadId(); - info.openMode = openMode; - - // Do we have an instance matching the request? - auto search = databases.find(info); - if (search != databases.end()) { - auto ptr = search->second.lock(); - - if (ptr) { - return ptr; - } - } - - // Creating a new database instance - auto ptr = std::make_shared(); - - auto databaseConnectionName = - "kactivities_db_resources_" - // Adding the thread number to the database name - + QString::number((quintptr)info.thread) - // And whether it is read-only or read-write - + (info.openMode == ReadOnly ? "_readonly" : "_readwrite"); - - ptr->d->database - = QSqlDatabase::contains(databaseConnectionName) - ? QSqlDatabase::database(databaseConnectionName) - : QSqlDatabase::addDatabase(QStringLiteral("QSQLITE"), databaseConnectionName); - - if (info.openMode == ReadOnly) { - ptr->d->database.setConnectOptions(QStringLiteral("QSQLITE_OPEN_READONLY")); - } - - // We are allowing the database file to be overridden mostly for testing purposes - ptr->d->database.setDatabaseName(ResourcesDatabaseSchema::path()); - - if (!ptr->d->database.open()) { - qWarning() << "KActivities: Database is not open: " - << ptr->d->database.connectionName() - << ptr->d->database.databaseName() - << ptr->d->database.lastError(); - - if (info.openMode == ReadWrite) { - qFatal("KActivities: Opening the database in RW mode should always succeed"); - } - - return Q_NULLPTR; - - } - - databases[info] = ptr; - - if (info.openMode == ReadOnly) { - // From now on, only SELECT queries will work - ptr->setPragma(QStringLiteral("query_only = 1")); - - // These should not make any difference - ptr->setPragma(QStringLiteral("synchronous = 0")); - - } else { - // Using the write-ahead log and sync = NORMAL for faster writes - ptr->setPragma(QStringLiteral("synchronous = 1")); - } - - // Maybe we should use the write-ahead log - auto walResult = ptr->pragma(QStringLiteral("journal_mode = WAL")); - - if (walResult != "wal") { - qFatal("KActivities: Database can not be opened in WAL mode. Check the " - "SQLite version (required >3.7.0). And whether your filesystem " - "supports shared memory"); - } - - // We don't have a big database, lets flush the WAL when - // it reaches 400k, not 4M as is default - ptr->setPragma(QStringLiteral("wal_autocheckpoint = 100")); - - qDebug() << "KActivities: Database connection: " << databaseConnectionName - << "\n query_only: " << ptr->pragma(QStringLiteral("query_only")) - << "\n journal_mode: " << ptr->pragma(QStringLiteral("journal_mode")) - << "\n wal_autocheckpoint: " << ptr->pragma(QStringLiteral("wal_autocheckpoint")) - << "\n synchronous: " << ptr->pragma(QStringLiteral("synchronous")) - ; - - return ptr; -} - -Database::Database() -{ - -} - - -Database::~Database() -{ -} - -QSqlQuery Database::createQuery() const -{ - return QSqlQuery(d->database); -} - -QString Database::lastQuery() const -{ -#ifdef QT_DEBUG - return lastExecutedQuery; -#endif - return QString(); -} - -QSqlQuery Database::execQuery(const QString &query, bool ignoreErrors) const -{ -#ifdef QT_NO_DEBUG - return QSqlQuery(query, d->database); -#else - auto result = QSqlQuery(query, d->database); - - lastExecutedQuery = query; - - if (!ignoreErrors && result.lastError().isValid()) { - qWarning() << "SQL: " - << "\n error: " << result.lastError() - << "\n query: " << query; - } - - return result; -#endif -} - -QSqlQuery Database::execQueries(const QStringList &queries) const -{ - QSqlQuery result; - - for (const auto query: queries) { - result = execQuery(query); - } - - return result; -} - -void Database::setPragma(const QString &pragma) -{ - execQuery(QStringLiteral("PRAGMA ") + pragma); -} - -QVariant Database::pragma(const QString &pragma) const -{ - return value("PRAGMA " + pragma); -} - -QVariant Database::value(const QString &query) const -{ - auto result = execQuery(query); - return result.next() ? result.value(0) : QVariant(); -} - -} // namespace Common - diff --git a/libs/kactivities-stats/src/common/database/schema/ResourcesDatabaseSchema.h b/libs/kactivities-stats/src/common/database/schema/ResourcesDatabaseSchema.h deleted file mode 100644 --- a/libs/kactivities-stats/src/common/database/schema/ResourcesDatabaseSchema.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2011, 2012, 2013, 2014, 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef RESOURCESDATABASESCHEMA_H -#define RESOURCESDATABASESCHEMA_H - -#include -#include "../Database.h" - -namespace Common { -namespace ResourcesDatabaseSchema { - - QString version(); - - QStringList schema(); - - QString path(); - void overridePath(const QString &path); - - void initSchema(Database &database); - -} // namespace ResourcesDatabase -} // namespace Common - -#endif // RESOURCESDATABASESCHEMA_H - diff --git a/libs/kactivities-stats/src/common/database/schema/ResourcesDatabaseSchema.cpp b/libs/kactivities-stats/src/common/database/schema/ResourcesDatabaseSchema.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/common/database/schema/ResourcesDatabaseSchema.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "ResourcesDatabaseSchema.h" - -#include -#include -#include - -namespace Common { -namespace ResourcesDatabaseSchema { - -const QString name = QStringLiteral("Resources"); - -QString version() -{ - return QStringLiteral("2015.02.09"); -} - -QStringList schema() -{ - // If only we could use initializer lists here ... - - return QStringList() - - << // Schema informations table, used for versioning - QStringLiteral("CREATE TABLE IF NOT EXISTS SchemaInfo (" - "key text PRIMARY KEY, value text" - ")") - - << QStringLiteral("INSERT OR IGNORE INTO schemaInfo VALUES ('version', '%1')").arg(version()) - << QStringLiteral("UPDATE schemaInfo SET value = '%1' WHERE key = 'version'").arg(version()) - - - << // The ResourceEvent table saves the Opened/Closed event pairs for - // a resource. The Accessed event is mapped to those. - // Focussing events are not stored in order not to get a - // huge database file and to lessen writes to the disk. - QStringLiteral("CREATE TABLE IF NOT EXISTS ResourceEvent (" - "usedActivity TEXT, " - "initiatingAgent TEXT, " - "targettedResource TEXT, " - "start INTEGER, " - "end INTEGER " - ")") - - << // The ResourceScoreCache table stores the calcualted scores - // for resources based on the recorded events. - QStringLiteral("CREATE TABLE IF NOT EXISTS ResourceScoreCache (" - "usedActivity TEXT, " - "initiatingAgent TEXT, " - "targettedResource TEXT, " - "scoreType INTEGER, " - "cachedScore FLOAT, " - "firstUpdate INTEGER, " - "lastUpdate INTEGER, " - "PRIMARY KEY(usedActivity, initiatingAgent, targettedResource)" - ")") - - - << // @since 2014.05.05 - // The ResourceLink table stores the information, formerly kept by - // Nepomuk, of which resources are linked to which activities. - // The additional features compared to the old days are - // the ability to limit the link to specific applications, and - // to create global links. - QStringLiteral("CREATE TABLE IF NOT EXISTS ResourceLink (" - "usedActivity TEXT, " - "initiatingAgent TEXT, " - "targettedResource TEXT, " - "PRIMARY KEY(usedActivity, initiatingAgent, targettedResource)" - ")") - - << // @since 2015.01.18 - // The ResourceInfo table stores the collected information about a - // resource that is not agent nor activity related like the - // title and the mime type. - // If these are automatically retrieved (works for files), the - // flag is set to true. This is done for the agents to be able to - // override these. - QStringLiteral("CREATE TABLE IF NOT EXISTS ResourceInfo (" - "targettedResource TEXT, " - "title TEXT, " - "mimetype TEXT, " - "autoTitle INTEGER, " - "autoMimetype INTEGER, " - "PRIMARY KEY(targettedResource)" - ")") - - ; -} - -// TODO: This will require some refactoring after we introduce more databases -QString defaultPath() -{ - return QStandardPaths::writableLocation( - QStandardPaths::GenericDataLocation) - + QStringLiteral("/kactivitymanagerd/resources/database"); -} - -const char *overrideFlagProperty = "org.kde.KActivities.ResourcesDatabase.overrideDatabase"; -const char *overrideFileProperty = "org.kde.KActivities.ResourcesDatabase.overrideDatabaseFile"; - -QString path() -{ - auto app = QCoreApplication::instance(); - - return - (app->property(overrideFlagProperty).toBool()) ? - app->property(overrideFileProperty).toString() : - defaultPath(); -} - -void overridePath(const QString &path) -{ - auto app = QCoreApplication::instance(); - - app->setProperty(overrideFlagProperty, true); - app->setProperty(overrideFileProperty, path); -} - -void initSchema(Database &database) -{ - QString dbSchemaVersion; - - auto query = database.execQuery( - QStringLiteral("SELECT value FROM SchemaInfo WHERE key = 'version'"), - /* ignore error */ true); - - if (query.next()) { - dbSchemaVersion = query.value(0).toString(); - } - - // Early bail-out if the schema is up-to-date - if (dbSchemaVersion == version()) { - return; - } - - // Transition to KF5: - // We left the world of Nepomuk, and all the ontologies went - // across the sea to the Undying Lands. - // This needs to be done before executing the schema() queries - // so that we do not create new (empty) tables and block these - // queries from being executed. - if (dbSchemaVersion < QStringLiteral("2014.04.14")) { - database.execQuery( - QStringLiteral("ALTER TABLE nuao_DesktopEvent RENAME TO ResourceEvent"), - /* ignore error */ true); - database.execQuery( - QStringLiteral("ALTER TABLE kext_ResourceScoreCache RENAME TO ResourceScoreCache"), - /* ignore error */ true); - } - - database.execQueries(ResourcesDatabaseSchema::schema()); - - // We can not allow empty fields for activity and agent, they need to - // be at least magic values. These do not change the structure - // of the database, but the old data. - if (dbSchemaVersion < QStringLiteral("2015.02.09")) { - const QString updateActivity = - QStringLiteral("SET usedActivity=':global' " - "WHERE usedActivity IS NULL OR usedActivity = ''"); - - const QString updateAgent = - QStringLiteral("SET initiatingAgent=':global' " - "WHERE initiatingAgent IS NULL OR initiatingAgent = ''"); - - // When the activity field was empty, it meant the file was - // linked to all activities (aka :global) - database.execQuery("UPDATE ResourceLink " + updateActivity); - - // When the agent field was empty, it meant the file was not - // linked to a specified agent (aka :global) - database.execQuery("UPDATE ResourceLink " + updateAgent); - - // These were not supposed to be empty, but in the case they were, - // deal with them as well - database.execQuery("UPDATE ResourceEvent " + updateActivity); - database.execQuery("UPDATE ResourceEvent " + updateAgent); - database.execQuery("UPDATE ResourceScoreCache " + updateActivity); - database.execQuery("UPDATE ResourceScoreCache " + updateAgent); - - } -} - -} // namespace Common -} // namespace ResourcesDatabaseSchema - diff --git a/libs/kactivities-stats/src/common/dbus/common.h b/libs/kactivities-stats/src/common/dbus/common.h deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/common.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012, 2013, 2014 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef DBUS_COMMON_H -#define DBUS_COMMON_H - -#include -#include - -#define KAMD_DBUS_SERVICE \ - QStringLiteral("org.kde.ActivityManager") - -#define KAMD_DBUS_OBJECT_PATH(A) \ - QLatin1String("/ActivityManager/" #A) - -#define KAMD_DBUS_OBJECT(A) \ - QLatin1String("org.kde.ActivityManager." #A) - -#define KAMD_DBUS_INTERFACE(OBJECT_PATH, OBJECT, PARENT) \ - QDBusInterface(KAMD_DBUS_SERVICE, \ - KAMD_DBUS_OBJECT_PATH(OBJECT_PATH), \ - KAMD_DBUS_OBJECT(OBJECT), \ - QDBusConnection::sessionBus(), \ - PARENT) - -#define KAMD_DECL_DBUS_INTERFACE(VAR, OBJECT_PATH, OBJECT) \ - QDBusInterface VAR(KAMD_DBUS_SERVICE, \ - KAMD_DBUS_OBJECT_PATH(OBJECT_PATH), \ - KAMD_DBUS_OBJECT(OBJECT), \ - QDBusConnection::sessionBus(), \ - Q_NULLPTR) - -#define KAMD_DBUS_CLASS_INTERFACE(OBJECT_PATH, OBJECT, PARENT) \ - org::kde::ActivityManager::OBJECT( \ - KAMD_DBUS_SERVICE, \ - KAMD_DBUS_OBJECT_PATH(OBJECT_PATH), \ - QDBusConnection::sessionBus(), \ - PARENT) - -#endif // DBUS_COMMON_H - diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.h b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.h deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.h +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KAMD_ACTIVITIES_DBUS_H -#define KAMD_ACTIVITIES_DBUS_H - -#include -#include -#include -#include - -struct ActivityInfo { - QString id; - QString name; - QString description; - QString icon; - int state; - - ActivityInfo(const QString &id = QString(), - const QString &name = QString(), - const QString &description = QString(), - const QString &icon = QString(), - int state = 0) - : id(id) - , name(name) - , description(description) - , icon(icon) - , state(state) - { - } - - bool operator<(const ActivityInfo &other) const - { - return id < other.id; - } - - bool operator==(const ActivityInfo &other) const - { - return id == other.id; - } -}; - -typedef QList ActivityInfoList; - -Q_DECLARE_METATYPE(ActivityInfo) -Q_DECLARE_METATYPE(ActivityInfoList) - -QDBusArgument &operator<<(QDBusArgument &arg, const ActivityInfo); -const QDBusArgument &operator>>(const QDBusArgument &arg, ActivityInfo &rec); - -QDebug operator<<(QDebug dbg, const ActivityInfo &r); - -#endif // KAMD_ACTIVITIES_DBUS_H diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.cpp b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (C) 2010, 2011, 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "org.kde.ActivityManager.Activities.h" - -#include -#include - -namespace details { - -class ActivityInfoStaticInit { -public: - ActivityInfoStaticInit() - { - qDBusRegisterMetaType(); - qDBusRegisterMetaType(); - } - - static ActivityInfoStaticInit _instance; -}; - -ActivityInfoStaticInit ActivityInfoStaticInit::_instance; - -} // namespace details - -QDBusArgument &operator<<(QDBusArgument &arg, const ActivityInfo r) -{ - arg.beginStructure(); - - arg << r.id; - arg << r.name; - arg << r.description; - arg << r.icon; - arg << r.state; - - arg.endStructure(); - - return arg; -} - -const QDBusArgument &operator>>(const QDBusArgument &arg, ActivityInfo &r) -{ - arg.beginStructure(); - - arg >> r.id; - arg >> r.name; - arg >> r.description; - arg >> r.icon; - arg >> r.state; - - arg.endStructure(); - - return arg; -} - -QDebug operator<<(QDebug dbg, const ActivityInfo &r) -{ - dbg << "ActivityInfo(" << r.id << r.name << ")"; - return dbg.space(); -} diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.xml b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.xml deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Activities.xml +++ /dev/null @@ -1,115 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Application.xml b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Application.xml deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Application.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - - diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Features.xml b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Features.xml deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Features.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Resources.xml b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Resources.xml deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.Resources.xml +++ /dev/null @@ -1,23 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.ResourcesLinking.xml b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.ResourcesLinking.xml deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.ResourcesLinking.xml +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.ResourcesScoring.xml b/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.ResourcesScoring.xml deleted file mode 100644 --- a/libs/kactivities-stats/src/common/dbus/org.kde.ActivityManager.ResourcesScoring.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/libs/kactivities-stats/src/common/specialvalues.h b/libs/kactivities-stats/src/common/specialvalues.h deleted file mode 100644 --- a/libs/kactivities-stats/src/common/specialvalues.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef SPECIALVALUES_H -#define SPECIALVALUES_H - -#include - -#define GLOBAL_ACTIVITY_TAG QStringLiteral(":global") -#define ANY_ACTIVITY_TAG QStringLiteral(":any") -#define CURRENT_ACTIVITY_TAG QStringLiteral(":current") - -#define GLOBAL_AGENT_TAG QStringLiteral(":global") -#define ANY_AGENT_TAG QStringLiteral(":any") -#define CURRENT_AGENT_TAG QStringLiteral(":current") - -#define ANY_TYPE_TAG QStringLiteral(":any") - - -#endif // SPECIALVALUES_H - diff --git a/libs/kactivities-stats/src/lib/CMakeLists.txt b/libs/kactivities-stats/src/lib/CMakeLists.txt deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -# vim:set softtabstop=3 shiftwidth=3 tabstop=3 expandtab: - -add_subdirectory (stats) - diff --git a/libs/kactivities-stats/src/lib/stats/CMakeLists.txt b/libs/kactivities-stats/src/lib/stats/CMakeLists.txt deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/CMakeLists.txt +++ /dev/null @@ -1,144 +0,0 @@ -# vim:set softtabstop=3 shiftwidth=3 tabstop=3 expandtab: - -project (KActivitiesStats) - -find_package (Qt5 REQUIRED NO_MODULE COMPONENTS Sql) -find_package (KF5Config ${KF5_DEP_VERSION} CONFIG REQUIRED) - -set ( - KActivitiesStats_LIB_SRCS - - query.cpp - terms.cpp - resultset.cpp - resultwatcher.cpp - resultmodel.cpp - activitiessync_p.cpp - cleaning.cpp - - ${KACTIVITIES_CURRENT_ROOT_SOURCE_DIR}/src/common/database/Database.cpp - ${KACTIVITIES_CURRENT_ROOT_SOURCE_DIR}/src/common/database/schema/ResourcesDatabaseSchema.cpp - ${KACTIVITIES_CURRENT_ROOT_SOURCE_DIR}/src/utils/qsqlquery_iterator.cpp - - version.cpp - ) - -qt5_add_dbus_interface ( - KActivitiesStats_LIB_SRCS - - ${KACTIVITIES_CURRENT_ROOT_SOURCE_DIR}/src/common/dbus/org.kde.ActivityManager.ResourcesScoring.xml - resourcesscoring_interface - ) - -qt5_add_dbus_interface ( - KActivitiesStats_LIB_SRCS - - ${KACTIVITIES_CURRENT_ROOT_SOURCE_DIR}/src/common/dbus/org.kde.ActivityManager.ResourcesLinking.xml - resourceslinking_interface - ) - - - -add_library ( - KF5ActivitiesExperimentalStats SHARED - ${KActivitiesStats_LIB_SRCS} - ) -add_library(KF5::ActivitiesExperimentalStats ALIAS KF5ActivitiesExperimentalStats) - -include_directories ( - ${KACTIVITIES_CURRENT_ROOT_SOURCE_DIR}/src - ${KDBusAddons_INCLUDE_DIR} - ) - -set_target_properties ( - KF5ActivitiesExperimentalStats - PROPERTIES - VERSION "0.0.1" - SOVERSION "1" - EXPORT_NAME ActivitiesExperimentalStats - ) - -target_link_libraries ( - KF5ActivitiesExperimentalStats - PUBLIC - Qt5::Core - PRIVATE - Qt5::DBus - Qt5::Sql - KF5::Activities - KF5::DBusAddons - KF5::ConfigCore - ) - -target_include_directories ( - KF5ActivitiesExperimentalStats - INTERFACE "$" - ) - -# install -generate_export_header (KF5ActivitiesExperimentalStats BASE_NAME KActivitiesStats) - -ecm_generate_headers ( - KActivitiesStats_CamelCase_HEADERS - HEADER_NAMES - Query - Terms - ResultSet - ResultWatcher - ResultModel - Cleaning - Version - - PREFIX KActivitiesExperimentalStats - REQUIRED_HEADERS KActivitiesStats_HEADERS -) - -if (NOT KACTIVITIES_INSTALL_EXPERIMENTAL_HEADERS) - set (SKIP_NAMELINK LIBRARY NAMELINK_SKIP) -endif () - -install ( - TARGETS KF5ActivitiesExperimentalStats - EXPORT KF5ActivitiesExperimentalStatsLibraryTargets - ${SKIP_NAMELINK} - ${KF5_INSTALL_TARGETS_DEFAULT_ARGS} - ) - -if (KACTIVITIES_INSTALL_EXPERIMENTAL_HEADERS) - install ( - FILES ${KActivitiesStats_CamelCase_HEADERS} - DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF5}/KActivitiesStats/KActivities/Experimental/Stats - COMPONENT Devel - ) - - install ( - FILES ${KActivitiesStats_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/kactivitiesstats_export.h - DESTINATION ${KDE_INSTALL_INCLUDEDIR_KF5}/KActivitiesStats/kactivitiesexperimentalstats - COMPONENT Devel - ) - - if (NOT WIN32) - configure_file ( - ${CMAKE_CURRENT_SOURCE_DIR}/libKActivitiesExperimentalStats.pc.cmake - ${CMAKE_CURRENT_BINARY_DIR}/libKActivitiesExperimentalStats.pc - ) - install ( - FILES ${CMAKE_CURRENT_BINARY_DIR}/libKActivitiesExperimentalStats.pc - DESTINATION ${KDE_INSTALL_LIBDIR}/pkgconfig - ) - endif () - - include (ECMGeneratePriFile) - ecm_generate_pri_file ( - BASE_NAME KActivitiesExperimentalStats - LIB_NAME KF5ActivitiesExperimentalStats - DEPS "KDBusAddons" - FILENAME_VAR PRI_FILENAME INCLUDE_INSTALL_DIR ${KF5_INCLUDE_INSTALL_DIR}/KActivitiesExperimentalStats - ) - install ( - FILES ${PRI_FILENAME} - DESTINATION ${ECM_MKSPECS_INSTALL_DIR} - ) -endif () - - diff --git a/libs/kactivities-stats/src/lib/stats/activitiessync_p.h b/libs/kactivities-stats/src/lib/stats/activitiessync_p.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/activitiessync_p.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef ACTIVITIES_SYNC_P_H -#define ACTIVITIES_SYNC_P_H - -#include -#include - -#include - -namespace ActivitiesSync { - - typedef std::shared_ptr ConsumerPtr; - - QString currentActivity(ConsumerPtr &activities); - -} // namespace ActivitiesSync - -#endif // ACTIVITIES_SYNC_P_H - diff --git a/libs/kactivities-stats/src/lib/stats/activitiessync_p.cpp b/libs/kactivities-stats/src/lib/stats/activitiessync_p.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/activitiessync_p.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "activitiessync_p.h" - -#include - -namespace ActivitiesSync { - typedef std::shared_ptr ConsumerPtr; - - ConsumerPtr instance() - { - static std::mutex s_instanceMutex; - static std::weak_ptr s_instance; - - std::unique_lock locker; - - auto ptr = s_instance.lock(); - - if (!ptr) { - ptr = std::make_shared(); - s_instance = ptr; - } - - return ptr; - - } - - QString currentActivity(ConsumerPtr &activities) - { - // We need to get the current activity synchonously, - // this means waiting for the service to be available. - // It should not introduce blockages since there usually - // is a global activity cache in applications that care - // about activities. - - if (!activities) { - activities = instance(); - } - - while (activities->serviceStatus() == KActivities::Consumer::Unknown) { - QCoreApplication::instance()->processEvents(); - } - - return activities->currentActivity(); - } - -} // namespace ActivitiesSync - diff --git a/libs/kactivities-stats/src/lib/stats/cleaning.h b/libs/kactivities-stats/src/lib/stats/cleaning.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/cleaning.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef CLEANING_H -#define CLEANING_H - -#include -#include "terms.h" -#include "query.h" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -/** - * Forget the resource(s) for the specified activity and agent - */ -void KACTIVITIESSTATS_EXPORT forgetResource(Terms::Activity activity, - Terms::Agent agent, - const QString &resource); - -enum KACTIVITIESSTATS_EXPORT TimeUnit { - Hours, - Days, - Months -}; - -/** - * Forget recent stats for the specified activity and time - */ -void KACTIVITIESSTATS_EXPORT forgetRecentStats(Terms::Activity activity, - int count, - TimeUnit what); - -/** - * Forget events that are older than the specified number of months - */ -void KACTIVITIESSTATS_EXPORT forgetEarlierStats(Terms::Activity activity, - int months); - -void KACTIVITIESSTATS_EXPORT forgetResources(const Query &query); - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -#endif // CLEANING_H - diff --git a/libs/kactivities-stats/src/lib/stats/cleaning.cpp b/libs/kactivities-stats/src/lib/stats/cleaning.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/cleaning.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - - -#include -#include -#include - -#include "cleaning.h" -#include "common/dbus/common.h" - -namespace KActivities { -namespace Experimental { -namespace Stats { - - -void forgetResource(Terms::Activity activities, Terms::Agent agents, - const QString &resource) -{ - KAMD_DECL_DBUS_INTERFACE(scoring, Resources/Scoring, ResourcesScoring); - for (const auto& activity: activities.values) { - for (const auto& agent: agents.values) { - scoring.call(QStringLiteral("DeleteStatsForResource"), activity, agent, resource); - } - } -} - -void forgetResources(const Query &query) -{ - KAMD_DECL_DBUS_INTERFACE(scoring, Resources/Scoring, ResourcesScoring); - for (const auto& activity: query.activities()) { - for (const auto& agent: query.agents()) { - for (const auto& urlFilter: query.urlFilters()) { - scoring.call(QStringLiteral("DeleteStatsForResource"), activity, agent, urlFilter); - } - } - } -} - -void forgetRecentStats(Terms::Activity activities, int count, TimeUnit what) -{ - KAMD_DECL_DBUS_INTERFACE(scoring, Resources/Scoring, ResourcesScoring); - for (const auto& activity: activities.values) { - scoring.call(QStringLiteral("DeleteRecentStats"), activity, count, - what == Hours ? "h" : - what == Days ? "d" : - "m" - ); - } -} - -void forgetEarlierStats(Terms::Activity activities, int months) -{ - KAMD_DECL_DBUS_INTERFACE(scoring, Resources/Scoring, ResourcesScoring); - for (const auto& activity: activities.values) { - scoring.call(QStringLiteral("DeleteEarlierStats"), activity, months); - } -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - diff --git a/libs/kactivities-stats/src/lib/stats/libKActivitiesExperimentalStats.pc.cmake b/libs/kactivities-stats/src/lib/stats/libKActivitiesExperimentalStats.pc.cmake deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/libKActivitiesExperimentalStats.pc.cmake +++ /dev/null @@ -1,12 +0,0 @@ -prefix=${CMAKE_INSTALL_PREFIX} -exec_prefix=${BIN_INSTALL_DIR} -libdir=${LIB_INSTALL_DIR} -includedir=${INCLUDE_INSTALL_DIR} - -Name: libKActivitiesExperimentalStats -Description: libKActivitiesStats is a C++ library for using KDE activities -URL: http://www.kde.org -Requires: -Version: ${KACTIVITIESSTATS_LIB_VERSION_STRING} -Libs: -L${LIB_INSTALL_DIR} -lKActivitiesExperimentalStats -Cflags: -I${INCLUDE_INSTALL_DIR} diff --git a/libs/kactivities-stats/src/lib/stats/query.h b/libs/kactivities-stats/src/lib/stats/query.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/query.h +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KACTIVITIES_STATS_QUERY_H -#define KACTIVITIES_STATS_QUERY_H - -#include - -#ifdef Q_COMPILER_INITIALIZER_LISTS -#include -#endif - -#include -#include - -#include "kactivitiesstats_export.h" - -#include "terms.h" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -class QueryPrivate; - -/** - * Class which defines what resource statistics should be - * returned. - * - * By default, limit will be set to 10. - */ -class KACTIVITIESSTATS_EXPORT Query { -public: - Query(Terms::Select selection = Terms::AllResources); - - // The damned rule of five minus one :) - Query(Query && source); - Query(const Query &source); - Query &operator= (Query source); - ~Query(); - - // Not all are born equal - bool operator== (const Query &right) const; - bool operator!= (const Query &right) const; - - Terms::Select selection() const; - QStringList types() const; - QStringList agents() const; - QStringList activities() const; - QStringList urlFilters() const; - Terms::Order ordering() const; - int offset() const; - int limit() const; - - void setSelection(Terms::Select selection); - void addTypes(const QStringList &types); - void addAgents(const QStringList &agents); - void addActivities(const QStringList &activities); - void addUrlFilters(const QStringList &urlFilters); - void setOrdering(Terms::Order ordering); - void setOffset(int offset); - void setLimit(int limit); - - void clearTypes(); - void clearAgents(); - void clearActivities(); - void clearUrlFilters(); - - void removeTypes(const QStringList &types); - void removeAgents(const QStringList &agents); - void removeActivities(const QStringList &activities); - void removeUrlFilters(const QStringList &urlFilters); - -private: - inline void addTerm(const Terms::Type &term) - { - addTypes(term.values); - } - - inline void addTerm(const Terms::Agent &term) - { - addAgents(term.values); - } - - inline void addTerm(const Terms::Activity &term) - { - addActivities(term.values); - } - - inline void addTerm(const Terms::Url &term) - { - addUrlFilters(term.values); - } - - inline void addTerm(Terms::Order ordering) - { - setOrdering(ordering); - } - - inline void addTerm(Terms::Select selection) - { - setSelection(selection); - } - - inline void addTerm(Terms::Limit limit) - { - setLimit(limit.value); - } - - inline void addTerm(Terms::Offset offset) - { - setOffset(offset.value); - } - -public: - - template - friend - inline Query operator| (const Query &query, Term &&term) - { - Query result(query); - result.addTerm(term); - return result; - } - - template - friend - inline Query operator| (Query &&query, Term &&term) - { - query.addTerm(term); - return query; - } - -private: - QueryPrivate* d; -}; - -template -inline Query operator| (Terms::Select selection, Term &&term) -{ - return Query(selection) | term; -} - - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Query &query); - -#endif // KACTIVITIES_STATS_QUERY_H - diff --git a/libs/kactivities-stats/src/lib/stats/query.cpp b/libs/kactivities-stats/src/lib/stats/query.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/query.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "query.h" -#include - -namespace KActivities { -namespace Experimental { -namespace Stats { - -namespace details { - inline void validateTypes(QStringList &types) - { - // Nothing at the moment - Q_UNUSED(types); - } - - inline void validateAgents(QStringList &agents) - { - // Nothing at the moment - Q_UNUSED(agents); - } - - inline void validateActivities(QStringList &activities) - { - // Nothing at the moment - Q_UNUSED(activities); - } - - inline void validateUrlFilters(QStringList &urlFilters) - { - auto i = urlFilters.begin(); - const auto end = urlFilters.end(); - - for (; i != end ; ++i) { - i->replace(QLatin1String("'"), QLatin1String("")); - } - } - -} // namespace details - -class QueryPrivate { -public: - QueryPrivate() - : ordering(Terms::HighScoredFirst) - , limit(10) - , offset(0) - { - } - - Terms::Select selection; - QStringList types; - QStringList agents; - QStringList activities; - QStringList urlFilters; - Terms::Order ordering; - int limit; - int offset; -}; - -Query::Query(Terms::Select selection) - : d(new QueryPrivate()) -{ - d->selection = selection; -} - -Query::Query(Query &&source) - : d(nullptr) -{ - std::swap(d, source.d); -} - -Query::Query(const Query &source) - : d(new QueryPrivate(*source.d)) -{ -} - -Query &Query::operator= (Query source) -{ - std::swap(d, source.d); - return *this; -} - - -Query::~Query() -{ - delete d; -} - -bool Query::operator== (const Query &right) const -{ - return selection() == right.selection() && - types() == right.types() && - agents() == right.agents() && - activities() == right.activities() && - selection() == right.selection() && - urlFilters() == right.urlFilters(); -} - -bool Query::operator!= (const Query &right) const -{ - return !(*this == right); -} - -#define IMPLEMENT_QUERY_LIST_FIELD(WHAT, What, Default) \ - void Query::add##WHAT(const QStringList &What) \ - { \ - d->What << What; \ - details::validate##WHAT(d->What); \ - } \ - \ - QStringList Query::What() const \ - { \ - return d->What.size() ? d->What : Default; \ - } \ - \ - void Query::clear##WHAT() \ - { \ - d->What.clear(); \ - } - -IMPLEMENT_QUERY_LIST_FIELD(Types, types, QStringList(":any")) -IMPLEMENT_QUERY_LIST_FIELD(Agents, agents, QStringList(":current")) -IMPLEMENT_QUERY_LIST_FIELD(Activities, activities, QStringList(":current")) -IMPLEMENT_QUERY_LIST_FIELD(UrlFilters, urlFilters, QStringList("*")) - -#undef IMPLEMENT_QUERY_LIST_FIELD - -void Query::setOrdering(Terms::Order ordering) -{ - d->ordering = ordering; -} - -void Query::setSelection(Terms::Select selection) -{ - d->selection = selection; -} - -void Query::setLimit(int limit) -{ - d->limit = limit; -} - -void Query::setOffset(int offset) -{ - d->offset = offset; -} - -Terms::Order Query::ordering() const -{ - return d->ordering; -} - -Terms::Select Query::selection() const -{ - return d->selection; -} - -int Query::limit() const -{ - return d->limit; -} - -int Query::offset() const -{ - Q_ASSERT_X(d->limit > 0, "Query::offset", "Offset can only be specified if limit is set"); - return d->offset; -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -namespace KAStats = KActivities::Experimental::Stats; - -QDebug operator<<(QDebug dbg, const KAStats::Query &query) -{ - using namespace KAStats::Terms; - - dbg.nospace() - << "Query { " - << query.selection() - << ", " << Type(query.types()) - << ", " << Agent(query.agents()) - << ", " << Activity(query.activities()) - << ", " << Url(query.urlFilters()) - << ", " << query.ordering() - << " }"; - return dbg; -} diff --git a/libs/kactivities-stats/src/lib/stats/resultmodel.h b/libs/kactivities-stats/src/lib/stats/resultmodel.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultmodel.h +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KACTIVITIES_STATS_RESULTMODEL_H -#define KACTIVITIES_STATS_RESULTMODEL_H - -// Qt -#include -#include - -// Local -#include "query.h" - -class QModelIndex; -class QDBusPendingCallWatcher; - -class KConfigGroup; - -namespace KActivities { -namespace Experimental { -namespace Stats { - -class ResultModelPrivate; - -/** - * ResultModel - */ - -class KACTIVITIESSTATS_EXPORT ResultModel : public QAbstractListModel { - Q_OBJECT - -public: - ResultModel(Query query, QObject *parent = 0); - ResultModel(Query query, const QString &clientId, QObject *parent = 0); - virtual ~ResultModel(); - - enum Roles { - ResourceRole = Qt::UserRole, - TitleRole = Qt::UserRole + 1, - ScoreRole = Qt::UserRole + 2, - FirstUpdateRole = Qt::UserRole + 3, - LastUpdateRole = Qt::UserRole + 4, - LinkStatusRole = Qt::UserRole + 5 - }; - - int rowCount(const QModelIndex &parent - = QModelIndex()) const Q_DECL_OVERRIDE; - QVariant data(const QModelIndex &item, - int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - QHash roleNames() const Q_DECL_OVERRIDE; - - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const Q_DECL_OVERRIDE; - - void fetchMore(const QModelIndex &parent) Q_DECL_OVERRIDE; - bool canFetchMore(const QModelIndex &parent) const Q_DECL_OVERRIDE; - - // TODO: BLOCKER Move these to libKActivities - void linkToActivity(const QUrl &resource, - const Terms::Activity &activity - = Terms::Activity(QStringList()), - const Terms::Agent &agent - = Terms::Agent(QStringList())); - - void unlinkFromActivity(const QUrl &resource, - const Terms::Activity &activity - = Terms::Activity(QStringList()), - const Terms::Agent &agent - = Terms::Agent(QStringList())); - -public Q_SLOTS: - /** - * Removes the specified resource from the history - */ - void forgetResource(const QString &resource); - - /** - * Removes the specified resource from the history - */ - void forgetResource(int row); - - /** - * Clears the history of all resources that match the current - * model query - */ - void forgetAllResources(); - - /** - * Moves the resource to the specified position. - * - * Note that this only applies to the linked resources - * since the recently/frequently used ones have - * their natural order. - * This requires the clientId to be specified on construction. - */ - void setResultPosition(const QString &resource, int position); - - /** - * Sort the items by title. - * - * Note that this only affects the linked resources - * since the recently/frequently used ones have - * their natural order. - * This requires the config to be specified on construction. - */ - void sortItems(Qt::SortOrder sortOrder); - -private: - friend class ResultModelPrivate; - ResultModelPrivate *const d; -}; - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -#endif // KACTIVITIES_STATS_RESULTMODEL_H - diff --git a/libs/kactivities-stats/src/lib/stats/resultmodel.cpp b/libs/kactivities-stats/src/lib/stats/resultmodel.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultmodel.cpp +++ /dev/null @@ -1,1013 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -// Self -#include "resultmodel.h" - -// Qt -#include -#include -#include -#include - -// STL and Boost -#include -#include -#include - -// KDE -#include -#include - -// Local -#include -#include -#include -#include -#include "resultset.h" -#include "resultwatcher.h" -#include "cleaning.h" -#include "kactivities/consumer.h" - -#include - -#define MAX_CHUNK_LOAD_SIZE 50 -#define MAX_RELOAD_CACHE_SIZE 50 - -#define QDBG qDebug() << "KActivitiesStats(" << (void*)this << ")" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -class ResultModelPrivate { -public: - ResultModelPrivate(Query query, const QString &clientId, ResultModel *parent) - : cache(this, clientId, query.limit()) - , query(query) - , watcher(query) - , hasMore(true) - , q(parent) - { - using Common::Database; - database = Database::instance(Database::ResourcesDatabase, Database::ReadOnly); - } - - enum Fetch { - FetchReset, // Remove old data and reload - FetchReload, // Update all data - FetchMore // Load more data if there is any - }; - - class Cache { //_ - public: - typedef QList Items; - - Cache(ResultModelPrivate *d, const QString &clientId, int limit) - : d(d) - , m_countLimit(limit) - , m_clientId(clientId) - { - if (!m_clientId.isEmpty()) { - m_configFile = new KConfig( - QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) - + QStringLiteral("/kactivitymanagerd-statsrc")); - - m_config = KConfigGroup(m_configFile, "ResultModel-OrderingFor-" + clientId); - - if (m_config.isValid()) { - m_fixedItems = m_config.readEntry("kactivitiesLinkedItemsOrder", - QStringList()); - } - - qDebug() << "Configuration activated " << m_configFile->name(); - } - } - - ~Cache() - { - delete m_configFile; - } - - inline int size() const - { - return m_items.size(); - } - - inline void setLinkedResultPosition(const QString &resource, - int position) - { - if (!m_config.isValid()) { - qWarning() << "We can not reorder the results, no clientId was specified"; - return; - } - - // Preconditions: - // - cache is ordered properly, first on the user's desired order, - // then on the query specified order - // - the resource that needs to be moved is already in the cache - // - the resource that needs to be moved is a linked resource, not - // one that comes from the stats (there are overly many - // corner-cases that need to be covered in order to support - // reordering of the statistics-based resources) - // - the new position for the resource is not outside of the cache - - qDebug() << "Searching for " << resource; - auto resourcePosition = find(resource); - qDebug() << "Was resource found? " << (bool)resourcePosition; - if (resourcePosition) { - qDebug() << "What is the status? " << resourcePosition.iterator->linkStatus(); - } - if (!resourcePosition - || resourcePosition.iterator->linkStatus() == ResultSet::Result::NotLinked) { - qWarning("Trying to reposition a resource that we do not have, or is not linked"); - return; - } - - // Lets make a list of linked items - we can only reorder them, - // not others - QStringList linkedItems; - - foreach (const ResultSet::Result &item, m_items) { - if (item.linkStatus() == ResultSet::Result::NotLinked) break; - linkedItems << item.resource(); - } - - // We can not accept the new position to be outside - // of the linked items area - if (position > linkedItems.size()) { - position = linkedItems.size(); - } - - auto oldPosition = linkedItems.indexOf(resource); - - kamd::utils::slide_one( - linkedItems.begin() + oldPosition, - linkedItems.begin() + position); - - m_fixedItems = linkedItems; - - m_config.writeEntry("kactivitiesLinkedItemsOrder", m_fixedItems); - m_config.sync(); - - // We are prepared to reorder the cache - d->repositionResult(resourcePosition, - d->destinationFor(*resourcePosition)); - } - - private: - ResultModelPrivate *const d; - - QList m_items; - int m_countLimit; - - QString m_clientId; - KConfig *m_configFile; - KConfigGroup m_config; - QStringList m_fixedItems; - - friend QDebug operator<< (QDebug out, const Cache &cache) - { - for (const auto& item: cache.m_items) { - out << "Cache item: " << item << "\n"; - } - - return out; - } - - public: - inline const QStringList &fixedItems() const - { - return m_fixedItems; - } - - //_ Fancy iterator, find, lowerBound - struct FindCacheResult { - Cache *const cache; - Items::iterator iterator; - int index; - - FindCacheResult(Cache *cache, Items::iterator iterator) - : cache(cache) - , iterator(iterator) - , index(std::distance(cache->m_items.begin(), iterator)) - { - } - - operator bool() const - { - return iterator != cache->m_items.end(); - } - - ResultSet::Result &operator*() const - { - return *iterator; - } - - ResultSet::Result *operator->() const - { - return &(*iterator); - } - - // const ResultSet::Result &operator*() const - // { - // return *iterator; - // } - // - // const ResultSet::Result *operator->() const - // { - // return &(*iterator); - // } - }; - - inline FindCacheResult find(const QString &resource) - { - using namespace kamd::utils::member_matcher; - using boost::find_if; - - return FindCacheResult( - this, find_if(m_items, member(&ResultSet::Result::resource) - == resource)); - } - - template - inline FindCacheResult lowerBound(What &&what, Predicate &&predicate) - { - return FindCacheResult( - this, boost::lower_bound(m_items, std::forward(what), - std::forward(predicate))); - } - - template - inline FindCacheResult lowerBound(Predicate &&predicate) - { - using namespace kamd::utils::member_matcher; - return FindCacheResult( - this, boost::lower_bound(m_items, _, - std::forward(predicate))); - } - //^ - - inline int indexOf(const FindCacheResult &result) - { - return std::distance(m_items.begin(), result.iterator); - } - - inline void insertAt(const FindCacheResult &at, - const ResultSet::Result &result) - { - m_items.insert(at.iterator, result); - } - - inline void removeAt(const FindCacheResult &at) - { - m_items.removeAt(at.index); - } - - inline const ResultSet::Result &operator[] (int index) const - { - return m_items[index]; - } - - inline void clear() - { - if (m_items.size() == 0) return; - - d->q->beginRemoveRows(QModelIndex(), 0, m_items.size()); - m_items.clear(); - d->q->endRemoveRows(); - } - - // Algorithm to calculate the edit operations to allow - //_ replaceing items without model reset - inline void replace(const Items &newItems, int from = 0) - { - using namespace kamd::utils::member_matcher; - -#if 0 - QDBG << "===\nOld items {"; - for (const auto& item: m_items) { - QDBG << item; - } - QDBG << "}"; - - QDBG << "New items to be added at " << from << " {"; - for (const auto& item: newItems) { - QDBG << item; - } - QDBG << "}"; -#endif - - - // Based on 'The string to string correction problem - // with block moves' paper by Walter F. Tichy - // - // In essence, it goes like this: - // - // Take the first element from the new list, and try to find - // it in the old one. If you can not find it, it is a new item - // item - send the 'inserted' event. - // If you did find it, test whether the following items also - // match. This detects blocks of items that have moved. - // - // In this example, we find 'b', and then detect the rest of the - // moved block 'b' 'c' 'd' - // - // Old items: a[b c d]e f g - // ^ - // / - // New items: [b c d]a f g - // - // After processing one block, just repeat until the end of the - // new list is reached. - // - // Then remove all remaining elements from the old list. - // - // The main addition here compared to the original papers is that - // our 'strings' can not hold two instances of the same element, - // and that we support updating from arbitrary position. - - auto newBlockStart = newItems.cbegin(); - - // How many items should we add? - // This should remove the need for post-replace-trimming - // in the case where somebody called this with too much new items. - const int maxToReplace = m_countLimit - from; - - if (maxToReplace <= 0) return; - - const auto newItemsEnd = - newItems.size() <= maxToReplace ? newItems.cend() : - newItems.cbegin() + maxToReplace; - - - // Finding the blocks until we reach the end of the newItems list - // - // from = 4 - // Old items: X Y Z U a b c d e f g - // ^ oldBlockStart points to the first element - // of the currently processed block in the old list - // - // New items: _ _ _ _ b c d a f g - // ^ newBlockStartIndex is the index of the first - // element of the block that is currently being - // processed (with 'from' offset) - - while (newBlockStart != newItemsEnd) { - - const int newBlockStartIndex - = from + std::distance(newItems.cbegin(), newBlockStart); - - const auto oldBlockStart = std::find_if( - m_items.begin() + from, m_items.end(), - member(&ResultSet::Result::resource) == newBlockStart->resource()); - - if (oldBlockStart == m_items.end()) { - // This item was not found in the old cache, so we are - // inserting a new item at the same position it had in - // the newItems array - d->q->beginInsertRows(QModelIndex(), newBlockStartIndex, - newBlockStartIndex); - - m_items.insert(newBlockStartIndex, *newBlockStart); - d->q->endInsertRows(); - - // This block contained only one item, move on to find - // the next block - it starts from the next item - ++newBlockStart; - - } else { - // We are searching for a block of matching items. - // This is a reimplementation of std::mismatch that - // accepts two complete ranges that is available only - // since C++14, so we can not use it. - auto newBlockEnd = newBlockStart; - auto oldBlockEnd = oldBlockStart; - - while (newBlockEnd != newItemsEnd && - oldBlockEnd != m_items.end() && - newBlockEnd->resource() == oldBlockEnd->resource()) { - ++newBlockEnd; - ++oldBlockEnd; - } - - // We have found matching blocks - // [newBlockStart, newBlockEnd) and [oldBlockStart, newBlockEnd) - const int oldBlockStartIndex - = std::distance(m_items.begin() + from, oldBlockStart); - - const int blockSize - = std::distance(oldBlockStart, oldBlockEnd); - - if (oldBlockStartIndex != newBlockStartIndex) { - // If these blocks do not have the same start, - // we need to send the move event. - - // Note: If there is a crash here, it means we - // are getting a bad query which has duplicate - // results - - d->q->beginMoveRows(QModelIndex(), oldBlockStartIndex, - oldBlockStartIndex + blockSize - 1, - QModelIndex(), newBlockStartIndex); - - // Moving the items from the old location to the new one - kamd::utils::slide( - oldBlockStart, oldBlockEnd, - m_items.begin() + newBlockStartIndex); - - d->q->endMoveRows(); - } - - // Skip all the items in this block, and continue with - // the search - newBlockStart = newBlockEnd; - } - } - - // We have avoided the need for trimming for the most part, - // but if the newItems list was shorter than needed, we still - // need to trim the rest. - trim(from + newItems.size()); - - // Check whether we got an item representing a non-existent file, - // if so, schedule its removal from the database - for (const auto &item: newItems) { - if (item.resource().startsWith('/') && !QFile(item.resource()).exists()) { - d->q->forgetResource(item.resource()); - } - } - } - //^ - - inline void trim() - { - trim(m_countLimit); - } - - inline void trim(int limit) - { - if (m_items.size() <= limit) return; - - // Example: - // limit is 5, - // current cache (0, 1, 2, 3, 4, 5, 6, 7), size = 8 - // We need to delete from 5 to 7 - - d->q->beginRemoveRows(QModelIndex(), limit, m_items.size() - 1); - m_items.erase(m_items.begin() + limit, m_items.end()); - d->q->endRemoveRows(); - } - - } cache; //^ - - struct FixedItemsLessThan { - //_ Compartor that orders the linked items by user-specified order - typedef kamd::utils::member_matcher::placeholder placeholder; - - FixedItemsLessThan(const Cache &cache, - const QString &matchResource = QString()) - : cache(cache), matchResource(matchResource) - { - } - - bool compare (const QString &leftResource, const QString &rightResource) const - { - const bool hasLeft = cache.fixedItems().contains(leftResource); - const bool hasRight = cache.fixedItems().contains(rightResource); - - return - ( hasLeft && !hasRight) ? true : - (!hasLeft && hasRight) ? false : - ( hasLeft && hasRight) ? cache.fixedItems().indexOf(leftResource) < - cache.fixedItems().indexOf(rightResource) : - false; - } - - template - bool operator() (const T &left, placeholder) const - { - return compare(left.resource(), matchResource); - } - - template - bool operator() (placeholder, const T &right) const - { - return compare(matchResource, right.resource()); - } - - template - bool operator() (const T &left, const V &right) const - { - return compare(left.resource(), right.resource()); - } - - const Cache &cache; - const QString matchResource; - //^ - }; - - inline Cache::FindCacheResult destinationFor(const ResultSet::Result &result) - { - using namespace kamd::utils::member_matcher; - using namespace Terms; - - const auto resource = result.resource(); - const auto score = result.score(); - const auto firstUpdate = result.firstUpdate(); - const auto lastUpdate = result.lastUpdate(); - const auto linkStatus = result.linkStatus(); - - #define ORDER_BY(Field) member(&ResultSet::Result::Field) > Field - #define ORDER_BY_FULL(Field) \ - cache.lowerBound(FixedItemsLessThan(cache, resource) \ - && ORDER_BY(linkStatus) \ - && ORDER_BY(Field) \ - && ORDER_BY(resource)) - - const auto destination = - query.ordering() == HighScoredFirst ? ORDER_BY_FULL(score): - query.ordering() == RecentlyUsedFirst ? ORDER_BY_FULL(lastUpdate): - query.ordering() == RecentlyCreatedFirst ? ORDER_BY_FULL(firstUpdate): - /* otherwise */ ORDER_BY_FULL(resource) - ; - #undef ORDER_BY - #undef ORDER_BY_FULL - - return destination; - } - - inline void removeResult(const Cache::FindCacheResult &result) - { - q->beginRemoveRows(QModelIndex(), result.index, result.index); - cache.removeAt(result); - q->endRemoveRows(); - - fetch(cache.size(), 1); - } - - inline void repositionResult(const Cache::FindCacheResult &result, - const Cache::FindCacheResult &destination) - { - using kamd::utils::slide_one; - - // We already have the resource in the cache - // So, it is the time for a reshuffle - const int currentIndex = result.index; - - q->dataChanged(q->index(currentIndex), q->index(currentIndex)); - - bool moving - = q->beginMoveRows(QModelIndex(), currentIndex, currentIndex, - QModelIndex(), destination.index); - - slide_one(result.iterator, destination.iterator); - - if (moving) { - q->endMoveRows(); - } - } - - void reload() - { - fetch(FetchReload); - } - - void init() - { - using namespace std::placeholders; - - QObject::connect( - &watcher, &ResultWatcher::resultScoreUpdated, - q, std::bind(&ResultModelPrivate::onResultScoreUpdated, this, _1, _2, _3, _4)); - QObject::connect( - &watcher, &ResultWatcher::resultRemoved, - q, std::bind(&ResultModelPrivate::onResultRemoved, this, _1)); - QObject::connect( - &watcher, &ResultWatcher::resultLinked, - q, std::bind(&ResultModelPrivate::onResultLinked, this, _1)); - QObject::connect( - &watcher, &ResultWatcher::resultUnlinked, - q, std::bind(&ResultModelPrivate::onResultUnlinked, this, _1)); - - QObject::connect( - &watcher, &ResultWatcher::resourceTitleChanged, - q, std::bind(&ResultModelPrivate::onResourceTitleChanged, this, _1, _2)); - QObject::connect( - &watcher, &ResultWatcher::resourceMimetypeChanged, - q, std::bind(&ResultModelPrivate::onResourceMimetypeChanged, this, _1, _2)); - - QObject::connect( - &watcher, &ResultWatcher::resultsInvalidated, - q, std::bind(&ResultModelPrivate::reload, this)); - - if (query.activities().contains(CURRENT_ACTIVITY_TAG)) { - QObject::connect( - &activities, &KActivities::Consumer::currentActivityChanged, q, - std::bind(&ResultModelPrivate::onCurrentActivityChanged, this, _1)); - } - - fetch(FetchReset); - } - - void fetch(int from, int count) - { - using namespace Terms; - - if (from + count > query.limit()) { - count = query.limit() - from; - } - - if (count <= 0) return; - - // In order to see whether there are more results, we need to pass - // the count increased by one - ResultSet results(query | Offset(from) | Limit(count + 1)); - - auto it = results.begin(); - - Cache::Items newItems; - - while (count --> 0 && it != results.end()) { - newItems << *it; - ++it; - } - - hasMore = (it != results.end()); - - // We need to sort the new items for the linked resources - // user-defined reordering - if (query.selection() != Terms::UsedResources) { - std::stable_sort(newItems.begin(), newItems.end(), - FixedItemsLessThan(cache)); - } - - cache.replace(newItems, from); - } - - void fetch(Fetch mode) - { - if (mode == FetchReset) { - // Removing the previously cached data - // and loading all from scratch - cache.clear(); - - fetch(0, MAX_CHUNK_LOAD_SIZE); - - } else if (mode == FetchReload) { - if (cache.size() > MAX_RELOAD_CACHE_SIZE) { - // If the cache is big, we are pretending - // we were asked to reset the model - fetch(FetchReset); - - } else { - // We are only updating the currently - // cached items, nothing more - fetch(0, cache.size()); - - } - - } else { // FetchMore - // Load a new batch of data - fetch(cache.size(), MAX_CHUNK_LOAD_SIZE); - } - } - - void onResultScoreUpdated(const QString &resource, double score, - uint lastUpdate, uint firstUpdate) - { - using boost::lower_bound; - - QDBG << "ResultModelPrivate::onResultAdded " - << "result added:" << resource - << "score:" << score - << "last:" << lastUpdate - << "first:" << firstUpdate; - - // This can also be called when the resource score - // has been updated, so we need to check whether - // we already have it in the cache - const auto result = cache.find(resource); - - ResultSet::Result::LinkStatus linkStatus - = result ? result->linkStatus() - : ResultSet::Result::NotLinked; - - if (result) { - // We are only updating a result we already had, - // lets fill out the data and send the update signal. - // Move it if necessary. - - auto &item = *result.iterator; - - item.setScore(score); - item.setLinkStatus(linkStatus); - item.setLastUpdate(lastUpdate); - item.setFirstUpdate(firstUpdate); - - const auto destination = destinationFor(item); - - repositionResult(result, destination); - - } else { - // We do not have the resource in the cache, - // lets fill out the data and insert it - // at the desired position - - ResultSet::Result result; - result.setResource(resource); - - result.setTitle(" "); - result.setMimetype(" "); - fillTitleAndMimetype(result); - - result.setScore(score); - result.setLinkStatus(linkStatus); - result.setLastUpdate(lastUpdate); - result.setFirstUpdate(firstUpdate); - - const auto destination = destinationFor(result); - - q->beginInsertRows(QModelIndex(), destination.index, - destination.index); - - cache.insertAt(destination, result); - - q->endInsertRows(); - - cache.trim(); - } - } - - void onResultRemoved(const QString &resource) - { - const auto result = cache.find(resource); - - if (!result) return; - - if (query.selection() == Terms::UsedResources - || result->linkStatus() != ResultSet::Result::Linked) { - removeResult(result); - } - } - - void onResultLinked(const QString &resource) - { - const auto result = cache.find(resource); - - if (!result) return; - - if (query.selection() == Terms::LinkedResources) { - onResultScoreUpdated(resource, 0, 0, 0); - - } else if (query.selection() == Terms::AllResources) { - result->setLinkStatus(ResultSet::Result::Linked); - repositionResult(result, destinationFor(*result)); - - } - } - - void onResultUnlinked(const QString &resource) - { - const auto result = cache.find(resource); - - if (!result) return; - - if (query.selection() == Terms::LinkedResources) { - removeResult(result); - - } else if (query.selection() == Terms::AllResources) { - result->setLinkStatus(ResultSet::Result::NotLinked); - repositionResult(result, destinationFor(*result)); - - } - } - - Query query; - ResultWatcher watcher; - bool hasMore; - - KActivities::Consumer activities; - Common::Database::Ptr database; - - //_ Title and mimetype functions - void fillTitleAndMimetype(ResultSet::Result &result) - { - auto query = database->execQuery( - "SELECT " - "title, mimetype " - "FROM " - "ResourceInfo " - "WHERE " - "targettedResource = '" + result.resource() + "'" - ); - - // Only one item at most - for (const auto &item: query) { - result.setTitle(item["title"].toString()); - result.setMimetype(item["mimetype"].toString()); - } - } - - void onResourceTitleChanged(const QString &resource, const QString &title) - { - const auto result = cache.find(resource); - - if (!result) return; - - result->setTitle(title); - - q->dataChanged(q->index(result.index), q->index(result.index)); - } - - void onResourceMimetypeChanged(const QString &resource, const QString &mimetype) - { - // TODO: This can add or remove items from the model - - const auto result = cache.find(resource); - - if (!result) return; - - result->setMimetype(mimetype); - - q->dataChanged(q->index(result.index), q->index(result.index)); - } - //^ - - void onCurrentActivityChanged(const QString &activity) - { - Q_UNUSED(activity); - // If the current activity has changed, and - // the query lists items for the ':current' one, - // reset the model (not a simple refresh this time) - if (query.activities().contains(CURRENT_ACTIVITY_TAG)) { - fetch(FetchReset); - } - } - -private: - ResultModel *const q; - -}; - -ResultModel::ResultModel(Query query, QObject *parent) - : QAbstractListModel(parent) - , d(new ResultModelPrivate(query, QString(), this)) -{ - d->init(); -} - -ResultModel::ResultModel(Query query, const QString &clientId, QObject *parent) - : QAbstractListModel(parent) - , d(new ResultModelPrivate(query, clientId, this)) -{ - d->init(); -} - -ResultModel::~ResultModel() -{ - delete d; -} - -QHash ResultModel::roleNames() const -{ - return { - { ResourceRole , "resource" }, - { TitleRole , "title" }, - { ScoreRole , "score" }, - { FirstUpdateRole , "created" }, - { LastUpdateRole , "modified" }, - { LinkStatusRole , "linkStatus" } - }; -} - -QVariant ResultModel::data(const QModelIndex &item, int role) const -{ - const auto row = item.row(); - - if (row < 0 || row >= d->cache.size()) return QVariant(); - - const auto &result = d->cache[row]; - - return role == Qt::DisplayRole ? ( - result.title() + " " + - result.resource() + " - " + - QString::number(result.linkStatus()) + " - " + - QString::number(result.score()) - ) - : role == ResourceRole ? result.resource() - : role == TitleRole ? result.title() - : role == ScoreRole ? result.score() - : role == FirstUpdateRole ? result.firstUpdate() - : role == LastUpdateRole ? result.lastUpdate() - : role == LinkStatusRole ? result.linkStatus() - : QVariant() - ; -} - -QVariant ResultModel::headerData(int section, Qt::Orientation orientation, - int role) const -{ - Q_UNUSED(section); - Q_UNUSED(orientation); - Q_UNUSED(role); - return QVariant(); -} - -int ResultModel::rowCount(const QModelIndex &parent) const -{ - return parent.isValid() ? 0 : d->cache.size(); -} - -void ResultModel::fetchMore(const QModelIndex &parent) -{ - if (parent.isValid()) return; - d->fetch(ResultModelPrivate::FetchMore); -} - -bool ResultModel::canFetchMore(const QModelIndex &parent) const -{ - return parent.isValid() ? false - : d->cache.size() >= d->query.limit() ? false - : d->hasMore; -} - -void ResultModel::forgetResource(const QString &resource) -{ - foreach (const QString &activity, d->query.activities()) { - foreach (const QString &agent, d->query.agents()) { - Stats::forgetResource( - activity, - agent == CURRENT_AGENT_TAG ? - QCoreApplication::applicationName() : agent, - resource); - } - } -} - -void ResultModel::forgetResource(int row) -{ - if (row >= d->cache.size()) return; - - foreach (const QString &activity, d->query.activities()) { - foreach (const QString &agent, d->query.agents()) { - Stats::forgetResource( - activity, - agent == CURRENT_AGENT_TAG ? - QCoreApplication::applicationName() : agent, - d->cache[row].resource()); - } - } -} - -void ResultModel::forgetAllResources() -{ - Stats::forgetResources(d->query); -} - -void ResultModel::setResultPosition(const QString &resource, int position) -{ - d->cache.setLinkedResultPosition(resource, position); -} - -void ResultModel::sortItems(Qt::SortOrder sortOrder) -{ - // TODO -} - -void ResultModel::linkToActivity(const QUrl &resource, - const Terms::Activity &activity, - const Terms::Agent &agent) -{ - d->watcher.linkToActivity(resource, activity, agent); -} - -void ResultModel::unlinkFromActivity(const QUrl &resource, - const Terms::Activity &activity, - const Terms::Agent &agent) -{ - d->watcher.unlinkFromActivity(resource, activity, agent); -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -// #include "resourcemodel.moc" - diff --git a/libs/kactivities-stats/src/lib/stats/resultset.h b/libs/kactivities-stats/src/lib/stats/resultset.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultset.h +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KACTIVITIES_STATS_RESULTSET -#define KACTIVITIES_STATS_RESULTSET - -#include "query.h" - -#include - -namespace KActivities { -namespace Experimental { -namespace Stats { - -class ResultSetPrivate; -class ResultSet_ResultPrivate; -class ResultSet_IteratorPrivate; - -/** - * Class that can query the KActivities usage tracking mechanism - * for resources. - * - * Note: It is important to note that you should not create a - * long-living instance of ResultSet. It might lock the database - * and break proper updating mechanisms. - */ -class KACTIVITIESSTATS_EXPORT ResultSet { -public: - /** - * Structure containing data of one of the results - */ - class Result { - public: - Result(); - ~Result(); - - Result(Result &&result); - Result(const Result &result); - Result &operator=(Result result); - - enum LinkStatus { - NotLinked = 0, - Unknown = 1, - Linked = 2 - }; - - QString resource() const; ///< URL of the resource - QString title() const; ///< Title of the resource, or URL if title is not known - QString mimetype() const; ///< Mimetype of the resource, or URL if title is not known - double score() const; ///< The score calculated based on the usage statistics - uint lastUpdate() const; ///< Timestamp of the last update - uint firstUpdate() const; ///< Timestamp of the first update - LinkStatus linkStatus() const; ///< Differentiates between linked and non-linked resources in mixed queries - - void setResource(QString resource); - void setTitle(QString title); - void setMimetype(QString mimetype); - void setScore(double score); - void setLastUpdate(uint lastUpdate); - void setFirstUpdate(uint firstUpdate); - void setLinkStatus(LinkStatus linkedStatus); - - private: - ResultSet_ResultPrivate * d; - }; - - /** - * ResultSet is a container. This notifies the generic algorithms - * from STLboost, and others of the contained type. - */ - typedef Result value_type; - - /** - * Creates the ResultSet from the specified query - */ - ResultSet(Query query); - - ResultSet(ResultSet && source); - ResultSet(const ResultSet &source); - ResultSet &operator= (ResultSet source); - ~ResultSet(); - - /** - * @returns a result at the specified index - * @param index of the result - * @note You should use iterators instead - */ - Result at(int index) const; - - // Iterators - - /** - * An STL-style constant forward iterator for accessing the results in a ResultSet - * TODO: Consider making this to be more than just forward iterator. - * Maybe even a random-access one. - */ - class const_iterator { - public: - typedef std::random_access_iterator_tag iterator_category; - typedef int difference_type; - - typedef const Result value_type; - typedef const Result& reference; - typedef const Result* pointer; - - const_iterator(); - const_iterator(const const_iterator &source); - const_iterator &operator=(const const_iterator &source); - - ~const_iterator(); - - bool isSourceValid() const; - - reference operator*() const; - pointer operator->() const; - - // prefix - const_iterator& operator++(); - // postfix - const_iterator operator++(int); - - // prefix - const_iterator& operator--(); - // postfix - const_iterator operator--(int); - - const_iterator operator+(difference_type n) const; - const_iterator& operator+=(difference_type n); - - const_iterator operator-(difference_type n) const; - const_iterator& operator-=(difference_type n); - - reference operator[](difference_type n) const; - - friend bool operator==(const const_iterator &left, const const_iterator &right); - friend bool operator!=(const const_iterator &left, const const_iterator &right); - - friend bool operator<(const const_iterator &left, const const_iterator &right); - friend bool operator>(const const_iterator &left, const const_iterator &right); - - friend bool operator<=(const const_iterator &left, const const_iterator &right); - friend bool operator>=(const const_iterator &left, const const_iterator &right); - - friend difference_type operator-(const const_iterator &left, const const_iterator &right); - - private: - const_iterator(const ResultSet *resultSet, int currentRow); - - friend class ResultSet; - - ResultSet_IteratorPrivate* const d; - }; - - /** - * @returns a constant iterator pointing to the start of the collection - * (to the first item) - * @note as usual in C++, the range of the collection is [begin, end) - */ - const_iterator begin() const; - /** - * @returns a constant iterator pointing to the end of the collection - * (after the last item) - * @note as usual in C++, the range of the collection is [begin, end) - */ - const_iterator end() const; - - /** - * Alias for begin - */ - inline const_iterator cbegin() const { return begin(); } - /** - * Alias for end - */ - inline const_iterator cend() const { return end(); } - - /** - * Alias for begin - */ - inline const_iterator constBegin() const { return cbegin(); } - /** - * Alias for end - */ - inline const_iterator constEnd() const { return cend(); } - -private: - friend class ResultSet_IteratorPrivate; - ResultSetPrivate *d; -}; - -bool KACTIVITIESSTATS_EXPORT operator==(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); -bool KACTIVITIESSTATS_EXPORT operator!=(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); - -bool KACTIVITIESSTATS_EXPORT operator<(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); -bool KACTIVITIESSTATS_EXPORT operator>(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); - -bool KACTIVITIESSTATS_EXPORT operator<=(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); -bool KACTIVITIESSTATS_EXPORT operator>=(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); - -ResultSet::const_iterator::difference_type KACTIVITIESSTATS_EXPORT -operator-(const ResultSet::const_iterator &left, - const ResultSet::const_iterator &right); - -inline QDebug operator<< (QDebug out, const ResultSet::Result &result) -{ - return out - << (result.linkStatus() == ResultSet::Result::Linked ? "⊤" : - result.linkStatus() == ResultSet::Result::NotLinked ? "⊥" : "?") - << result.score() - << result.title() - << result.resource() - ; -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -#endif // KACTIVITIES_STATS_RESULTSET - diff --git a/libs/kactivities-stats/src/lib/stats/resultset.cpp b/libs/kactivities-stats/src/lib/stats/resultset.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultset.cpp +++ /dev/null @@ -1,435 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "resultset.h" - -// Qt -#include -#include -#include - -// Local -#include -#include - -// Boost and STL -#include -#include -#include -#include - -// KActivities -#include "activitiessync_p.h" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -using namespace Terms; - -class ResultSet_ResultPrivate { -public: - QString resource; - QString title; - QString mimetype; - double score; - uint lastUpdate; - uint firstUpdate; - ResultSet::Result::LinkStatus linkStatus; - -}; - -ResultSet::Result::Result() - : d(new ResultSet_ResultPrivate()) -{ -} - -ResultSet::Result::Result(Result &&result) - : d(result.d) -{ - result.d = Q_NULLPTR; -} - -ResultSet::Result::Result(const Result &result) - : d(new ResultSet_ResultPrivate(*result.d)) -{ -} - -ResultSet::Result &ResultSet::Result::operator=(Result result) -{ - std::swap(d, result.d); - - return *this; -} - -ResultSet::Result::~Result() -{ - delete d; -} - -#define CREATE_GETTER_AND_SETTER(Type, Name, Set) \ - Type ResultSet::Result::Name() const \ - { \ - return d->Name; \ - } \ - \ - void ResultSet::Result::Set(Type Name) \ - { \ - d->Name = Name; \ - } - -CREATE_GETTER_AND_SETTER(QString, resource, setResource) -CREATE_GETTER_AND_SETTER(QString, title, setTitle) -CREATE_GETTER_AND_SETTER(QString, mimetype, setMimetype) -CREATE_GETTER_AND_SETTER(double, score, setScore) -CREATE_GETTER_AND_SETTER(uint, lastUpdate, setLastUpdate) -CREATE_GETTER_AND_SETTER(uint, firstUpdate, setFirstUpdate) -CREATE_GETTER_AND_SETTER(ResultSet::Result::LinkStatus, linkStatus, setLinkStatus) - -#undef CREATE_GETTER_AND_SETTER - -class ResultSetPrivate { -public: - Common::Database::Ptr database; - QSqlQuery query; - Query queryDefinition; - - mutable ActivitiesSync::ConsumerPtr activities; - - void initQuery() - { - if (!database || query.isActive()) { - return; - } - - auto selection = queryDefinition.selection(); - - query = database->execQuery(replaceQueryParameters( - selection == LinkedResources ? linkedResourcesQuery() - : selection == UsedResources ? usedResourcesQuery() - : selection == AllResources ? allResourcesQuery() - : QString())); - - if (query.lastError().isValid()) { - qDebug() << "Error: " << query.lastError(); - } - - Q_ASSERT_X(query.isActive(), "ResultSet initQuery", "Query is not valid"); - } - - QString agentClause(const QString &agent) const - { - if (agent == QLatin1String(":any")) return QStringLiteral("1"); - - return "agent = '" + ( - agent == QLatin1String(":current") ? QCoreApplication::instance()->applicationName() : - agent - ) + "'"; - } - - QString activityClause(const QString &activity) const - { - if (activity == QLatin1String(":any")) return QStringLiteral("1"); - - return "activity = '" + ( - activity == QLatin1String(":current") ? ActivitiesSync::currentActivity(activities) : - activity - ) + "'"; - } - - inline QString starPattern(const QString &pattern) const - { - return Common::parseStarPattern(pattern, QStringLiteral("%"), [] (QString str) { - return str.replace(QLatin1String("%"), QLatin1String("\\%")).replace(QLatin1String("_"), QLatin1String("\\_")); - }); - } - - QString urlFilterClause(const QString &urlFilter) const - { - if (urlFilter == QLatin1String("*")) return QStringLiteral("1"); - - return "resource LIKE '" + Common::starPatternToLike(urlFilter) + "' ESCAPE '\\'"; - } - - QString mimetypeClause(const QString &mimetype) const - { - if (mimetype == QLatin1String(":any") || mimetype == QLatin1String("*")) return QStringLiteral("1"); - - return "mimetype LIKE '" + Common::starPatternToLike(mimetype) + "' ESCAPE '\\'"; - } - - /** - * Transforms the input list's elements with the f member method, - * and returns the resulting list - */ - template - inline - QStringList transformedList(const QStringList &input, F f) const - { - using namespace std::placeholders; - - QStringList result; - boost::transform(input, - std::back_inserter(result), - std::bind(f, this, _1)); - - return result; - } - - QString limitOffsetSuffix() const - { - QString result; - - const int limit = queryDefinition.limit(); - if (limit > 0) { - result += " LIMIT " + QString::number(limit); - - const int offset = queryDefinition.offset(); - if (offset > 0) { - result += " OFFSET " + QString::number(offset); - } - } - - return result; - } - - inline QString replaceQueryParameters(const QString &_query) const - { - // ORDER BY column - auto ordering = queryDefinition.ordering(); - QString orderingColumn = QStringLiteral("linkStatus DESC, ") + ( - ordering == HighScoredFirst ? QStringLiteral("score DESC,") - : ordering == RecentlyCreatedFirst ? QStringLiteral("firstUpdate DESC,") - : ordering == RecentlyUsedFirst ? QStringLiteral("lastUpdate DESC,") - : ordering == OrderByTitle ? QStringLiteral("title ASC,") - : QString() - ); - - - // WHERE clause for filtering on agents - QStringList agentsFilter = transformedList( - queryDefinition.agents(), &ResultSetPrivate::agentClause); - - // WHERE clause for filtering on activities - QStringList activitiesFilter = transformedList( - queryDefinition.activities(), &ResultSetPrivate::activityClause); - - // WHERE clause for filtering on resource URLs - QStringList urlFilter = transformedList( - queryDefinition.urlFilters(), &ResultSetPrivate::urlFilterClause); - - // WHERE clause for filtering on resource mime - QStringList mimetypeFilter = transformedList( - queryDefinition.types(), &ResultSetPrivate::mimetypeClause); - - auto query = _query - + "\nORDER BY $orderingColumn resource ASC\n" - + limitOffsetSuffix(); - - - return kamd::utils::debug_and_return("Query: ", - query - .replace(QLatin1String("$orderingColumn"), orderingColumn) - .replace(QLatin1String("$agentsFilter"), agentsFilter.join(QStringLiteral(" OR "))) - .replace(QLatin1String("$activitiesFilter"), activitiesFilter.join(QStringLiteral(" OR "))) - .replace(QLatin1String("$urlFilter"), urlFilter.join(QStringLiteral(" OR "))) - .replace(QLatin1String("$mimetypeFilter"), mimetypeFilter.join(QStringLiteral(" OR "))) - ); - } - - const QString &linkedResourcesQuery() const - { - // TODO: We need to correct the scores based on the time that passed - // since the cache was last updated, although, for this query, - // scores are not that important. - static const QString query = - QStringLiteral("\n" - "SELECT \n" - " rl.targettedResource as resource \n" - " , SUM(rsc.cachedScore) as score \n" - " , MIN(rsc.firstUpdate) as firstUpdate \n" - " , MAX(rsc.lastUpdate) as lastUpdate \n" - " , rl.usedActivity as activity \n" - " , rl.initiatingAgent as agent \n" - " , COALESCE(ri.title, rl.targettedResource) as title \n" - " , ri.mimetype as mimetype \n" - " , 2 as linkStatus \n" - - "FROM \n" - " ResourceLink rl \n" - "LEFT JOIN \n" - " ResourceScoreCache rsc \n" - " ON rl.targettedResource = rsc.targettedResource \n" - " AND rl.usedActivity = rsc.usedActivity \n" - " AND rl.initiatingAgent = rsc.initiatingAgent \n" - "LEFT JOIN \n" - " ResourceInfo ri \n" - " ON rl.targettedResource = ri.targettedResource \n" - - "WHERE \n" - " ($agentsFilter) \n" - " AND ($activitiesFilter) \n" - " AND ($urlFilter)\n" - " AND ($mimetypeFilter)\n" - - "GROUP BY resource, title \n") - ; - - return query; - } - - const QString &usedResourcesQuery() const - { - // TODO: We need to correct the scores based on the time that passed - // since the cache was last updated - static const QString query = - QStringLiteral("\n" - "SELECT \n" - " rsc.targettedResource as resource \n" - " , SUM(rsc.cachedScore) as score \n" - " , MIN(rsc.firstUpdate) as firstUpdate \n" - " , MAX(rsc.lastUpdate) as lastUpdate \n" - " , rsc.usedActivity as activity \n" - " , rsc.initiatingAgent as agent \n" - " , COALESCE(ri.title, rsc.targettedResource) as title \n" - " , ri.mimetype as mimetype \n" - " , 1 as linkStatus \n" // Note: this is replaced by allResourcesQuery - - "FROM \n" - " ResourceScoreCache rsc \n" - "LEFT JOIN \n" - " ResourceInfo ri \n" - " ON rsc.targettedResource = ri.targettedResource \n" - - "WHERE \n" - " ($agentsFilter) \n" - " AND ($activitiesFilter) \n" - " AND ($urlFilter)\n" - " AND ($mimetypeFilter)\n" - - "GROUP BY resource, title \n") - ; - - return query; - } - - const QString &allResourcesQuery() const - { - // TODO: Implement counting of the linked items - // int linkedItemsCount = 0; // ...; - // - // if (linkedItemsCount >= limit) { - // return linkedResourcesQuery(); - // - // } else if (linkedItemsCount == 0) { - // return usedResourcesQuery(); - // - // } else { - static QString usedResourcesQuery_ = usedResourcesQuery(); - - static const QString query = - "WITH LinkedResourcesResults as (\n" + - linkedResourcesQuery() + - "\n)\n" + - "SELECT * FROM LinkedResourcesResults \n" + - "UNION \n" + - usedResourcesQuery_ - .replace(QLatin1String("WHERE "), - QLatin1String("WHERE rsc.targettedResource NOT IN " - "(SELECT resource FROM LinkedResourcesResults) AND ")) - .replace(QLatin1String("1 as linkStatus"), QLatin1String("0 as linkStatus")); - // } - - return query; - } - - ResultSet::Result currentResult() const - { - ResultSet::Result result; - result.setResource(query.value(QStringLiteral("resource")).toString()); - result.setTitle(query.value(QStringLiteral("title")).toString()); - result.setMimetype(query.value(QStringLiteral("mimetype")).toString()); - result.setScore(query.value(QStringLiteral("score")).toDouble()); - result.setLastUpdate(query.value(QStringLiteral("lastUpdate")).toInt()); - result.setFirstUpdate(query.value(QStringLiteral("firstUpdate")).toInt()); - - result.setLinkStatus( - (ResultSet::Result::LinkStatus)query.value(QStringLiteral("linkStatus")).toInt()); - - return result; - } -}; - -ResultSet::ResultSet(Query query) - : d(new ResultSetPrivate()) -{ - using namespace Common; - - d->database = Database::instance(Database::ResourcesDatabase, Database::ReadOnly); - - if (!(d->database)) { - qWarning() << "KActivities ERROR: There is no database. This probably means " - "that you do not have the Activity Manager running, or that " - "something else is broken on your system. Recent documents and " - "alike will not work!"; - Q_ASSERT_X((bool)d->database, "ResultSet constructor", "Database is NULL"); - } - - d->queryDefinition = query; - - d->initQuery(); -} - -ResultSet::ResultSet(ResultSet &&source) - : d(nullptr) -{ - std::swap(d, source.d); -} - -ResultSet::ResultSet(const ResultSet &source) - : d(new ResultSetPrivate(*source.d)) -{ -} - -ResultSet &ResultSet::operator= (ResultSet source) -{ - std::swap(d, source.d); - return *this; -} - -ResultSet::~ResultSet() -{ - delete d; -} - -ResultSet::Result ResultSet::at(int index) const -{ - Q_ASSERT_X(d->query.isActive(), "ResultSet::at", "Query is not active"); - - d->query.seek(index); - - return d->currentResult(); -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -#include "resultset_iterator.cpp" - diff --git a/libs/kactivities-stats/src/lib/stats/resultset_iterator.cpp b/libs/kactivities-stats/src/lib/stats/resultset_iterator.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultset_iterator.cpp +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include - -namespace KActivities { -namespace Experimental { -namespace Stats { - -using namespace Terms; - -typedef ResultSet::const_iterator iterator; - -// Iterator - -class ResultSet_IteratorPrivate { -public: - ResultSet_IteratorPrivate(const ResultSet *resultSet, int currentRow = -1) - : resultSet(resultSet) - , currentRow(currentRow) - { - updateValue(); - } - - const ResultSet *resultSet; - int currentRow; - boost::optional currentValue; - - inline void moveTo(int row) - { - if (row == currentRow) return; - currentRow = row; - updateValue(); - } - - inline void moveBy(int row) - { - moveTo(currentRow + row); - } - - void updateValue() - { - using namespace boost; - - if (!resultSet || !resultSet->d->query.seek(currentRow)) { - currentValue = none; - - } else { - auto value = resultSet->d->currentResult(); - currentValue = make_optional(std::move(value)); - - } - } - - friend void swap(ResultSet_IteratorPrivate &left, - ResultSet_IteratorPrivate &right) - { - using namespace std; - swap(left.resultSet, right.resultSet); - swap(left.currentRow, right.currentRow); - swap(left.currentValue, right.currentValue); - } - - bool operator==(const ResultSet_IteratorPrivate &other) const - { - bool thisValid = currentValue.is_initialized(); - bool otherValid = other.currentValue.is_initialized(); - - return - // If one is valid, and the other is not, - // they are not equal - thisValid != otherValid ? false : - - // If both are invalid, they are equal - !thisValid ? true : - - // Otherwise, really compare - resultSet == other.resultSet && - currentRow == other.currentRow; - } - - bool isValid() const - { - return currentValue.is_initialized(); - } - - static bool sameSource(const ResultSet_IteratorPrivate &left, - const ResultSet_IteratorPrivate &right) - { - return left.resultSet == right.resultSet && - left.resultSet != Q_NULLPTR; - } - -}; - -iterator::const_iterator(const ResultSet *resultSet, int currentRow) - : d(new ResultSet_IteratorPrivate(resultSet, currentRow)) -{ -} - -iterator::const_iterator() - : d(new ResultSet_IteratorPrivate(Q_NULLPTR, -1)) -{ -} - -iterator::const_iterator(const const_iterator &source) - : d(new ResultSet_IteratorPrivate(source.d->resultSet, - source.d->currentRow)) -{ -} - -bool iterator::isSourceValid() const -{ - return d->resultSet != Q_NULLPTR; -} - -iterator &iterator::operator=(const const_iterator &source) -{ - const_iterator temp(source); - swap(*d, *temp.d); - return *this; -} - -iterator::~const_iterator() -{ - delete d; -} - -iterator::reference iterator::operator*() const -{ - return d->currentValue.get(); -} - -iterator::pointer iterator::operator->() const -{ - return &d->currentValue.get(); -} - -// prefix -iterator& iterator::operator++() -{ - d->currentRow++; - d->updateValue(); - - return *this; -} - -// postfix -iterator iterator::operator++(int) -{ - return const_iterator(d->resultSet, d->currentRow + 1); -} - -// prefix -iterator& iterator::operator--() -{ - d->currentRow--; - d->updateValue(); - - return *this; -} - -// postfix -iterator iterator::operator--(int) -{ - return const_iterator(d->resultSet, d->currentRow - 1); -} - -iterator ResultSet::begin() const -{ - return const_iterator(this, d->database ? 0 : -1); -} - -iterator ResultSet::end() const -{ - return const_iterator(this, -1); -} - -iterator iterator::operator+(iterator::difference_type n) const -{ - return const_iterator(d->resultSet, d->currentRow + n); -} - -iterator &iterator::operator+=(iterator::difference_type n) -{ - d->moveBy(n); - return *this; -} - -iterator iterator::operator-(iterator::difference_type n) const -{ - return const_iterator(d->resultSet, d->currentRow - n); -} - -iterator &iterator::operator-=(iterator::difference_type n) -{ - d->moveBy(-n); - return *this; -} - -iterator::reference iterator::operator[](iterator::difference_type n) const -{ - return *(*this + n); -} - -// bool iterator::operator==(const const_iterator &right) const -// { -// return *d == *right.d; -// } -// -// bool iterator::operator!=(const const_iterator &right) const -// { -// return !(*d == *right.d); -// } - -bool operator==(const iterator &left, const iterator &right) -{ - return *left.d == *right.d; -} - -bool operator!=(const iterator &left, const iterator &right) -{ - return !(*left.d == *right.d); -} - -#define COMPARATOR_IMPL(OP) \ - bool operator OP(const iterator &left, const iterator &right) \ - { \ - return ResultSet_IteratorPrivate::sameSource(*left.d, *right.d) \ - ? left.d->currentRow OP right.d->currentRow \ - : false; \ - } - -COMPARATOR_IMPL(<) -COMPARATOR_IMPL(>) -COMPARATOR_IMPL(<=) -COMPARATOR_IMPL(>=) - -#undef COMPARATOR_IMPL - -iterator::difference_type operator-(const iterator &left, const iterator &right) -{ - return ResultSet_IteratorPrivate::sameSource(*left.d, *right.d) - ? left.d->currentRow - right.d->currentRow - : 0; -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - diff --git a/libs/kactivities-stats/src/lib/stats/resultwatcher.h b/libs/kactivities-stats/src/lib/stats/resultwatcher.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultwatcher.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KACTIVITIES_STATS_RESULTWATCHER -#define KACTIVITIES_STATS_RESULTWATCHER - -#include - -#include "query.h" -#include "resultset.h" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -class ResultWatcherPrivate; - -/** - * A very thin class that sends signals when new resources matching - * a predefined query are available. - */ -class KACTIVITIESSTATS_EXPORT ResultWatcher: public QObject { - Q_OBJECT - -public: - ResultWatcher(Query query, QObject *parent = Q_NULLPTR); - ~ResultWatcher(); - -Q_SIGNALS: - /** - * Emitted when a result has been added or updated. This either means - * a new resource has appeared in the result set, or that - * a previously existing one has some of the attributes changed. - * @param result new data for the resource defined by result.resource - */ - void resultScoreUpdated(const QString &resource, double score, - uint lastUpdate, uint firstUpdate); - - /** - * Emitted when a result has been added or updated. This either means - * a new resource has appeared in the result set, or that - * a previously existing one has some of the attributes changed. - * @param result new data for the resource defined by result.resource - */ - void resultRemoved(const QString &resource); - - /** - * Emitted when a result has been linked to the activity - */ - void resultLinked(const QString &resource); - - /** - * Emitted when a result has been linked to the activity - */ - void resultUnlinked(const QString &resource); - - /** - * Emitted when the title of a resource has been changed. - * @param resource URL of the resource that has a new title - * @param title new title of the resource - * @note This signal will be emitted even for the resources that - * do not match the specified query. This is because the class is - * lightweight, and it does not keep track of which resources match - * the query to be able to filter this signal. - */ - void resourceTitleChanged(const QString &resource, const QString &title); - - /** - * Emitted when the mimetype of a resource has been changed. - * @param resource URL of the resource that has a new mimetype - * @param mimetype new mimetype of the resource - * @note This signal will be emitted even for the resources that - * do not match the specified query. This is because the class is - * lightweight, and it does not keep track of which resources match - * the query to be able to filter this signal. - */ - void resourceMimetypeChanged(const QString &resource, const QString &mimetype); - - /** - * Emitted when the client should forget about all the results it - * knew about and reload them. This can happen when the user clears - * the history, or when there are more significant changes to the data. - */ - void resultsInvalidated(); - -public: - // TODO: BLOCKER Move these to libKActivities - - void linkToActivity(const QUrl &resource, - const Terms::Activity &activity - = Terms::Activity(QStringList()), - const Terms::Agent &agent - = Terms::Agent(QStringList())); - - void unlinkFromActivity(const QUrl &resource, - const Terms::Activity &activity - = Terms::Activity(QStringList()), - const Terms::Agent &agent - = Terms::Agent(QStringList())); - - -private: - ResultWatcherPrivate *const d; - -}; - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -#endif // KACTIVITIES_STATS_RESULTWATCHER - diff --git a/libs/kactivities-stats/src/lib/stats/resultwatcher.cpp b/libs/kactivities-stats/src/lib/stats/resultwatcher.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/resultwatcher.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "resultwatcher.h" - -// Qt -#include -#include -#include -#include -#include - -// Local -#include -#include - -// Boost and STL -#include -#include -#include -#include -#include - -// KActivities -#include - -#include "resourceslinking_interface.h" -#include "resourcesscoring_interface.h" -#include "common/dbus/common.h" -#include "common/specialvalues.h" -#include "activitiessync_p.h" -#include "utils/lazy_val.h" -#include "utils/qsqlquery_iterator.h" - -#include - -#define QDBG qDebug() << "KActivitiesStats(" << (void*)this << ")" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -// Main class - -class ResultWatcherPrivate { -public: - mutable ActivitiesSync::ConsumerPtr activities; - QList urlFilters; - - ResultWatcherPrivate(ResultWatcher *parent, Query query) - : linking(new KAMD_DBUS_CLASS_INTERFACE(Resources/Linking, ResourcesLinking, Q_NULLPTR)) - , scoring(new KAMD_DBUS_CLASS_INTERFACE(Resources/Scoring, ResourcesScoring, Q_NULLPTR)) - , q(parent) - , query(query) - { - for (const auto& urlFilter: query.urlFilters()) { - urlFilters << Common::starPatternToRegex(urlFilter); - } - - m_resultInvalidationTimer.setSingleShot(true); - m_resultInvalidationTimer.setInterval(200); - QObject::connect(&m_resultInvalidationTimer, &QTimer::timeout, - q, emit &ResultWatcher::resultsInvalidated); - } - - // Like boost any_of, but returning true if the range is empty - template - inline bool any_of(const Collection &collection, Predicate &&predicate) const - { - const auto begin = collection.cbegin(); - const auto end = collection.cend(); - - return begin == end - || std::any_of(begin, end, std::forward(predicate)); - } - -#define DEBUG_MATCHERS 0 - - // Processing the list of activities as specified by the query. - // If it contains :any, we are returning true, otherwise - // we want to match a specific activity (be it the current - // activity or not). The :global special value is not special here - bool activityMatches(const QString &activity) const - { - #if DEBUG_MATCHERS - qDebug() << "Activity " << activity << "matching against" - << query.activities(); - #endif - - return kamd::utils::debug_and_return(DEBUG_MATCHERS, " -> returning ", - activity == ANY_ACTIVITY_TAG || - any_of(query.activities(), [&] (const QString &matcher) { - return - matcher == ANY_ACTIVITY_TAG - ? true - : matcher == CURRENT_ACTIVITY_TAG - ? (matcher == activity || activity == ActivitiesSync::currentActivity(activities)) - : activity == matcher; - } - )); - } - - // Same as above, but for agents - bool agentMatches(const QString &agent) const - { - #if DEBUG_MATCHERS - qDebug() << "Agent " << agent << "matching against" << query.agents(); - #endif - - return kamd::utils::debug_and_return(DEBUG_MATCHERS, " -> returning ", - agent == ANY_AGENT_TAG || - any_of(query.agents(), [&] (const QString &matcher) { - return - matcher == ANY_AGENT_TAG - ? true - : matcher == CURRENT_AGENT_TAG - ? (matcher == agent || agent == QCoreApplication::applicationName()) - : agent == matcher; - } - )); - } - - // Same as above, but for urls - bool urlMatches(const QString &url) const - { - #if DEBUG_MATCHERS - qDebug() << "Url " << url << "matching against" << urlFilters; - #endif - - return kamd::utils::debug_and_return(DEBUG_MATCHERS, " -> returning ", - any_of(urlFilters, [&] (const QRegExp &matcher) { - return matcher.exactMatch(url); - } - )); - } - - bool typeMatches(const QString &resource) const - { - // We don't necessarily need to retrieve the type from - // the database. If we do, get it only once - auto type = kamd::utils::make_lazy_val([&] () -> QString { - using Common::Database; - - auto query - = Database::instance(Database::ResourcesDatabase, - Database::ReadOnly) - ->execQuery("SELECT mimetype FROM ResourceInfo WHERE " - "targettedResource = '" + resource + "'"); - - for (const auto &item : query) { - return item[0].toString(); - } - - return QString(); - }); - - #if DEBUG_MATCHERS - qDebug() << "Type " << "...type..." << "matching against" << query.types(); - qDebug() << "ANY_TYPE_TAG" << ANY_TYPE_TAG; - #endif - - return kamd::utils::debug_and_return(DEBUG_MATCHERS, " -> returning ", - any_of(query.types(), [&] (const QString &matcher) { - return matcher == ANY_TYPE_TAG || matcher == type; - } - )); - } - -#undef DEBUG_MATCHERS - - bool eventMatches(const QString &agent, const QString &resource, - const QString &activity) const - { - // The order of checks is not arbitrary, it is sorted - // from the cheapest, to the most expensive - return agentMatches(agent) - && activityMatches(activity) - && urlMatches(resource) - && typeMatches(resource) - ; - } - - void onResourceLinkedToActivity(const QString &agent, - const QString &resource, - const QString &activity) - { - // The used resources do not really care about the linked ones - if (query.selection() == Terms::UsedResources) return; - - if (!eventMatches(agent, resource, activity)) return; - - // TODO: See whether it makes sense to have - // lastUpdate/firstUpdate here as well - emit q->resultLinked(resource); - } - - void onResourceUnlinkedFromActivity(const QString &agent, - const QString &resource, - const QString &activity) - { - // The used resources do not really care about the linked ones - if (query.selection() == Terms::UsedResources) return; - - if (!eventMatches(agent, resource, activity)) return; - - emit q->resultUnlinked(resource); - } - - void onResourceScoreUpdated(const QString &activity, const QString &agent, - const QString &resource, double score, - uint lastUpdate, uint firstUpdate) - { - Q_ASSERT_X(activity == "00000000-0000-0000-0000-000000000000" || - !QUuid(activity).isNull(), - "ResultWatcher::onResourceScoreUpdated", - "The activity should be always specified here, no magic values"); - - // The linked resources do not really care about the stats - if (query.selection() == Terms::LinkedResources) return; - - if (!eventMatches(agent, resource, activity)) return; - - emit q->resultScoreUpdated(resource, score, lastUpdate, firstUpdate); - } - - - void onEarlierStatsDeleted(QString, int) - { - // The linked resources do not really care about the stats - if (query.selection() == Terms::LinkedResources) return; - - scheduleResultsInvalidation(); - } - - void onRecentStatsDeleted(QString, int, QString) - { - // The linked resources do not really care about the stats - if (query.selection() == Terms::LinkedResources) return; - - scheduleResultsInvalidation(); - } - - void onStatsForResourceDeleted(const QString &activity, - const QString &agent, - const QString &resource) - { - if (query.selection() == Terms::LinkedResources) return; - - if (activityMatches(activity) && agentMatches(agent)) { - if (resource.contains('*')) { - scheduleResultsInvalidation(); - - } else if (typeMatches(resource)) { - if (!m_resultInvalidationTimer.isActive()) { - // Remove a result only if we haven't an invalidation - // request scheduled - q->resultRemoved(resource); - } - } - } - } - - // Lets not send a lot of invalidation events at once - QTimer m_resultInvalidationTimer; - void scheduleResultsInvalidation() - { - QDBG << "Scheduling invalidation"; - m_resultInvalidationTimer.start(); - } - - QScopedPointer linking; - QScopedPointer scoring; - - ResultWatcher * const q; - Query query; -}; - -ResultWatcher::ResultWatcher(Query query, QObject *parent) - : QObject(parent) - , d(new ResultWatcherPrivate(this, query)) -{ - using namespace org::kde::ActivityManager; - using namespace std::placeholders; - - // There is no need for private slots, when we have bind - - // Connecting the linking service - QObject::connect( - d->linking.data(), &ResourcesLinking::ResourceLinkedToActivity, - this, std::bind(&ResultWatcherPrivate::onResourceLinkedToActivity, d, _1, _2, _3)); - QObject::connect( - d->linking.data(), &ResourcesLinking::ResourceUnlinkedFromActivity, - this, std::bind(&ResultWatcherPrivate::onResourceUnlinkedFromActivity, d, _1, _2, _3)); - - // Connecting the scoring service - QObject::connect( - d->scoring.data(), &ResourcesScoring::ResourceScoreUpdated, - this, std::bind(&ResultWatcherPrivate::onResourceScoreUpdated, d, _1, _2, _3, _4, _5, _6)); - QObject::connect( - d->scoring.data(), &ResourcesScoring::ResourceScoreDeleted, - this, std::bind(&ResultWatcherPrivate::onStatsForResourceDeleted, d, _1, _2, _3)); - QObject::connect( - d->scoring.data(), &ResourcesScoring::RecentStatsDeleted, - this, std::bind(&ResultWatcherPrivate::onRecentStatsDeleted, d, _1, _2, _3)); - QObject::connect( - d->scoring.data(), &ResourcesScoring::EarlierStatsDeleted, - this, std::bind(&ResultWatcherPrivate::onEarlierStatsDeleted, d, _1, _2)); - -} - -ResultWatcher::~ResultWatcher() -{ - delete d; -} - -void ResultWatcher::linkToActivity(const QUrl &resource, - const Terms::Activity &activity, - const Terms::Agent &agent) -{ - const auto activities = - (!activity.values.isEmpty()) ? activity.values : - (!d->query.activities().isEmpty()) ? d->query.activities() : - Terms::Activity::current().values; - const auto agents = - (!agent.values.isEmpty()) ? agent.values : - (!d->query.agents().isEmpty()) ? d->query.agents() : - Terms::Agent::current().values; - - for (const auto &activity : activities) { - for (const auto &agent : agents) { - d->linking->LinkResourceToActivity(agent, resource.toString(), - activity); - } - } -} - -void ResultWatcher::unlinkFromActivity(const QUrl &resource, - const Terms::Activity &activity, - const Terms::Agent &agent) -{ - const auto activities = - !activity.values.isEmpty() ? activity.values : - !d->query.activities().isEmpty() ? d->query.activities() : - Terms::Activity::current().values; - const auto agents = - !agent.values.isEmpty() ? agent.values : - !d->query.agents().isEmpty() ? d->query.agents() : - Terms::Agent::current().values; - - for (const auto &activity : activities) { - for (const auto &agent : agents) { - d->linking->UnlinkResourceFromActivity(agent, resource.toString(), - activity); - } - } -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - diff --git a/libs/kactivities-stats/src/lib/stats/terms.h b/libs/kactivities-stats/src/lib/stats/terms.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/terms.h +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KACTIVITIES_STATS_TERMS_H -#define KACTIVITIES_STATS_TERMS_H - -#include - -#ifdef Q_COMPILER_INITIALIZER_LISTS -#include -#endif - -#include -#include - -#include "kactivitiesstats_export.h" - -namespace KActivities { -namespace Experimental { -namespace Stats { - -namespace Terms { - /** - * Enumerator specifying the ordering in which the - * results of the query should be listed - */ - enum KACTIVITIESSTATS_EXPORT Order { - HighScoredFirst, ///< Resources with the highest scores first - RecentlyUsedFirst, ///< Recently used resources first - RecentlyCreatedFirst, ///< Recently created resources first - OrderByUrl, ///< Order by uri, alphabetically - OrderByTitle ///< Order by uri, alphabetically - }; - - /** - * Which resources should be returned - */ - enum KACTIVITIESSTATS_EXPORT Select { - LinkedResources, ///< Resources linked to an activity, or globally - UsedResources, ///< Resources that have been accessed - AllResources ///< Combined set of accessed and linked resources - }; - - /** - * How many items do you need? - */ - struct KACTIVITIESSTATS_EXPORT Limit { - Limit(int value); - static Limit all(); - int value; - }; - - /** - * How many items to skip? - * This can be specified only if limit is also set to a finite value. - */ - struct KACTIVITIESSTATS_EXPORT Offset { - Offset(int value); - int value; - }; - - /** - * Term to filter the resources according to their types - */ - struct KACTIVITIESSTATS_EXPORT Type { - /** - * Show resources of any type - */ - static Type any(); - - #ifdef Q_COMPILER_INITIALIZER_LISTS - inline Type(std::initializer_list types) - : values(types) - { - } - #endif - - Type(QStringList types); - Type(QString type); - - const QStringList values; - }; - - /** - * Term to filter the resources according the agent (application) which - * accessed it - */ - struct KACTIVITIESSTATS_EXPORT Agent { - /** - * Show resources accessed/linked by any application - */ - static Agent any(); - - /** - * Show resources not tied to a specific agent - */ - static Agent global(); - - /** - * Show resources accessed/linked by the current application - */ - static Agent current(); - - #ifdef Q_COMPILER_INITIALIZER_LISTS - inline Agent(std::initializer_list agents) - : values(agents) - { - } - #endif - - Agent(QStringList agents); - Agent(QString agent); - - const QStringList values; - }; - - /** - * Term to filter the resources according the activity in which they - * were accessed - */ - struct KACTIVITIESSTATS_EXPORT Activity { - /** - * Show resources accessed in / linked to any activity - */ - static Activity any(); - - /** - * Show resources linked to all activities - */ - static Activity global(); - - /** - * Show resources linked to all activities - */ - static Activity current(); - - #ifdef Q_COMPILER_INITIALIZER_LISTS - inline Activity(std::initializer_list activities) - : values(activities) - { - } - #endif - - Activity(QStringList activities); - Activity(QString activity); - - const QStringList values; - }; - - /** - * Url filtering. - */ - struct KACTIVITIESSTATS_EXPORT Url { - /** - * Show only resources that start with the specified prefix - */ - static Url startsWith(const QString &prefix); - - /** - * Show resources that contain the specified infix - */ - static Url contains(const QString &infix); - - /** - * Show local files - */ - static Url localFile(); - - /** - * Show local files, smb, fish, ftp and stfp - */ - static Url file(); - - #ifdef Q_COMPILER_INITIALIZER_LISTS - inline Url(std::initializer_list urlPatterns) - : values(urlPatterns) - { - } - #endif - - Url(QStringList urlPatterns); - Url(QString urlPattern); - - const QStringList values; - - }; -} // namespace Terms - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Order &order); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Select &select); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Type &type); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Agent &agent); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Activity &activity); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Url &url); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Limit &limit); - -KACTIVITIESSTATS_EXPORT -QDebug operator<<(QDebug dbg, const KActivities::Experimental::Stats::Terms::Offset &offset); - -#endif // KACTIVITIES_STATS_TERMS_H - diff --git a/libs/kactivities-stats/src/lib/stats/terms.cpp b/libs/kactivities-stats/src/lib/stats/terms.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/terms.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "terms.h" -#include - -namespace KActivities { -namespace Experimental { -namespace Stats { - -// Term classes -#define IMPLEMENT_TERM_CONSTRUCTORS(TYPE) \ - Terms::TYPE::TYPE(QStringList values) \ - : values(values) \ - {} \ - \ - Terms::TYPE::TYPE(QString value) \ - : values(QStringList() << value) \ - {} - -#define IMPLEMENT_SPECIAL_TERM_VALUE(TYPE, VALUE_NAME, VALUE) \ - Terms::TYPE Terms::TYPE::VALUE_NAME() \ - { \ - return Terms::TYPE(VALUE); \ - } - -IMPLEMENT_TERM_CONSTRUCTORS(Type) -IMPLEMENT_SPECIAL_TERM_VALUE(Type, any, ":any") - -IMPLEMENT_TERM_CONSTRUCTORS(Agent) -IMPLEMENT_SPECIAL_TERM_VALUE(Agent, any, ":any") -IMPLEMENT_SPECIAL_TERM_VALUE(Agent, global, ":global") -IMPLEMENT_SPECIAL_TERM_VALUE(Agent, current, ":current") - -IMPLEMENT_TERM_CONSTRUCTORS(Activity) -IMPLEMENT_SPECIAL_TERM_VALUE(Activity, any, ":any") -IMPLEMENT_SPECIAL_TERM_VALUE(Activity, global, ":global") -IMPLEMENT_SPECIAL_TERM_VALUE(Activity, current, ":current") - -IMPLEMENT_TERM_CONSTRUCTORS(Url) -IMPLEMENT_SPECIAL_TERM_VALUE(Url, localFile, "/*") -IMPLEMENT_SPECIAL_TERM_VALUE(Url, file, QStringList() << "/*" << "smb:*" << "fish:*" << "sftp:*" << "ftp:*") - -#undef IMPLEMENT_TERM_CONSTRUCTORS -#undef IMPLEMENT_SPECIAL_TERM_VALUE - -Terms::Limit::Limit(int value) - : value(value) -{ -} - -Terms::Limit Terms::Limit::all() -{ - return Limit(0); -} - -Terms::Offset::Offset(int value) - : value(value) -{ -} - -Terms::Url Terms::Url::startsWith(const QString &prefix) -{ - return Url(prefix + "*"); -} - -Terms::Url Terms::Url::contains(const QString &infix) -{ - return Url("*" + infix + "*"); -} - -} // namespace Stats -} // namespace Experimental -} // namespace KActivities - -namespace KAStats = KActivities::Experimental::Stats; - -#define QDEBUG_TERM_OUT(TYPE, OUT) \ - QDebug operator<<(QDebug dbg, const KAStats::Terms::TYPE &_) \ - { \ - using namespace KAStats::Terms; \ - dbg.nospace() << #TYPE << ": " << (OUT); \ - return dbg; \ - } - -QDEBUG_TERM_OUT(Order, _ == HighScoredFirst ? "HighScore" : - _ == RecentlyUsedFirst ? "RecentlyUsed" : - _ == RecentlyCreatedFirst ? "RecentlyCreated" : - "Alphabetical" ) - -QDEBUG_TERM_OUT(Select, _ == LinkedResources ? "LinkedResources" : - _ == UsedResources ? "UsedResources" : - "AllResources" ) - -QDEBUG_TERM_OUT(Type, _.values) -QDEBUG_TERM_OUT(Agent, _.values) -QDEBUG_TERM_OUT(Activity, _.values) -QDEBUG_TERM_OUT(Url, _.values) - -QDEBUG_TERM_OUT(Limit, _.value) -QDEBUG_TERM_OUT(Offset, _.value) - -#undef QDEBUG_TERM_OUT - diff --git a/libs/kactivities-stats/src/lib/stats/version.h b/libs/kactivities-stats/src/lib/stats/version.h deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/version.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2008 by Aaron Seigo - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef KACTIVITIESSTATS_VERSION_H -#define KACTIVITIESSTATS_VERSION_H - -/** @file version.h */ - -#include "kactivitiesstats_export.h" - -/** - * String version of libkactivitiesstats version, suitable for use in - * file formats or network protocols - */ -#define KACTIVITIESSTATS_VERSION_STRING \ - "0.0.1" - -/// @brief Major version of libkactivitiesstats, at compile time -#define KACTIVITIESSTATS_VERSION_MAJOR \ - 0 -/// @brief Minor version of libkactivitiesstats, at compile time -#define KACTIVITIESSTATS_VERSION_MINOR \ - 0 -/// @brief Release version of libkactivitiesstats, at compile time -#define KACTIVITIESSTATS_VERSION_RELEASE \ - 1 - -#define KACTIVITIESSTATS_MAKE_VERSION(a, b, c) \ - (((a) << 16) | ((b) << 8) | (c)) - -/** - * Compile time macro for the version number of libkactivitiesstats - */ -#define KACTIVITIESSTATS_VERSION \ - KACTIVITIESSTATS_MAKE_VERSION(KACTIVITIESSTATS_VERSION_MAJOR, KACTIVITIESSTATS_VERSION_MINOR, KACTIVITIESSTATS_VERSION_RELEASE) - -/** - * Compile-time macro for checking the kactivities version. Not useful for - * detecting the version of libkactivities at runtime. - */ -#define KACTIVITIESSTATS_IS_VERSION(a, b, c) \ - (KACTIVITIESSTATS_VERSION >= KACTIVITIESSTATS_MAKE_VERSION(a, b, c)) - -/** - * Namespace for everything in libkactivitiesstats - */ -namespace KActivities { -namespace Stats { - -/** - * The runtime version of libkactivitiesstats - */ -KACTIVITIESSTATS_EXPORT unsigned int version(); - -/** - * The runtime major version of libkactivitiesstats - */ -KACTIVITIESSTATS_EXPORT unsigned int versionMajor(); - -/** - * The runtime major version of libkactivitiesstats - */ -KACTIVITIESSTATS_EXPORT unsigned int versionMinor(); - -/** - * The runtime major version of libkactivitiesstats - */ -KACTIVITIESSTATS_EXPORT unsigned int versionRelease(); - -/** - * The runtime version string of libkactivitiesstats - */ -KACTIVITIESSTATS_EXPORT const char *versionString(); - -} // Stats namespace -} // KActivities namespace - -#endif // multiple inclusion guard diff --git a/libs/kactivities-stats/src/lib/stats/version.cpp b/libs/kactivities-stats/src/lib/stats/version.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/lib/stats/version.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2008 by Aaron Seigo - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Library General Public License as - * published by the Free Software Foundation; either version 2, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU Library General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "version.h" - -namespace KActivities { -namespace Stats { - -unsigned int version() -{ - return KACTIVITIESSTATS_VERSION; -} - -unsigned int versionMajor() -{ - return KACTIVITIESSTATS_VERSION_MAJOR; -} - -unsigned int versionMinor() -{ - return KACTIVITIESSTATS_VERSION_MINOR; -} - -unsigned int versionRelease() -{ - return KACTIVITIESSTATS_VERSION_RELEASE; -} - -const char *versionString() -{ - return KACTIVITIESSTATS_VERSION_STRING; -} - -} // Stats namespace -} // KActivities namespace diff --git a/libs/kactivities-stats/src/utils/continue_with.h b/libs/kactivities-stats/src/utils/continue_with.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/continue_with.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * continue_with.h - * Copyright (C) 2014 Ivan Čukić - * - * Distributed under terms of the MIT license. - */ - -#ifndef UTILS_CONTINUE_WITH_H -#define UTILS_CONTINUE_WITH_H - -#include -#include -#include - -#include "utils/optional_view.h" -// #include - -#ifdef ENABLE_QJSVALUE_CONTINUATION -#include -#endif - -namespace kamd { -namespace utils { - -namespace detail { //_ -#ifdef ENABLE_QJSVALUE_CONTINUATION - inline void test_continuation(const QJSValue &continuation) - { - if (!continuation.isCallable()) { - qWarning() << "Passed handler is not callable: " << continuation.toString(); - } - } - - template - inline void pass_value(const QFuture<_ReturnType> &future, - QJSValue continuation) - { - auto result = continuation.call({ future.result() }); - if (result.isError()) { - qWarning() << "Handler returned this error: " << result.toString(); - } - } - - inline void pass_value(const QFuture &future, QJSValue continuation) - { - Q_UNUSED(future); - auto result = continuation.call({}); - if (result.isError()) { - qWarning() << "Handler returned this error: " << result.toString(); - } - } -#endif - - template - inline void test_continuation(_Continuation &&continuation) - { - Q_UNUSED(continuation); - } - - template - inline void pass_value(const QFuture<_ReturnType> &future, - _Continuation &&continuation) - { - using namespace kamd::utils; - continuation(future.resultCount() > 0 - ? make_optional_view(future.result()) - : none()); - } - - template - inline void pass_value(_Continuation &&continuation) - { - continuation(); - } - -} //^ namespace detail - -template -inline void continue_with(const QFuture<_ReturnType> &future, - _Continuation &&continuation) -{ - detail::test_continuation(continuation); - - auto watcher = new QFutureWatcher<_ReturnType>(); - QObject::connect(watcher, &QFutureWatcherBase::finished, [=]() mutable { - detail::pass_value(future, continuation); - }); - - watcher->setFuture(future); -} - -} // namespace utils -} // namespace kamd - -#endif /* !UTILS_CONTINUE_WITH_H */ - - diff --git a/libs/kactivities-stats/src/utils/d_ptr.h b/libs/kactivities-stats/src/utils/d_ptr.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/d_ptr.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef D_PTR_H -#define D_PTR_H - -#include - -namespace kamd { -namespace utils { - -template -class d_ptr { -private: - std::unique_ptr d; - -public: - d_ptr(); - - template - d_ptr(Args &&...); - - ~d_ptr(); - - T *operator->() const; -}; - -#define D_PTR \ - class Private; \ - friend class Private; \ - const ::kamd::utils::d_ptr d - -} // namespace utils -} // namespace kamd - -#endif diff --git a/libs/kactivities-stats/src/utils/d_ptr_implementation.h b/libs/kactivities-stats/src/utils/d_ptr_implementation.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/d_ptr_implementation.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef D_PTR_IMPLEMENTATION_H -#define D_PTR_IMPLEMENTATION_H - -#include - -namespace kamd { -namespace utils { - -template -d_ptr::d_ptr() - : d(new T()) -{ -} - -template -template -d_ptr::d_ptr(Args &&... args) - : d(new T(std::forward(args)...)) -{ -} - -template -d_ptr::~d_ptr() -{ -} - -template -T *d_ptr::operator->() const -{ - return d.get(); -} - -} // namespace utils -} // namespace kamd - -#endif diff --git a/libs/kactivities-stats/src/utils/dbusfuture_p.h b/libs/kactivities-stats/src/utils/dbusfuture_p.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/dbusfuture_p.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright (C) 2013 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef ACTIVITIES_DBUSFUTURE_P_H -#define ACTIVITIES_DBUSFUTURE_P_H - -#include -#include -#include -#include -#include -#include -#include - -#include "debug_p.h" - -namespace DBusFuture { - -namespace detail { //_ - -template -class DBusCallFutureInterface : public QObject, - public QFutureInterface<_Result> { -public: - DBusCallFutureInterface(QDBusPendingReply<_Result> reply) - : reply(reply), - replyWatcher(Q_NULLPTR) - { - } - - ~DBusCallFutureInterface() - { - delete replyWatcher; - } - - void callFinished(); - - QFuture<_Result> start() - { - replyWatcher = new QDBusPendingCallWatcher(reply); - - QObject::connect(replyWatcher, - &QDBusPendingCallWatcher::finished, - [this] () { callFinished(); }); - - this->reportStarted(); - - if (reply.isFinished()) { - this->callFinished(); - } - - return this->future(); - } - -private: - QDBusPendingReply<_Result> reply; - QDBusPendingCallWatcher * replyWatcher; -}; - -template -void DBusCallFutureInterface<_Result>::callFinished() -{ - deleteLater(); - - if (!reply.isError()) { - this->reportResult(reply.value()); - } - - this->reportFinished(); -} - -template <> -void DBusCallFutureInterface::callFinished(); - -template -class ValueFutureInterface : public QObject, QFutureInterface<_Result> { -public: - ValueFutureInterface(const _Result & value) - : value(value) - { - } - - QFuture<_Result> start() - { - auto future = this->future(); - - this->reportResult(value); - this->reportFinished(); - - deleteLater(); - - return future; - } - -private: - _Result value; - -}; - -template <> -class ValueFutureInterface : public QObject, QFutureInterface { -public: - ValueFutureInterface(); - - QFuture start(); - // { - // auto future = this->future(); - // this->reportFinished(); - // deleteLater(); - // return future; - // } -}; - -} //^ namespace detail - -template -QFuture<_Result> -asyncCall(QDBusAbstractInterface *interface, const QString &method, - const QVariant &arg1 = QVariant(), const QVariant &arg2 = QVariant(), - const QVariant &arg3 = QVariant(), const QVariant &arg4 = QVariant(), - const QVariant &arg5 = QVariant(), const QVariant &arg6 = QVariant(), - const QVariant &arg7 = QVariant(), const QVariant &arg8 = QVariant()) -{ - using namespace detail; - - auto callFutureInterface = new DBusCallFutureInterface - <_Result>(interface->asyncCall(method, arg1, arg2, arg3, arg4, arg5, - arg6, arg7, arg8)); - - return callFutureInterface->start(); -} - -template -QFuture<_Result> -fromValue(const _Result & value) -{ - using namespace detail; - - auto valueFutureInterface = new ValueFutureInterface<_Result>(value); - - return valueFutureInterface->start(); -} - -template -QFuture<_Result> -fromReply(const QDBusPendingReply<_Result> &reply) -{ - using namespace detail; - - auto callFutureInterface = new DBusCallFutureInterface<_Result>(reply); - - return callFutureInterface->start(); -} - -QFuture fromVoid(); - -} // namespace DBusFuture - -#endif /* DBUSFUTURE_P_H */ - diff --git a/libs/kactivities-stats/src/utils/dbusfuture_p.cpp b/libs/kactivities-stats/src/utils/dbusfuture_p.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/dbusfuture_p.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2013 Ivan Cukic - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License version 2 as published by the Free Software Foundation. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - */ - -#include "dbusfuture_p.h" - -namespace DBusFuture { - -namespace detail { //_ - -template <> -void DBusCallFutureInterface::callFinished() -{ - deleteLater(); - - // qDebug() << "This is call end"; - - this->reportFinished(); -} - -ValueFutureInterface::ValueFutureInterface() -{ -} - -QFuture ValueFutureInterface::start() -{ - auto future = this->future(); - - this->reportFinished(); - - deleteLater(); - - return future; -} - -} //^ namespace detail - -QFuture fromVoid() -{ - using namespace detail; - - auto valueFutureInterface = new ValueFutureInterface(); - - return valueFutureInterface->start(); -} - -} // namespace DBusFuture - diff --git a/libs/kactivities-stats/src/utils/debug_and_return.h b/libs/kactivities-stats/src/utils/debug_and_return.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/debug_and_return.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef DEBUG_AND_RETURN_H -#define DEBUG_AND_RETURN_H - -#ifdef QT_DEBUG -#include -#endif - -namespace kamd { -namespace utils { - -template -T debug_and_return(const char * message, T && value) { - #ifdef QT_DEBUG - qDebug() << message << " " << value; - #endif - - return std::forward(value); -} - -template -T debug_and_return(bool debug, const char * message, T && value) { - #ifdef QT_DEBUG - if (debug) { - qDebug() << message << " " << value; - } - #endif - - return std::forward(value); -} - -} // namespace utils -} // namespace kamd - -#endif // DEBUG_AND_RETURN_H - diff --git a/libs/kactivities-stats/src/utils/for_each_assoc.h b/libs/kactivities-stats/src/utils/for_each_assoc.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/for_each_assoc.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation,3 Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_FOR_EACH_ASSOC_H -#define UTILS_FOR_EACH_ASSOC_H - -#include - -/******************************************************************** - * Associative container's for_each (for hash, map, and similar ) * - ********************************************************************/ - -namespace kamd { -namespace utils { - -namespace details { //_ - -// Iterator Functions - -template -Function qt_for_each_assoc(Iterator start, Iterator end, Function f) -{ - for (; start != end; ++start) - f(start.key(), start.value()); - - return f; -} - -template -Function stl_for_each_assoc(Iterator start, Iterator end, Function f) -{ - for (; start != end; ++start) - f(start->first, start->second); - - return f; -} - -// Container functions - -template -Function _for_each_assoc_helper_container(const Container &c, Function f, - decltype(&Container::constBegin) *) -{ - // STL will never have methods with camelCase :) - return qt_for_each_assoc(c.constBegin(), c.constEnd(), f); -} - -template -Function _for_each_assoc_helper_container(const Container &c, Function f, - Default *) -{ - return stl_for_each_assoc(c.cbegin(), c.cend(), f); -} - -} //^ namespace details - -template -Function for_each_assoc(const Container &c, Function f) -{ - return details::_for_each_assoc_helper_container - (c, f, Q_NULLPTR); -} - -} // namespace utils -} // namespace kamd - -#endif // UTILS_FOR_EACH_ASSOC_H diff --git a/libs/kactivities-stats/src/utils/lazy_val.h b/libs/kactivities-stats/src/utils/lazy_val.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/lazy_val.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_LAZY_VAL_H -#define UTILS_LAZY_VAL_H - -namespace kamd { -namespace utils { - -template -class lazy_val { -public: - lazy_val(F f) - : _f(std::forward(f)) - , valueRetrieved(false) - { - } - -private: - F _f; - mutable decltype(_f()) value; - mutable bool valueRetrieved; - -public: - operator decltype(_f()) () const - { - if (!valueRetrieved) { - valueRetrieved = true; - value = _f(); - } - - return value; - } -}; - -template -inline lazy_val make_lazy_val(F && f) -{ - return lazy_val(std::forward(f)); -} - -} // namespace utils -} // namespace kamd - -#endif // UTILS_LAZY_VAL_H - diff --git a/libs/kactivities-stats/src/utils/member_matcher.h b/libs/kactivities-stats/src/utils/member_matcher.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/member_matcher.h +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_MEMBER_MATCHER_H -#define UTILS_MEMBER_MATCHER_H - -namespace kamd { -namespace utils { - -namespace member_matcher { - struct placeholder {} _; - - namespace detail { //_ - enum ComparisonOperation { - Less, - LessOrEqual, - Equal, - GreaterOrEqual, - Greater - }; - - // Member comparison object - // Call operator returns true if: - // collection item specified item - // where can be <, >, ==, >=, <= - template - struct member_comparator { //_ - - member_comparator(ComparisonOperation comparison, Member member, Value value) - : m_comparator(comparison) - , m_member(member) - , m_value(value) - { - } - - const ComparisonOperation m_comparator; - const Member m_member; - const Value m_value; - - // When passing only a item to compare with, - // it means that we already have the value for comparison. - // For example (member(M) > 5)(2) - template - inline bool operator()(const T &collItem) const - { - return operator()(collItem, m_value); - } - - // When passing the placeholder aka 'ignore' as a value, - // it means that we already have the value for comparison. - // For example (member(M) > 5)(collItem, _) - template - inline bool operator()(const T &collItem, - const placeholder &) const - { - return operator()(collItem, m_value); - } - - // Like the previous one, but with reversed argument order - template - inline bool operator()(const placeholder &, - const T &collItem) const - { - return compare(m_value, (collItem.*m_member)()); - } - - // Comparing two values - // For example (member(M) > _)(item, 5) - template - inline bool operator()(const T &collItem, const V &value) const - { - // TODO: Make this work if the arguments are reversed, - // or even if both arhuments need to be checked - // for the specified member - return compare((collItem.*m_member)(), value); - } - - - private: - template - inline bool compare(const Left &left, const Right &right) const - { - return - m_comparator == Less ? left < right : - m_comparator == LessOrEqual ? left <= right : - m_comparator == Equal ? left == right : - m_comparator == GreaterOrEqual ? left >= right : - m_comparator == Greater ? left > right : - false; - } - - }; //^ - - // Chaining multiple comparators to achieve lexicographical - // comparison of multiple members in order. - // This would me so much nicer with variadic templates... f**ing MSVC. - template - struct member_comparator_chain { - member_comparator_chain(First first, Second second) - : first(first) - , second(second) - { - } - - // Implement if needed... - // template - // inline bool operator()(const T &item) const - // { - // return first(item) || second(item); - // } - - template - inline bool operator()(const T &item, const V &value) const - { - return first(item, value) || - (!first(value, item) && second(item, value)); - } - - First first; - Second second; - }; - - template - inline member_comparator_chain operator&&(First first, - Second second) - { - return member_comparator_chain(first, second); - } - - // Provides syntax sugar for building member comparators - template - struct member_matcher { //_ - member_matcher(Member m) - : m_member(m) - { - } - - #define IMPLEMENT_COMPARISON_OPERATOR(OPERATOR, NAME) \ - template \ - inline member_comparator \ - operator OPERATOR (const Value &value) const \ - { \ - return member_comparator(NAME, m_member, value);\ - } - - IMPLEMENT_COMPARISON_OPERATOR(< , Less) - IMPLEMENT_COMPARISON_OPERATOR(<= , LessOrEqual) - IMPLEMENT_COMPARISON_OPERATOR(== , Equal) - IMPLEMENT_COMPARISON_OPERATOR(>= , GreaterOrEqual) - IMPLEMENT_COMPARISON_OPERATOR(> , Greater) - - #undef IMPLEMENT_COMPARISON_OPERATOR - - Member m_member; - }; //^ - - } //^ namespace detail - - template - detail::member_matcher member(Member m) - { - return detail::member_matcher(m); - } -} // namespace member - - -} // namespace utils -} // namespace kamd - -#endif // UTILS_MEMBER_MATCHER_H diff --git a/libs/kactivities-stats/src/utils/merge_into.h b/libs/kactivities-stats/src/utils/merge_into.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/merge_into.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation,3 Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_MERGE_INTO_H -#define UTILS_MERGE_INTO_H - -namespace kamd { -namespace utils { - -template -inline void merge_into(Container &into, const Container &from) -{ - typename Container::iterator into_begin = into.begin(); - typename Container::iterator into_end = into.end(); - typename Container::const_iterator from_begin = from.begin(); - typename Container::const_iterator from_end = from.end(); - - while (from_begin != from_end) { - while (into_begin != into_end && *from_begin >= *into_begin) - into_begin++; - - into_begin = into.insert(into_begin, *from_begin); - into_begin++; - from_begin++; - } -} - -} // namespace utils -} // namespace kamd - -#endif // UTILS_MERGE_INTO_H diff --git a/libs/kactivities-stats/src/utils/optional_view.h b/libs/kactivities-stats/src/utils/optional_view.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/optional_view.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_OPTIONAL_H -#define UTILS_OPTIONAL_H - -namespace kamd { -namespace utils { - -struct none_t {}; -inline const none_t none() { return none_t(); } - -// A simple implementation of the optional class -// until we can rely on std::optional. -// It is not going to come close in the supported -// features to the std one. -// (we need it in the core library, so we don't -// want to use boost.optional) -template -class optional_view { -public: - explicit optional_view(const T &value) - : m_value(&value) - { - } - - optional_view(const none_t &) - : m_value(Q_NULLPTR) - { - } - - bool is_initialized() const - { - return m_value != Q_NULLPTR; - } - - const T &get() const - { - return *m_value; - } - - const T *operator->() const - { - return m_value; - } - -private: - const T *const m_value; -}; - -template -optional_view make_optional_view(const T &value) -{ - return optional_view(value); -} - -} // namespace utils -} // namespace kamd - - -#endif // UTILS_OPTIONAL_H - diff --git a/libs/kactivities-stats/src/utils/ptr_to.h b/libs/kactivities-stats/src/utils/ptr_to.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/ptr_to.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef PTR_TO_H -#define PTR_TO_H - -namespace kamd { -namespace utils { - -enum { - Const = 0, - Mutable = 1 -}; - -template -struct ptr_to { - typedef const T * const type; -}; - -template -struct ptr_to { - typedef T * const type; -}; - - - -} // namespace utils -} // namespace kamd - -#endif // PTR_TO_H diff --git a/libs/kactivities-stats/src/utils/qsqlquery_iterator.h b/libs/kactivities-stats/src/utils/qsqlquery_iterator.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/qsqlquery_iterator.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2013 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_QSQLQUERYITERATOR_H -#define UTILS_QSQLQUERYITERATOR_H - -#include -#include - -template -class NextValueIterator { -public: - enum Type { - NormalIterator, - EndIterator - }; - - NextValueIterator(ResultSet &query, Type type = NormalIterator) - : m_query(query) - , m_type(type) - { - if (type != EndIterator) { - m_query.next(); - } - } - - inline bool operator!= (const NextValueIterator &other) const - { - Q_UNUSED(other); - return m_query.isValid(); - } - - inline NextValueIterator &operator*() - { - return *this; - } - - inline QVariant operator[] (int index) const - { - return m_query.value(index); - } - - inline QVariant operator[] (const QString &name) const - { - return m_query.value(name); - } - - inline NextValueIterator &operator ++() - { - m_query.next(); - return *this; - } - -private: - ResultSet &m_query; - Type m_type; - -}; - -NextValueIterator begin(QSqlQuery &query); -NextValueIterator end(QSqlQuery &query); - - -#endif /* UTILS_QSQLQUERYITERATOR_H */ - diff --git a/libs/kactivities-stats/src/utils/qsqlquery_iterator.cpp b/libs/kactivities-stats/src/utils/qsqlquery_iterator.cpp deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/qsqlquery_iterator.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2013 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#include "qsqlquery_iterator.h" - -NextValueIterator begin(QSqlQuery &query) -{ - return NextValueIterator(query); -} - -NextValueIterator end(QSqlQuery &query) -{ - return NextValueIterator - (query, NextValueIterator::EndIterator); -} - - - diff --git a/libs/kactivities-stats/src/utils/range.h b/libs/kactivities-stats/src/utils/range.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/range.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation,3 Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_RANGE_H -#define UTILS_RANGE_H - -#include -#include -#include - -/******************************************************************** - * Syntactic sugar for converting ranges to collections * - ********************************************************************/ - -namespace kamd { -namespace utils { - -template -__inline Collection as_collection(Range range) -{ - Collection result; - - boost::copy(range, std::back_inserter(result)); - - return result; -} - -template -__inline auto transformed(Member member, Args... args) - -> decltype(boost::adaptors::transformed( - std::bind(member, args..., std::placeholders::_1))) -{ - return boost::adaptors::transformed( - std::bind(member, args..., std::placeholders::_1) - ); - -} - -template -__inline auto filtered(Member member, Args... args) - -> decltype(boost::adaptors::filtered( - std::bind(member, args..., std::placeholders::_1))) -{ - return boost::adaptors::filtered( - std::bind(member, args..., std::placeholders::_1) - ); - -} - -template -__inline auto filtered(Class *const self, Member member) - -> decltype(boost::adaptors::filtered( - std::bind(member, self, std::placeholders::_1))) -{ - return boost::adaptors::filtered( - std::bind(member, self, std::placeholders::_1) - ); - -} - - -} // namespace utils -} // namespace kamd - -#endif // UTILS_RANGE_H diff --git a/libs/kactivities-stats/src/utils/remove_if.h b/libs/kactivities-stats/src/utils/remove_if.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/remove_if.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2012 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details - * - * You should have received a copy of the GNU Lesser General Public - * License along with this program; if not, write to the - * Free Software Foundation,3 Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_REMOVE_IF_H -#define UTILS_REMOVE_IF_H - -#include -#include - -/******************************************************************** - * Syntactic sugar for the erase-remove idiom * - ********************************************************************/ - -namespace kamd { -namespace utils { - -template -__inline void remove_if(Collection &collection, Filter filter) -{ - collection.erase( - std::remove_if( - collection.begin(), collection.end(), filter), - collection.end()); -} - -} // namespace utils -} // namespace kamd - -#endif // UTILS_REMOVE_IF_H diff --git a/libs/kactivities-stats/src/utils/slide.h b/libs/kactivities-stats/src/utils/slide.h deleted file mode 100644 --- a/libs/kactivities-stats/src/utils/slide.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2015 Ivan Cukic - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License version 2, - * or (at your option) any later version, as published by the Free - * Software Foundation - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details - * - * You should have received a copy of the GNU General Public - * License along with this program; if not, write to the - * Free Software Foundation, Inc., - * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -#ifndef UTILS_SLIDE_H -#define UTILS_SLIDE_H - -#include - -// Inspired by C++ Seasoning talk by Sean Parent - -namespace kamd { -namespace utils { - -template -void slide(Iterator f, Iterator l, Iterator p) -{ - if (p < f) { - std::rotate(p, f, l); - } else if (l < p) { - std::rotate(f, l, p); - } -} - -template -void slide_one(Iterator f, Iterator p) -{ - slide(f, f + 1, p); -} - -} // namespace utils -} // namespace kamd - - -#endif // UTILS_SLIDE_H - diff --git a/libs/kactivities-stats/update.sh b/libs/kactivities-stats/update.sh deleted file mode 100755 --- a/libs/kactivities-stats/update.sh +++ /dev/null @@ -1,49 +0,0 @@ -#!/bin/bash - -current_directory=`pwd` - -if [ -z "$1" ]; then - echo "You need to pass the path to the kactivities directory" - exit 1 -fi - -kactivities_directory=$1 - -pushd $1 - -project_name="`git remote show origin | grep Push | sed 's/.*\///'`" -if [ "$project_name" != "kactivities" ]; then - echo "You need to pass the path to the kactivities directory, not for $project_name" - exit 1 -fi - -kactivities_branch="`git rev-parse --abbrev-ref HEAD`" -if [ "$2" != "--force-branch" -a "$kactivities_branch" != "master" ]; then - echo "The branch of kactivities needs to be master" - echo "Alternatively, you could call $0 $1 --force-branch" - exit 1 -fi - -popd - -echo "will run: rm -fr ./src/lib/stats" -echo "will run: rm -fr ./src/common" -echo "will run: rm -fr ./src/utils" -echo "[enter] to continue, [ctrl+c] to cancel" -read - -rm -fr ./src/lib/stats -rm -fr ./src/common -rm -fr ./src/utils - -echo "will run: cp -a $kactivities_directory/src/lib/stats ./src/lib/stats" -echo "will run: cp -a $kactivities_directory/src/common ./src/common" -echo "will run: cp -a $kactivities_directory/src/utils ./src/utils" -echo "[enter] to continue, [ctrl+c] to cancel" -read - -echo "copying files from kactivities" -cp -a $kactivities_directory/src/lib/stats ./src/lib/stats -cp -a $kactivities_directory/src/common ./src/common -cp -a $kactivities_directory/src/utils ./src/utils -