diff --git a/CMakeLists.txt b/CMakeLists.txt index e43b4cb..794755a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,152 +1,152 @@ project(Apper) cmake_minimum_required(VERSION 3.0) set(APPER_VERSION 0.9.3) set (QT_MIN_VERSION "5.2.0") find_package(ECM REQUIRED NO_MODULE) set(CMAKE_MODULE_PATH ${ECM_MODULE_PATH}) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) include(FindPkgConfig) include(KDEInstallDirs) include(KDECompilerSettings) include(KDECMakeSettings) include(FeatureSummary) include(ECMInstallIcons) find_package(Qt5 ${QT_MIN_VERSION} CONFIG REQUIRED Core DBus Widgets Quick Sql XmlPatterns) # Load the frameworks we need find_package(KF5 REQUIRED COMPONENTS Config DocTools GuiAddons I18n KCMUtils DBusAddons KIO Notifications KDELibs4Support ) find_package(LibKWorkspace REQUIRED) find_package(KDED REQUIRED) -find_package(PackageKitQt5 0.9.0 REQUIRED) +find_package(PackageKitQt5 1.0.0 REQUIRED) find_package(LibKWorkspace REQUIRED) # # Options # # The various parts of Apper that can be built, or not. option(BUILD_APPER "Build the Apper application" ON) option(BUILD_APPERKCM "Build the Apper KDE Control Module" ON) option(BUILD_APPERD "Build the Apper daemon" ON) option(BUILD_DECLARATIVE "Build the Qt Quick plugins" ON) option(BUILD_PKSESSION "Build the PkSession helper application" ON) option(BUILD_PLASMOID "Build the update notifier plasmoid" ON) # Only for Debian based systems option(DEBCONF_SUPPORT "Build Apper with debconf support" OFF) # Yum does not support this option(AUTOREMOVE "Build Apper with auto remove enabled" OFF) set(HAVE_AUTOREMOVE ${AUTOREMOVE}) message(STATUS "Building Apper with auto remove: " ${AUTOREMOVE}) # AppStream application management support option(APPSTREAM "Build Apper with AppStream support" OFF) set(HAVE_APPSTREAM ${APPSTREAM}) message(STATUS "Building Apper with AppStream support: " ${APPSTREAM}) # Enable support for Limba packages option(LIMBA "Build Apper with Limba bundle support" OFF) set(HAVE_LIMBA ${LIMBA}) message(STATUS "Building Apper with Limba support: " ${LIMBA}) option(MAINTAINER "Enable maintainer mode" OFF) if(DEBCONF_SUPPORT) # Tries to find the package, when it finds it, set HAVE_DEBCONFKDE find_package(DebconfKDE REQUIRED) message(STATUS "Building with Debconf support") set(HAVE_DEBCONF ${DEBCONF_SUPPORT}) endif(DEBCONF_SUPPORT) # command to edit the packages origins set(EDIT_ORIGNS_DESKTOP_NAME "" CACHE STRING "Edit origins desktop name") if (EDIT_ORIGNS_DESKTOP_NAME) message(STATUS "Edit origins desktop name: " ${EDIT_ORIGNS_DESKTOP_NAME}) endif(EDIT_ORIGNS_DESKTOP_NAME) # Generate config.h configure_file(${CMAKE_CURRENT_SOURCE_DIR}/config.h.cmake ${CMAKE_CURRENT_BINARY_DIR}/config.h) # # Add definitions # set(MAINTAINER_CFLAGS "") if(MAINTAINER) set(MAINTAINER_CFLAGS "-Werror -Wall -Wcast-align -Wno-uninitialized -Wempty-body -Wformat-security -Winit-self -Wno-deprecated-declarations") if (CMAKE_COMPILER_IS_GNUCC) execute_process(COMMAND ${CMAKE_C_COMPILER} -dumpversion OUTPUT_VARIABLE GCC_VERSION) if (GCC_VERSION VERSION_GREATER 4.9 OR GCC_VERSION VERSION_EQUAL 4.9) set(MAINTAINER_CFLAGS ${MAINTAINER_CFLAGS} "-fdiagnostics-color=auto") endif() endif() endif(MAINTAINER) add_definitions(${MAINTAINER_CFLAGS}) add_definitions("-std=gnu++11") add_definitions( -DQT_USE_QSTRINGBUILDER -DQT_STRICT_ITERATORS -DQT_NO_URL_CAST_FROM_STRING -DQT_NO_CAST_FROM_BYTEARRAY -DQT_NO_SIGNALS_SLOTS_KEYWORDS -DQT_USE_FAST_OPERATOR_PLUS ) # # Global includes # include_directories(${CMAKE_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_BINARY_DIR} ${PackageKitQt5_INCLUDE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/libapper) # # Subcomponents # add_subdirectory(libapper) if(BUILD_APPERKCM) add_subdirectory(ApperKCM) endif(BUILD_APPERKCM) if(BUILD_APPER) add_subdirectory(Apper) endif(BUILD_APPER) if(BUILD_PKSESSION) add_subdirectory(PkSession) endif(BUILD_PKSESSION) if(BUILD_APPERD) add_subdirectory(apperd) endif(BUILD_APPERD) if(BUILD_DECLARATIVE) add_subdirectory(declarative-plugins) endif(BUILD_DECLARATIVE) if(BUILD_PLASMOID) add_subdirectory(plasmoid) endif(BUILD_PLASMOID) if(LIMBA) add_subdirectory(AppSetup) endif() add_subdirectory(doc) feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/apperd/ApperdThread.cpp b/apperd/ApperdThread.cpp index 92dd280..911494f 100644 --- a/apperd/ApperdThread.cpp +++ b/apperd/ApperdThread.cpp @@ -1,335 +1,335 @@ /*************************************************************************** * Copyright (C) 2012 by Daniel Nicoletti * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "ApperdThread.h" #include "RefreshCacheTask.h" #include "Updater.h" #include "DistroUpgrade.h" #include "TransactionWatcher.h" #include "DBusInterface.h" #include "RebootListener.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #define FIVE_MIN 360000 #define ONE_MIN 72000 /* * What we need: * - Refresh the package cache periodicaly (implies listenning to PK's updates changed) * - Update or Display Package Updates * - Display Distro Upgrades * - Start Sentinel to keep an eye on running transactions */ using namespace PackageKit; using namespace Solid; ApperdThread::ApperdThread(QObject *parent) : QObject(parent), m_proxyChanged(true), m_AptRebootListener(new AptRebootListener(this)) { } ApperdThread::~ApperdThread() { } void ApperdThread::init() { connect(PowerManagement::notifier(), SIGNAL(appShouldConserveResourcesChanged(bool)), this, SLOT(appShouldConserveResourcesChanged())); // This timer keeps polling to see if it has // to refresh the cache m_qtimer = new QTimer(this); m_qtimer->setInterval(FIVE_MIN); connect(m_qtimer, SIGNAL(timeout()), this, SLOT(poll())); m_qtimer->start(); //check if any changes to the file occour //this also prevents from reading when a checkUpdate happens KDirWatch *confWatch = new KDirWatch(this); confWatch->addFile(KStandardDirs::locateLocal("config", "apper")); connect(confWatch, SIGNAL(dirty(QString)), this, SLOT(configFileChanged())); connect(confWatch, SIGNAL(created(QString)), this, SLOT(configFileChanged())); connect(confWatch, SIGNAL(deleted(QString)), this, SLOT(configFileChanged())); confWatch->startScan(); // Watch for changes in the KDE proxy settings KDirWatch *proxyWatch = new KDirWatch(this); proxyWatch->addFile(KStandardDirs::locateLocal("config", "kioslaverc")); connect(proxyWatch, SIGNAL(dirty(QString)), this, SLOT(proxyChanged())); connect(proxyWatch, SIGNAL(created(QString)), this, SLOT(proxyChanged())); connect(proxyWatch, SIGNAL(deleted(QString)), this, SLOT(proxyChanged())); proxyWatch->startScan(); - QString locale(KGlobal::locale()->language() % QLatin1Char('.') % KGlobal::locale()->encoding()); + QString locale(KLocale::global()->language() % QLatin1Char('.') % KLocale::global()->encoding()); Daemon::global()->setHints(QLatin1String("locale=") % locale); connect(Daemon::global(), SIGNAL(updatesChanged()), SLOT(updatesChanged())); m_interface = new DBusInterface(this); m_refreshCache = new RefreshCacheTask(this); connect(m_interface, SIGNAL(refreshCache()), m_refreshCache, SLOT(refreshCache())); m_updater = new Updater(this); m_distroUpgrade = new DistroUpgrade(this); // read the current settings configFileChanged(); // In case PackageKit is not running watch for it's registration to configure proxy QDBusServiceWatcher *watcher; watcher = new QDBusServiceWatcher(QLatin1String("org.freedesktop.PackageKit"), QDBusConnection::systemBus(), QDBusServiceWatcher::WatchForRegistration, this); connect(watcher, SIGNAL(serviceRegistered(QString)), SLOT(setProxy())); // if PackageKit is running check to see if there are running transactons already bool packagekitIsRunning = nameHasOwner(QLatin1String("org.freedesktop.PackageKit"), QDBusConnection::systemBus()); m_transactionWatcher = new TransactionWatcher(packagekitIsRunning, this); // connect the watch transaction coming from the updater icon to our watcher connect(m_interface, SIGNAL(watchTransaction(QDBusObjectPath)), m_transactionWatcher, SLOT(watchTransaction(QDBusObjectPath))); // listen to Debian/Apt reboot signals from other sources (apt) connect(m_AptRebootListener, SIGNAL(requestReboot()), m_transactionWatcher, SLOT(showRebootNotificationApt())); QTimer::singleShot(2 /*minutes*/ * 60 /*seconds*/ * 1000 /*msec*/, m_AptRebootListener, SLOT(checkForReboot())); if (packagekitIsRunning) { // PackageKit is running set the session Proxy setProxy(); // If packagekit is already running go check // for updates updatesChanged(); } else { // Initial check for updates QTimer::singleShot(ONE_MIN, this, SLOT(updatesChanged())); } } // This is called every 5 minutes void ApperdThread::poll() { if (m_lastRefreshCache.isNull()) { // This value wasn't set // convert this to QDateTime m_lastRefreshCache = getTimeSinceRefreshCache(); } // If check for updates is active if (m_configs[CFG_INTERVAL].value() != Enum::Never) { // Find out how many seconds passed since last refresh cache uint secsSinceLastRefresh; secsSinceLastRefresh = QDateTime::currentDateTime().toTime_t() - m_lastRefreshCache.toTime_t(); // If lastRefreshCache is null it means that the cache was never refreshed if (m_lastRefreshCache.isNull() || secsSinceLastRefresh > m_configs[CFG_INTERVAL].value()) { bool ignoreBattery = m_configs[CFG_CHECK_UP_BATTERY].value(); bool ignoreMobile = m_configs[CFG_CHECK_UP_MOBILE].value(); if (isSystemReady(ignoreBattery, ignoreMobile)) { m_refreshCache->refreshCache(); } // Invalidate the last time the cache was refreshed m_lastRefreshCache = QDateTime(); } } } void ApperdThread::configFileChanged() { KConfig config("apper"); KConfigGroup checkUpdateGroup(&config, "CheckUpdate"); m_configs[CFG_CHECK_UP_BATTERY] = checkUpdateGroup.readEntry(CFG_CHECK_UP_BATTERY, DEFAULT_CHECK_UP_BATTERY); m_configs[CFG_CHECK_UP_MOBILE] = checkUpdateGroup.readEntry(CFG_CHECK_UP_MOBILE, DEFAULT_CHECK_UP_MOBILE); m_configs[CFG_INSTALL_UP_BATTERY] = checkUpdateGroup.readEntry(CFG_INSTALL_UP_BATTERY, DEFAULT_INSTALL_UP_BATTERY); m_configs[CFG_INSTALL_UP_MOBILE] = checkUpdateGroup.readEntry(CFG_INSTALL_UP_MOBILE, DEFAULT_INSTALL_UP_MOBILE); m_configs[CFG_AUTO_UP] = checkUpdateGroup.readEntry(CFG_AUTO_UP, Enum::AutoUpdateDefault); m_configs[CFG_INTERVAL] = checkUpdateGroup.readEntry(CFG_INTERVAL, Enum::TimeIntervalDefault); m_configs[CFG_DISTRO_UPGRADE] = checkUpdateGroup.readEntry(CFG_DISTRO_UPGRADE, Enum::DistroUpgradeDefault); m_updater->setConfig(m_configs); m_distroUpgrade->setConfig(m_configs); KDirWatch *confWatch = qobject_cast(sender()); if (confWatch) { // Check for updates again since the config changed updatesChanged(); } } void ApperdThread::proxyChanged() { // We must reparse the configuration since the values are all cached KProtocolManager::reparseConfiguration(); QHash proxyConfig; if (KProtocolManager::proxyType() == KProtocolManager::ManualProxy) { proxyConfig["http"] = KProtocolManager::proxyFor("http"); proxyConfig["https"] = KProtocolManager::proxyFor("https"); proxyConfig["ftp"] = KProtocolManager::proxyFor("ftp"); proxyConfig["socks"] = KProtocolManager::proxyFor("socks"); } // Check if the proxy settings really changed to avoid setting them twice if (proxyConfig != m_proxyConfig) { m_proxyConfig = proxyConfig; m_proxyChanged = true; setProxy(); } } void ApperdThread::setProxy() { if (!m_proxyChanged) { return; } // If we were called by the watcher it is because PackageKit is running bool packagekitIsRunning = true; QDBusServiceWatcher *watcher = qobject_cast(sender()); if (!watcher) { packagekitIsRunning = nameHasOwner(QLatin1String("org.freedesktop.PackageKit"), QDBusConnection::systemBus()); } if (packagekitIsRunning) { // Apply the proxy changes only if packagekit is running // use value() to not insert items on the hash Daemon::global()->setProxy(m_proxyConfig.value("http"), m_proxyConfig.value("https"), m_proxyConfig.value("ftp"), m_proxyConfig.value("socks"), QString(), QString()); m_proxyChanged = false; } } void ApperdThread::updatesChanged() { // update the last time the cache was refreshed QDateTime lastCacheRefresh; lastCacheRefresh = getTimeSinceRefreshCache(); if (lastCacheRefresh != m_lastRefreshCache) { m_lastRefreshCache = lastCacheRefresh; } bool ignoreBattery = m_configs[CFG_INSTALL_UP_BATTERY].value(); bool ignoreMobile = m_configs[CFG_INSTALL_UP_MOBILE].value(); // Make sure the user sees the updates m_updater->checkForUpdates(isSystemReady(ignoreBattery, ignoreMobile)); m_distroUpgrade->checkDistroUpgrades(); } void ApperdThread::appShouldConserveResourcesChanged() { bool ignoreBattery = m_configs[CFG_INSTALL_UP_BATTERY].value(); bool ignoreMobile = m_configs[CFG_INSTALL_UP_MOBILE].value(); if (isSystemReady(ignoreBattery, ignoreMobile)) { m_updater->setSystemReady(); } } QDateTime ApperdThread::getTimeSinceRefreshCache() const { uint value = Daemon::global()->getTimeSinceAction(Transaction::RoleRefreshCache); // When the refresh cache value was not yet defined UINT_MAX is returned if (value == UINT_MAX) { return QDateTime(); } else { // Calculate the last time the cache was refreshed by // subtracting the seconds from the current time return QDateTime::currentDateTime().addSecs(value * -1); } } bool ApperdThread::nameHasOwner(const QString &name, const QDBusConnection &connection) { QDBusMessage message; message = QDBusMessage::createMethodCall(QLatin1String("org.freedesktop.DBus"), QLatin1String("/"), QLatin1String("org.freedesktop.DBus"), QLatin1String("NameHasOwner")); message << qVariantFromValue(name); QDBusReply reply = connection.call(message); return reply.value(); } bool ApperdThread::isSystemReady(bool ignoreBattery, bool ignoreMobile) const { // First check if we should conserve resources // check how applications should behave (e.g. on battery power) if (!ignoreBattery && Solid::PowerManagement::appShouldConserveResources()) { kDebug() << "System is not ready, application should conserve resources"; // This was fixed for KDElibs 4.8.5 return false; } // TODO it would be nice is Solid provided this // so we wouldn't be waking up PackageKit for this Solid task. Daemon::Network network = Daemon::global()->networkState(); // test whether network is connected if (network == Daemon::NetworkOffline || network == Daemon::NetworkUnknown) { kDebug() << "System is not ready, network state" << network; return false; } // check how applications should behave (e.g. on battery power) if (!ignoreMobile && network == Daemon::NetworkMobile) { kDebug() << "System is not ready, network state" << network; return false; } return true; } diff --git a/apperd/TransactionWatcher.cpp b/apperd/TransactionWatcher.cpp index b059282..7fd7dd7 100644 --- a/apperd/TransactionWatcher.cpp +++ b/apperd/TransactionWatcher.cpp @@ -1,356 +1,356 @@ /*************************************************************************** * Copyright (C) 2008-2011 by Daniel Nicoletti * * dantti12@gmail.com * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "TransactionWatcher.h" #include "TransactionJob.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include TransactionWatcher::TransactionWatcher(bool packagekitIsRunning, QObject *parent) : QObject(parent), m_inhibitCookie(-1) { m_tracker = new KUiServerJobTracker(this); // keep track of new transactions connect(Daemon::global(), SIGNAL(transactionListChanged(QStringList)), this, SLOT(transactionListChanged(QStringList))); // if PackageKit is running check to see if there are running transactons already if (packagekitIsRunning) { // here we check whether a transaction job should be created or not QList paths = Daemon::global()->getTransactionList(); QStringList tids; foreach (const QDBusObjectPath &path, paths) { tids << path.path(); } transactionListChanged(tids); } } TransactionWatcher::~TransactionWatcher() { // release any cookie that we might have suppressSleep(false, m_inhibitCookie); } void TransactionWatcher::transactionListChanged(const QStringList &tids) { if (tids.isEmpty()) { // release any cookie that we might have suppressSleep(false, m_inhibitCookie); } else { foreach (const QString &tid, tids) { watchTransaction(QDBusObjectPath(tid), false); } } } void TransactionWatcher::watchTransaction(const QDBusObjectPath &tid, bool interactive) { Transaction *transaction; if (!m_transactions.contains(tid)) { // Check if the current transaction is still the same transaction = new Transaction(tid); connect(transaction, SIGNAL(roleChanged()), this, SLOT(transactionReady())); connect(transaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), this, SLOT(finished(PackageKit::Transaction::Exit))); // Store the transaction id m_transactions[tid] = transaction; } else { transaction = m_transactions[tid]; if (transaction->role() != Transaction::RoleUnknown) { // force the first changed or create a TransactionJob transactionChanged(transaction, interactive); } } } void TransactionWatcher::transactionReady() { Transaction *transaction = qobject_cast(sender()); Transaction::Role role = transaction->role(); Transaction::TransactionFlags flags = transaction->transactionFlags(); if (!(flags & Transaction::TransactionFlagOnlyDownload || flags & Transaction::TransactionFlagSimulate) && (role == Transaction::RoleInstallPackages || role == Transaction::RoleInstallFiles || role == Transaction::RoleRemovePackages || role == Transaction::RoleUpdatePackages)) { // AVOID showing messages and restart requires when // the user was just simulating an instalation connect(transaction, SIGNAL(message(PackageKit::Transaction::Message,QString)), this, SLOT(message(PackageKit::Transaction::Message,QString))); connect(transaction, SIGNAL(requireRestart(PackageKit::Transaction::Restart,QString)), this, SLOT(requireRestart(PackageKit::Transaction::Restart,QString))); // Don't let the system sleep while doing some sensible actions suppressSleep(true, m_inhibitCookie, PkStrings::action(role, flags)); } connect(transaction, SIGNAL(isCallerActiveChanged()), SLOT(transactionChanged())); } void TransactionWatcher::showRebootNotificationApt() { // Create the notification about this transaction KNotification *notify = new KNotification("RestartRequired", 0, KNotification::Persistent); connect(notify, SIGNAL(activated(uint)), this, SLOT(logout())); notify->setComponentName("apperd"); QString text("" + i18n("The system update has completed") + ""); text.append("
" + PkStrings::restartType(Transaction::RestartSystem)); notify->setPixmap(PkIcons::restartIcon(Transaction::RestartSystem).pixmap(KPK_ICON_SIZE, KPK_ICON_SIZE)); notify->setText(text); // TODO RestartApplication should be handled differently QStringList actions; actions << i18n("Restart"); notify->setActions(actions); notify->sendEvent(); } void TransactionWatcher::finished(PackageKit::Transaction::Exit exit) { // check if the transaction emitted any require restart Transaction *transaction = qobject_cast(sender()); QDBusObjectPath tid = transaction->tid(); transaction->disconnect(this); m_transactions.remove(tid); m_transactionJob.remove(tid); if (exit == Transaction::ExitSuccess && !transaction->property("restartType").isNull()) { Transaction::Restart type = transaction->property("restartType").value(); QStringList restartPackages = transaction->property("restartPackages").toStringList(); // Create the notification about this transaction KNotification *notify = new KNotification("RestartRequired", 0, KNotification::Persistent); connect(notify, SIGNAL(activated(uint)), this, SLOT(logout())); notify->setComponentName("apperd"); notify->setProperty("restartType", qVariantFromValue(type)); notify->setPixmap(PkIcons::restartIcon(type).pixmap(KPK_ICON_SIZE, KPK_ICON_SIZE)); notify->setTitle(PkStrings::restartType(type)); // Create a readable text with package names that required the restart if (!restartPackages.isEmpty()) { restartPackages.removeDuplicates(); restartPackages.sort(); QString text; text = i18np("Package: %2", "Packages: %2", restartPackages.size(), restartPackages.join(QLatin1String(", "))); notify->setText(text); } // TODO RestartApplication should be handled differently QStringList actions; actions << i18n("Restart"); notify->setActions(actions); notify->sendEvent(); } } void TransactionWatcher::transactionChanged(Transaction *transaction, bool interactive) { if (!transaction) { transaction = qobject_cast(sender()); } QDBusObjectPath tid = transaction->tid(); if (!interactive) { interactive = !transaction->isCallerActive(); } // If the if (!m_transactionJob.contains(tid) && interactive) { TransactionJob *job = new TransactionJob(transaction, this); connect(transaction, SIGNAL(errorCode(PackageKit::Transaction::Error,QString)), this, SLOT(errorCode(PackageKit::Transaction::Error,QString))); connect(job, SIGNAL(canceled()), this, SLOT(watchedCanceled())); m_tracker->registerJob(job); m_transactionJob[tid] = job; job->start(); } } -void TransactionWatcher::message(PackageKit::Transaction::Message type, const QString &message) -{ - KNotification *notify; - notify = new KNotification("TransactionMessage", 0, KNotification::Persistent); - notify->setComponentName("apperd"); - notify->setTitle(PkStrings::message(type)); - notify->setText(message); - - notify->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(KPK_ICON_SIZE, KPK_ICON_SIZE)); - notify->sendEvent(); -} +//void TransactionWatcher::message(PackageKit::Transaction::Message type, const QString &message) +//{ +// KNotification *notify; +// notify = new KNotification("TransactionMessage", 0, KNotification::Persistent); +// notify->setComponentName("apperd"); +// notify->setTitle(PkStrings::message(type)); +// notify->setText(message); + +// notify->setPixmap(QIcon::fromTheme("dialog-warning").pixmap(KPK_ICON_SIZE, KPK_ICON_SIZE)); +// notify->sendEvent(); +//} void TransactionWatcher::errorCode(PackageKit::Transaction::Error err, const QString &details) { KNotification *notify; notify = new KNotification("TransactionError", 0, KNotification::Persistent); notify->setComponentName("apperd"); notify->setTitle(PkStrings::error(err)); notify->setText(PkStrings::errorMessage(err)); notify->setProperty("ErrorType", QVariant::fromValue(err)); notify->setProperty("Details", details); QStringList actions; actions << i18n("Details"); notify->setActions(actions); notify->setPixmap(QIcon::fromTheme("dialog-error").pixmap(KPK_ICON_SIZE, KPK_ICON_SIZE)); connect(notify, SIGNAL(activated(uint)), this, SLOT(errorActivated(uint))); notify->sendEvent(); } void TransactionWatcher::errorActivated(uint action) { KNotification *notify = qobject_cast(sender()); // if the user clicked "Details" if (action == 1) { Transaction::Error error = notify->property("ErrorType").value(); QString details = notify->property("Details").toString(); KMessageBox::detailedSorry(0, PkStrings::errorMessage(error), details.replace('\n', "
"), PkStrings::error(error), KMessageBox::Notify); } notify->close(); } void TransactionWatcher::requireRestart(PackageKit::Transaction::Restart type, const QString &packageID) { Transaction *transaction = qobject_cast(sender()); if (transaction->property("restartType").isNull()) { transaction->setProperty("restartType", qVariantFromValue(type)); } else { Transaction::Restart oldType; oldType = transaction->property("restartType").value(); int old = PackageImportance::restartImportance(oldType); int newer = PackageImportance::restartImportance(type); // Check to see which one is more important if (newer > old) { transaction->setProperty("restartType", qVariantFromValue(type)); } } if (!Transaction::packageName(packageID).isEmpty()) { QStringList restartPackages = transaction->property("restartPackages").toStringList(); restartPackages << Transaction::packageName(packageID); transaction->setProperty("restartPackages", restartPackages); } } void TransactionWatcher::logout() { KNotification *notify = qobject_cast(sender()); Transaction::Restart restartType; restartType = notify->property("restartType").value(); KWorkSpace::ShutdownType shutdownType; switch (restartType) { case Transaction::RestartSystem: case Transaction::RestartSecuritySystem: // The restart type was system shutdownType = KWorkSpace::ShutdownTypeReboot; break; case Transaction::RestartSession: case Transaction::RestartSecuritySession: // The restart type was session shutdownType = KWorkSpace::ShutdownTypeLogout; break; default: kWarning() << "Unknown restart type:" << restartType; return; } // We call KSM server to restart or logout our system KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmYes, shutdownType, KWorkSpace::ShutdownModeInteractive); } void TransactionWatcher::watchedCanceled() { TransactionJob *job = qobject_cast(sender()); if (job->isFinished()) { job->deleteLater(); return; } Transaction::Role role = job->transaction()->role(); if (role != Transaction::RoleCancel && role != Transaction::RoleUnknown) { m_tracker->unregisterJob(job); m_tracker->registerJob(job); job->start(); } } void TransactionWatcher::suppressSleep(bool enable, int &inhibitCookie, const QString &reason) { if (inhibitCookie == -1) { return; } if (enable) { kDebug() << "Begin Suppressing Sleep"; inhibitCookie = Solid::PowerManagement::beginSuppressingSleep(reason); if (inhibitCookie == -1) { kDebug() << "Sleep suppression denied!"; } } else { kDebug() << "Stop Suppressing Sleep"; if (!Solid::PowerManagement::stopSuppressingSleep(inhibitCookie)) { kDebug() << "Stop failed: invalid cookie."; } inhibitCookie = -1; } } diff --git a/apperd/TransactionWatcher.h b/apperd/TransactionWatcher.h index 1a6bed3..b46390c 100644 --- a/apperd/TransactionWatcher.h +++ b/apperd/TransactionWatcher.h @@ -1,72 +1,72 @@ /*************************************************************************** * Copyright (C) 2008-2011 by Daniel Nicoletti * * dantti12@gmail.com * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef TRANSACTION_WATCHER_H #define TRANSACTION_WATCHER_H //#include "AbstractIsRunning.h" #include #include #include using namespace PackageKit; class TransactionJob; class TransactionWatcher : public QObject { Q_OBJECT public: explicit TransactionWatcher(bool packagekitIsRunning, QObject *parent = 0); ~TransactionWatcher(); public Q_SLOTS: void watchTransaction(const QDBusObjectPath &tid, bool interactive = true); void transactionReady(); void showRebootNotificationApt(); private Q_SLOTS: void transactionListChanged(const QStringList &tids); - void message(PackageKit::Transaction::Message type, const QString &message); +// void message(PackageKit::Transaction::Message type, const QString &message); void errorCode(PackageKit::Transaction::Error, const QString &); void errorActivated(uint action); void requireRestart(PackageKit::Transaction::Restart type, const QString &packageID); void finished(PackageKit::Transaction::Exit exit); void transactionChanged(Transaction *transaction = 0, bool interactive = false); void logout(); void watchedCanceled(); private: static void suppressSleep(bool enable, int &inhibitCookie, const QString &reason = QString()); // Hash of transactions we are watching QHash m_transactions; QHash m_transactionJob; // cookie to suppress sleep int m_inhibitCookie; KUiServerJobTracker *m_tracker; }; #endif diff --git a/declarative-plugins/qmlplugins.cpp b/declarative-plugins/qmlplugins.cpp index 915bb25..ba606e9 100644 --- a/declarative-plugins/qmlplugins.cpp +++ b/declarative-plugins/qmlplugins.cpp @@ -1,84 +1,84 @@ /*************************************************************************** * Copyright (C) 2012-2013 by Daniel Nicoletti * * * * 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) 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 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 "qmlplugins.h" #include "daemonhelper.h" #include "DBusUpdaterInterface.h" #include #include #include #include #include #include #include #include #include #include #include void QmlPlugins::registerTypes(const char* uri) { Q_ASSERT(uri == QLatin1String("org.kde.apper")); qmlRegisterType(uri, 0, 1, "DaemonHelper"); qmlRegisterType(uri, 0, 1, "DBusUpdaterInterface"); qmlRegisterType(uri, 0, 1, "PackageModel"); qmlRegisterType(uri, 0, 1, "PkTransaction"); qmlRegisterType(uri, 0, 1, "PkTransactionProgressModel"); qmlRegisterType(uri, 0, 1, "ApplicationSortFilterModel"); qmlRegisterType(uri, 0, 1, "Transaction"); qmlRegisterUncreatableType(uri, 0, 1, "Daemon", "Global"); qRegisterMetaType("PkTransaction::ExitStatus"); qRegisterMetaType("PackageKit::Daemon::Network"); qRegisterMetaType("PackageKit::Daemon::Authorize"); qRegisterMetaType("PackageKit::Transaction::InternalError"); qRegisterMetaType("PackageKit::Transaction::Role"); qRegisterMetaType("PackageKit::Transaction::Error"); qRegisterMetaType("PackageKit::Transaction::Exit"); qRegisterMetaType("PackageKit::Transaction::Filter"); - qRegisterMetaType("PackageKit::Transaction::Message"); +// qRegisterMetaType("PackageKit::Transaction::Message"); qRegisterMetaType("PackageKit::Transaction::Status"); qRegisterMetaType("PackageKit::Transaction::MediaType"); qRegisterMetaType("PackageKit::Transaction::DistroUpgrade"); qRegisterMetaType("PackageKit::Transaction::TransactionFlag"); qRegisterMetaType("PackageKit::Transaction::TransactionFlags"); qRegisterMetaType("PackageKit::Transaction::Restart"); qRegisterMetaType("PackageKit::Transaction::UpdateState"); qRegisterMetaType("PackageKit::Transaction::Group"); qRegisterMetaType("PackageKit::Transaction::Info"); qRegisterMetaType("PackageKit::Transaction::SigType"); } void QmlPlugins::initializeEngine(QQmlEngine *engine, const char *uri) { Q_UNUSED(uri) Q_ASSERT(uri == QLatin1String("org.kde.apper")); KLocalizedString::setApplicationDomain("apper"); engine->rootContext()->setContextProperty("Daemon", Daemon::global()); engine->rootContext()->setContextProperty("PkStrings", new PkStrings); engine->rootContext()->setContextProperty("PkIcons", new PkIcons); engine->rootContext()->setContextProperty("DaemonHelper", new DaemonHelper); } diff --git a/libapper/ApplicationsDelegate.cpp b/libapper/ApplicationsDelegate.cpp index 4bcf720..3278816 100644 --- a/libapper/ApplicationsDelegate.cpp +++ b/libapper/ApplicationsDelegate.cpp @@ -1,343 +1,343 @@ /* * Copyright (C) 2007 Ivan Cukic * Copyright (C) 2008-2011 Daniel Nicoletti * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Library/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 General Public License for more details * * You should have received a copy of the GNU Library/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. */ #include "ApplicationsDelegate.h" #include #include #include #include #include "PackageModel.h" #include "PkIcons.h" #define UNIVERSAL_PADDING 4 #define FADE_LENGTH 16 using namespace PackageKit; ApplicationsDelegate::ApplicationsDelegate(QAbstractItemView *parent) : QStyledItemDelegate(parent), m_viewport(parent->viewport()), // loads it here to be faster when displaying items m_installIcon("go-down"), m_installString(i18n("Install")), m_removeIcon("edit-delete"), m_removeString(i18n("Remove")), m_undoIcon("edit-undo"), m_undoString(i18n("Deselect")), m_checkedIcon("dialog-ok"), m_checkable(false) { m_viewport->setAttribute(Qt::WA_Hover, true); QPushButton button, button2; button.setText(m_installString); button.setIcon(m_installIcon); button2.setText(m_removeString); button2.setIcon(m_removeIcon); m_buttonSize = button.sizeHint(); int width = qMax(button.sizeHint().width(), button2.sizeHint().width()); button.setText(m_undoString); width = qMax(width, button2.sizeHint().width()); m_buttonSize.setWidth(width); m_buttonIconSize = button.iconSize(); } void ApplicationsDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { if (!index.isValid()) { return; } // Button height int btHeight = m_buttonSize.height() + UNIVERSAL_PADDING; if (index.column() == PackageModel::VersionCol || index.column() == PackageModel::CurrentVersionCol || index.column() == PackageModel::ArchCol || index.column() == PackageModel::OriginCol || index.column() == PackageModel::SizeCol) { - QStyleOptionViewItemV4 opt(option); + QStyleOptionViewItem opt(option); if (opt.state & QStyle::State_HasFocus) { opt.state ^= QStyle::State_HasFocus; } painter->save(); QStyledItemDelegate::paint(painter, opt, index); painter->restore(); return; } else if (index.column() == PackageModel::NameCol) { bool leftToRight = (painter->layoutDirection() == Qt::LeftToRight); - QStyleOptionViewItemV4 opt1(option); + QStyleOptionViewItem opt1(option); if (opt1.state & QStyle::State_HasFocus) { opt1.state ^= QStyle::State_HasFocus; } QSize size = QStyledItemDelegate::sizeHint(opt1, index); if (leftToRight) { opt1.rect.setRight(size.width()); } else { opt1.rect.setLeft(option.rect.left() + (option.rect.width() - size.width())); } painter->save(); QStyledItemDelegate::paint(painter, opt1, index); painter->restore(); // a new option for the summary - QStyleOptionViewItemV4 opt(option); + QStyleOptionViewItem opt(option); if (leftToRight) { opt.rect.setLeft(size.width() + 1); } else { opt.rect.setRight(option.rect.left() + (option.rect.width() - size.width()) - 1); } QPixmap pixmap(opt.rect.size()); pixmap.fill(Qt::transparent); QPainter p(&pixmap); if (!p.isActive()) { return; // TODO test if this fixes warnigns } p.translate(-opt.rect.topLeft()); QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); - opt.viewItemPosition = QStyleOptionViewItemV4::Middle; + opt.viewItemPosition = QStyleOptionViewItem::Middle; painter->save(); style->drawPrimitive(QStyle::PE_PanelItemViewItem, &opt, painter, opt.widget); painter->restore(); int left = opt.rect.left(); int width = opt.rect.width(); QString pkgSummary = index.data(PackageModel::SummaryRole).toString(); if (!pkgSummary.isEmpty()) { if (leftToRight) { pkgSummary.prepend(QLatin1String("- ")); } else { pkgSummary.append(QLatin1String(" -")); } } // store the original opacity qreal opa = p.opacity(); QStyleOptionViewItem local_option_normal(opt); QColor foregroundColor; p.setOpacity(0.75); if (opt.state.testFlag(QStyle::State_Selected)) { foregroundColor = opt.palette.color(QPalette::HighlightedText); } else { foregroundColor = opt.palette.color(QPalette::Text); } p.setFont(local_option_normal.font); p.setPen(foregroundColor); p.drawText(opt.rect, Qt::AlignVCenter | (leftToRight ? Qt::AlignLeft : Qt::AlignRight), pkgSummary); p.setOpacity(opa); QLinearGradient gradient; // Gradient part of the background - fading of the text at the end if (leftToRight) { gradient = QLinearGradient(left + width - UNIVERSAL_PADDING - FADE_LENGTH, 0, left + width - UNIVERSAL_PADDING, 0); gradient.setColorAt(0, Qt::white); gradient.setColorAt(1, Qt::transparent); } else { gradient = QLinearGradient(left + UNIVERSAL_PADDING, 0, left + UNIVERSAL_PADDING + FADE_LENGTH, 0); gradient.setColorAt(0, Qt::transparent); gradient.setColorAt(1, Qt::white); } QRect paintRect = opt.rect; p.setCompositionMode(QPainter::CompositionMode_DestinationIn); p.fillRect(paintRect, gradient); if (leftToRight) { gradient.setStart(left + width - (UNIVERSAL_PADDING) - FADE_LENGTH, 0); gradient.setFinalStop(left + width - (UNIVERSAL_PADDING), 0); } else { gradient.setStart(left + UNIVERSAL_PADDING + (UNIVERSAL_PADDING ), 0); gradient.setFinalStop(left + UNIVERSAL_PADDING + (UNIVERSAL_PADDING) + FADE_LENGTH, 0); } paintRect.setHeight(btHeight); p.fillRect(paintRect, gradient); p.setCompositionMode(QPainter::CompositionMode_SourceOver); p.end(); painter->drawPixmap(opt.rect.topLeft(), pixmap); return; } else if (index.column() == PackageModel::ActionCol) { bool pkgChecked = index.data(PackageModel::CheckStateRole).toBool(); - QStyleOptionViewItemV4 opt(option); + QStyleOptionViewItem opt(option); if (opt.state & QStyle::State_HasFocus) { opt.state ^= QStyle::State_HasFocus; } // Do not draw if the line is not selected or the mouse is over it if (!(option.state & QStyle::State_MouseOver) && !(option.state & QStyle::State_Selected) && !pkgChecked) { QStyledItemDelegate::paint(painter, opt, index); return; } QStyledItemDelegate::paint(painter, opt, index); QStyle *style = opt.widget ? opt.widget->style() : QApplication::style(); QStyleOptionButton optBt; optBt.rect = option.rect; Transaction::Info info; info = index.data(PackageModel::InfoRole).value(); bool pkgInstalled = (info == Transaction::InfoInstalled || info == Transaction::InfoCollectionInstalled); // Calculate the top of the button which is the item height - the button height size divided by 2 // this give us a little value which is the top and bottom margin optBt.rect.setLeft(optBt.rect.left() + UNIVERSAL_PADDING / 2); optBt.rect.setTop(optBt.rect.top() + ((btHeight - m_buttonSize.height()) / 2)); optBt.rect.setSize(m_buttonSize); // the width and height sizes of the button if (option.state & QStyle::State_Selected) { optBt.palette.setColor(QPalette::WindowText, option.palette.color(QPalette::HighlightedText)); } optBt.features = QStyleOptionButton::Flat; optBt.iconSize = m_buttonIconSize; if (pkgChecked) { optBt.state |= QStyle::State_Sunken | QStyle::State_Active | QStyle::State_Enabled;; } else { if (option.state & QStyle::State_MouseOver) { optBt.state |= QStyle::State_MouseOver; } optBt.state |= QStyle::State_Raised | QStyle::State_Active | QStyle::State_Enabled; } optBt.icon = pkgInstalled ? m_removeIcon : m_installIcon; optBt.text = pkgInstalled ? m_removeString : m_installString; style->drawControl(QStyle::CE_PushButton, &optBt, painter); return; } } bool ApplicationsDelegate::insideButton(const QRect &rect, const QPoint &pos) const { // kDebug() << rect << pos; if ((pos.x() >= rect.x() && (pos.x() <= rect.x() + rect.width())) && (pos.y() >= rect.y() && (pos.y() <= rect.y() + rect.height()))) { return true; } return false; } bool ApplicationsDelegate::editorEvent(QEvent *event, QAbstractItemModel *model, const QStyleOptionViewItem &option, const QModelIndex &index) { bool setData = false; if (index.column() == PackageModel::ActionCol && event->type() == QEvent::MouseButtonPress) { setData = true; } const QWidget *widget = 0; - if (const QStyleOptionViewItemV4 *v4 = qstyleoption_cast(&option)) { - widget = v4->widget; + if (const QStyleOptionViewItem *v = qstyleoption_cast(&option)) { + widget = v->widget; } QStyle *style = widget ? widget->style() : QApplication::style(); // make sure that we have the right event type if ((event->type() == QEvent::MouseButtonRelease) || (event->type() == QEvent::MouseButtonDblClick)) { - QStyleOptionViewItemV4 viewOpt(option); + QStyleOptionViewItem viewOpt(option); initStyleOption(&viewOpt, index); QRect checkRect = style->subElementRect(QStyle::SE_ItemViewItemCheckIndicator, &viewOpt, widget); QMouseEvent *me = static_cast(event); if (me->button() != Qt::LeftButton || !checkRect.contains(me->pos())) return false; // eat the double click events inside the check rect if (event->type() == QEvent::MouseButtonDblClick) return true; setData = true; } else if (event->type() == QEvent::KeyPress) { if (static_cast(event)->key() == Qt::Key_Space || static_cast(event)->key() == Qt::Key_Select) { setData = true; } } if (setData) { return model->setData(index, !index.data(PackageModel::CheckStateRole).toBool(), Qt::CheckStateRole); } return false; } void ApplicationsDelegate::setCheckable(bool checkable) { m_checkable = checkable; } QSize ApplicationsDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { QSize size; // kDebug() << index; if (index.column() == PackageModel::ActionCol) { size = m_buttonSize; size.rheight() += UNIVERSAL_PADDING; size.rwidth() += UNIVERSAL_PADDING; } else { QFontMetrics metric = QFontMetrics(option.font); // Button size is always bigger than text (since it has text in it size.setHeight(m_buttonSize.height() + UNIVERSAL_PADDING); size.setWidth(metric.width(index.data().toString())); if (index.column() == PackageModel::NameCol) { if (m_checkable) { const QStyle *style = QApplication::style(); QRect rect = style->subElementRect(QStyle::SE_CheckBoxIndicator, &option); // Adds the icon size AND the checkbox size // [ x ] (icon) Text size.rwidth() += 4 * UNIVERSAL_PADDING + 46 + rect.width(); // return QStyledItemDelegate::sizeHint(option, index); } else { // Adds the icon size size.rwidth() += 3 * UNIVERSAL_PADDING + 44; } } else { size.rwidth() += 2 * UNIVERSAL_PADDING; } } return size; } #include "ApplicationsDelegate.moc" diff --git a/libapper/CustomProgressBar.cpp b/libapper/CustomProgressBar.cpp index cffc529..066b426 100644 --- a/libapper/CustomProgressBar.cpp +++ b/libapper/CustomProgressBar.cpp @@ -1,49 +1,49 @@ /*************************************************************************** * Copyright (C) 2009-2011 by Daniel Nicoletti * * dantti12@gmail.com * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "CustomProgressBar.h" #include #include CustomProgressBar::CustomProgressBar(QWidget *parent) : QProgressBar(parent), m_remaining(0) { } CustomProgressBar::~CustomProgressBar() { } QString CustomProgressBar::text() const { if (m_remaining) { - return i18n("%1 remaining", KGlobal::locale()->prettyFormatDuration(m_remaining * 1000)); + return i18n("%1 remaining", KLocale::global()->prettyFormatDuration(m_remaining * 1000)); } else { return QProgressBar::text(); } } void CustomProgressBar::setRemaining(uint remaining) { m_remaining = remaining; } #include "CustomProgressBar.moc" diff --git a/libapper/PackageModel.cpp b/libapper/PackageModel.cpp index 7fb41c9..47caffc 100644 --- a/libapper/PackageModel.cpp +++ b/libapper/PackageModel.cpp @@ -1,891 +1,886 @@ /*************************************************************************** * Copyright (C) 2008-2011 by Daniel Nicoletti * * dantti12@gmail.com * * Copyright (C) 2008 by Trever Fischer * * wm161@wm161.net * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include #include "PackageModel.h" #include #include #include #include #include #include #include #include #include #ifdef HAVE_APPSTREAM #include #endif #ifndef HAVE_APPSTREAM #include #include #endif #define ICON_SIZE 22 #define OVERLAY_SIZE 16 using namespace PackageKit; PackageModel::PackageModel(QObject *parent) : QAbstractItemModel(parent), m_finished(false), m_checkable(false), m_fetchSizesTransaction(0), m_fetchInstalledVersionsTransaction(0) { m_installedEmblem = PkIcons::getIcon("dialog-ok-apply", QString()).pixmap(16, 16); QHash roles = roleNames(); roles[SortRole] = "rSort"; roles[NameRole] = "rName"; roles[SummaryRole] = "rSummary"; roles[VersionRole] = "rVersion"; roles[ArchRole] = "rArch"; roles[IconRole] = "rIcon"; roles[IdRole] = "rId"; roles[CheckStateRole] = "rChecked"; roles[InfoRole] = "rInfo"; roles[ApplicationId] = "rApplicationId"; roles[IsPackageRole] = "rIsPackageRole"; roles[PackageName] = "rPackageName"; roles[InfoIconRole] = "rInfoIcon"; setRoleNames(roles); } void PackageModel::addSelectedPackagesFromModel(PackageModel *model) { QList packages = model->internalSelectedPackages(); foreach (const InternalPackage &package, packages) { addPackage(package.info, package.packageID, package.summary, true); } finished(); } void PackageModel::addPackage(Transaction::Info info, const QString &packageID, const QString &summary, bool selected) { if (m_finished) { qDebug() << Q_FUNC_INFO << "we are finished calling clear"; clear(); } switch(info) { case Transaction::InfoBlocked: case Transaction::InfoFinished: case Transaction::InfoCleanup: return; default: break; } #ifdef HAVE_APPSTREAM QList applications; if (!m_checkable) { applications = AppStream::instance()->applications(Transaction::packageName(packageID)); foreach (const AppStream::Application &app, applications) { InternalPackage iPackage; iPackage.info = info; iPackage.packageID = packageID; iPackage.version = Transaction::packageVersion(packageID); iPackage.arch = Transaction::packageArch(packageID); iPackage.repo = Transaction::packageData(packageID); iPackage.isPackage = false; if (app.name.isEmpty()) { iPackage.displayName = Transaction::packageName(packageID); } else { iPackage.displayName = app.name; } if (app.summary.isEmpty()) { iPackage.summary = summary; } else { iPackage.summary = app.summary; } iPackage.icon = app.icon_url; iPackage.appId = app.id; iPackage.size = 0; if (selected) { checkPackage(iPackage, false); } m_packages.append(iPackage); } } if (applications.isEmpty()) { #endif //HAVE_APPSTREAM InternalPackage iPackage; iPackage.info = info; iPackage.packageID = packageID; iPackage.displayName = Transaction::packageName(packageID); iPackage.version = Transaction::packageVersion(packageID); iPackage.arch = Transaction::packageArch(packageID); iPackage.repo = Transaction::packageData(packageID); iPackage.summary = summary; iPackage.size = 0; #ifdef HAVE_APPSTREAM iPackage.icon = AppStream::instance()->genericIcon(Transaction::packageName(packageID)); if (iPackage.icon.isEmpty()) iPackage.icon = Transaction::packageIcon(packageID); if (m_checkable) { // in case of updates model only check if it's an app applications = AppStream::instance()->applications(Transaction::packageName(packageID)); if (!applications.isEmpty() || !Transaction::packageIcon(packageID).isEmpty()) { iPackage.isPackage = false; } else { iPackage.isPackage = true; } } else { iPackage.isPackage = true; } #else - iPackage.icon = Transaction::packageIcon(packageID); - if (iPackage.icon.isEmpty()) { - iPackage.isPackage = true; - } else { - iPackage.isPackage = false; - QSqlDatabase db = QSqlDatabase::database(); - QSqlQuery query(db); - query.prepare("SELECT filename FROM cache WHERE package = :name"); - query.bindValue(":name", Transaction::packageName(packageID)); - if (query.exec()) { - if (query.next()) { - QString filename = query.value(0).toString(); - filename.remove(QRegExp(".desktop$")).remove(QRegExp("^/.*/")); - iPackage.appId = filename; - } + iPackage.isPackage = false; + QSqlDatabase db = QSqlDatabase::database(); + QSqlQuery query(db); + query.prepare("SELECT filename FROM cache WHERE package = :name"); + query.bindValue(":name", Transaction::packageName(packageID)); + if (query.exec()) { + if (query.next()) { + QString filename = query.value(0).toString(); + filename.remove(QRegExp(".desktop$")).remove(QRegExp("^/.*/")); + iPackage.appId = filename; } } #endif // HAVE_APPSTREAM if (selected) { checkPackage(iPackage, false); } m_packages.append(iPackage); #ifdef HAVE_APPSTREAM } #endif // HAVE_APPSTREAM } void PackageModel::addSelectedPackage(Transaction::Info info, const QString &packageID, const QString &summary) { addPackage(info, packageID, summary, true); } QVariant PackageModel::headerData(int section, Qt::Orientation orientation, int role) const { QVariant ret; if (orientation == Qt::Horizontal && role == Qt::DisplayRole) { switch (section) { case NameCol: if (m_checkable) { ret = PkStrings::packageQuantity(true, m_packages.size(), m_checkedPackages.size()); } else { ret = i18n("Name"); } break; case VersionCol: ret = i18n("Version"); break; case CurrentVersionCol: ret = i18n("Installed Version"); break; case ArchCol: ret = i18n("Arch"); break; case OriginCol: ret = i18n("Origin"); break; case SizeCol: ret = i18n("Size"); break; case ActionCol: ret = i18n("Action"); break; } } return ret; } int PackageModel::rowCount(const QModelIndex &parent) const { if (parent.isValid() || !m_finished) { return 0; } return m_packages.size(); } QModelIndex PackageModel::index(int row, int column, const QModelIndex &parent) const { // kDebug() << parent.isValid() << m_packageCount << row << column; // Check to see if the index isn't out of list if (!parent.isValid() && m_packages.size() > row) { return createIndex(row, column); } return QModelIndex(); } QModelIndex PackageModel::parent(const QModelIndex &index) const { Q_UNUSED(index) return QModelIndex(); } QVariant PackageModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) { return QVariant(); } const InternalPackage &package = m_packages[index.row()]; if (index.column() == NameCol) { switch (role) { case Qt::CheckStateRole: if (!m_checkable) { return QVariant(); } case CheckStateRole: if (containsChecked(package.packageID)) { return Qt::Checked; } return Qt::Unchecked; case IsPackageRole: return package.isPackage; case Qt::DisplayRole: return package.displayName; case Qt::DecorationRole: { QPixmap icon = QPixmap(44, ICON_SIZE); icon.fill(Qt::transparent); if (!package.icon.isNull()) { QPixmap pixmap; if (package.icon.startsWith("/")) { pixmap = QPixmap(); pixmap.load(package.icon); pixmap = pixmap.scaledToHeight(ICON_SIZE); } else { pixmap = KIconLoader::global()->loadIcon(package.icon, KIconLoader::NoGroup, ICON_SIZE, KIconLoader::DefaultState, QStringList(), 0L, true); } if (!pixmap.isNull()) { QPainter painter(&icon); painter.drawPixmap(QPoint(2, 0), pixmap); } } if (package.info == Transaction::InfoInstalled || package.info == Transaction::InfoCollectionInstalled) { QPainter painter(&icon); QPoint startPoint; // bottom right corner startPoint = QPoint(44 - OVERLAY_SIZE, 4); painter.drawPixmap(startPoint, m_installedEmblem); } else if (m_checkable) { QIcon emblemIcon = PkIcons::packageIcon(package.info); QPainter painter(&icon); QPoint startPoint; // bottom right corner startPoint = QPoint(44 - OVERLAY_SIZE, 4); painter.drawPixmap(startPoint, emblemIcon.pixmap(OVERLAY_SIZE, OVERLAY_SIZE)); } return icon; } case PackageName: return Transaction::packageName(package.packageID); case Qt::ToolTipRole: if (m_checkable) { return PkStrings::info(package.info); } else { return i18n("Version: %1\nArchitecture: %2", package.version, package.arch); } } } else if (role == Qt::DisplayRole) { if (index.column() == VersionCol) { return package.version; } else if (index.column() == CurrentVersionCol) { return package.currentVersion; } else if (index.column() == ArchCol) { return package.arch; } else if (index.column() == OriginCol) { return package.repo; } else if (index.column() == SizeCol) { - return package.size ? KGlobal::locale()->formatByteSize(package.size) : QString(); + return package.size ? KLocale::global()->formatByteSize(package.size) : QString(); } } else if (index.column() == SizeCol && role == Qt::TextAlignmentRole) { return static_cast(Qt::AlignRight | Qt::AlignVCenter); } switch (role) { case IconRole: return package.icon; case SortRole: return QString(package.displayName % QLatin1Char(' ') % package.version % QLatin1Char(' ') % package.arch); case CheckStateRole: if (containsChecked(package.packageID)) { return Qt::Checked; } return Qt::Unchecked; case IdRole: return package.packageID; case NameRole: return package.displayName; case SummaryRole: return package.summary; case VersionRole: return package.version; case ArchRole: return package.arch; case OriginCol: return package.repo; case InfoRole: return qVariantFromValue(package.info); case KCategorizedSortFilterProxyModel::CategoryDisplayRole: if (package.info == Transaction::InfoInstalled || package.info == Transaction::InfoCollectionInstalled) { return i18n("To be Removed"); } else { return i18n("To be Installed"); } case KCategorizedSortFilterProxyModel::CategorySortRole: // USING 0 here seems to let things unsorted return package.isPackage ? 1 : 0; // Packages comes after applications case ApplicationId: return package.appId; case InfoIconRole: return PkIcons::packageIcon(package.info); default: return QVariant(); } return QVariant(); } bool PackageModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role == Qt::CheckStateRole && m_packages.size() > index.row()) { if (value.toBool()) { checkPackage(m_packages[index.row()]); } else { uncheckPackage(m_packages[index.row()].packageID); } emit changed(!m_checkedPackages.isEmpty()); return true; } return false; } Qt::ItemFlags PackageModel::flags(const QModelIndex &index) const { if (index.column() == NameCol) { return Qt::ItemIsUserCheckable | Qt::ItemIsEnabled | QAbstractItemModel::flags(index); } return QAbstractItemModel::flags(index); } int PackageModel::columnCount(const QModelIndex &parent) const { Q_UNUSED(parent); if (m_checkable) { // when the model is checkable the action column is not shown return ActionCol; } else { return ActionCol + 1; } } void PackageModel::removePackage(const QString &packageID) { int i = 0; while (i < m_packages.size()) { InternalPackage iPackage = m_packages[i]; if (iPackage.packageID == packageID && iPackage.info != Transaction::InfoUntrusted) { beginRemoveRows(QModelIndex(), i, i); m_packages.remove(i); endRemoveRows(); // since we removed one entry we don't // need to increase the counter continue; } ++i; } } void PackageModel::clear() { qDebug() << Q_FUNC_INFO; beginRemoveRows(QModelIndex(), 0, m_packages.size()); m_finished = false; m_packages.clear(); m_fetchSizesTransaction = 0; m_fetchInstalledVersionsTransaction = 0; if (m_getUpdatesTransaction) { m_getUpdatesTransaction->disconnect(this); m_getUpdatesTransaction->cancel(); } endRemoveRows(); } void PackageModel::clearSelectedNotPresent() { foreach (const InternalPackage &package, m_checkedPackages) { bool notFound = true; foreach (const InternalPackage &iPackage, m_packages) { if (iPackage.packageID == package.packageID) { notFound = false; break; } } if (notFound) { // Uncheck the package If it's not in the model uncheckPackage(package.packageID); } } } bool PackageModel::checkable() const { return m_checkable; } void PackageModel::uncheckInstalledPackages() { foreach (const InternalPackage &package, m_checkedPackages) { if (package.info == Transaction::InfoInstalled || package.info == Transaction::InfoCollectionInstalled) { uncheckPackage(package.packageID, true); } } } void PackageModel::uncheckAvailablePackages() { foreach (const InternalPackage &package, m_checkedPackages) { if (package.info == Transaction::InfoAvailable || package.info == Transaction::InfoCollectionAvailable) { uncheckPackage(package.packageID, true); } } } void PackageModel::finished() { Transaction *trans = qobject_cast(sender()); qDebug() << Q_FUNC_INFO << trans << sender(); if (trans /*== m_getUpdatesTransaction*/) { // m_getUpdatesTransaction = 0; // When pkd dies this method is called twice // pk-qt2 bug.. trans->disconnect(this, SLOT(finished())); } // The whole structure is about to change if (!m_packages.isEmpty()) { beginInsertRows(QModelIndex(), 0, m_packages.size() - 1); m_finished = true; endInsertRows(); } emit changed(!m_checkedPackages.isEmpty()); } void PackageModel::fetchSizes() { if (m_fetchSizesTransaction) { return; } // get package size QStringList pkgs; foreach (const InternalPackage &p, m_packages) { pkgs << p.packageID; } if (!pkgs.isEmpty()) { m_fetchSizesTransaction = Daemon::getDetails(pkgs); connect(m_fetchSizesTransaction, SIGNAL(details(PackageKit::Details)), SLOT(updateSize(PackageKit::Details))); connect(m_fetchSizesTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), this, SLOT(fetchSizesFinished())); } } void PackageModel::fetchSizesFinished() { Transaction *trans = qobject_cast(sender()); if (trans) { // When pkd dies this method is called twice // pk-qt2 bug.. trans->disconnect(this, SLOT(fetchSizesFinished())); } // emit this after all is changed otherwise on large models it will // be hell slow... emit dataChanged(createIndex(0, SizeCol), createIndex(m_packages.size(), SizeCol)); emit changed(!m_checkedPackages.isEmpty()); } void PackageModel::updateSize(const PackageKit::Details &details) { // if size is 0 don't waste time looking for the package qulonglong size = details.size(); if (size == 0) { return; } for (int i = 0; i < m_packages.size(); ++i) { const QString &packageId = details.packageId(); if (packageId == m_packages[i].packageID) { m_packages[i].size = size; if (m_checkable) { // updates the checked packages as well if (m_checkedPackages.contains(packageId)) { // Avoid checking packages that aren't checked m_checkedPackages[packageId].size = size; } break; } #ifdef HAVE_APPSTREAM if (m_checkable) { // checkable models don't have duplicated package ids // so don't waste time scanning all list break; } #else // Without AppStream we don't have duplicated package ids break; #endif // HAVE_APPSTREAM } } } void PackageModel::fetchCurrentVersions() { if (m_fetchInstalledVersionsTransaction) { return; } // get package current version QStringList pkgs; foreach (const InternalPackage &p, m_packages) { pkgs << Transaction::packageName(p.packageID); } if (!pkgs.isEmpty()) { m_fetchInstalledVersionsTransaction = Daemon::resolve(pkgs, Transaction::FilterInstalled);; connect(m_fetchInstalledVersionsTransaction, SIGNAL(package(PackageKit::Transaction::Info,QString,QString)), this, SLOT(updateCurrentVersion(PackageKit::Transaction::Info,QString,QString))); connect(m_fetchInstalledVersionsTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), this, SLOT(fetchCurrentVersionsFinished())); } } void PackageModel::fetchCurrentVersionsFinished() { Transaction *trans = qobject_cast(sender()); if (trans) { // When pkd dies this method is called twice // pk-qt2 bug.. trans->disconnect(this, SLOT(fetchCurrentVersionsFinished())); } // emit this after all is changed otherwise on large models it will // be hell slow... emit dataChanged(createIndex(0, CurrentVersionCol), createIndex(m_packages.size(), CurrentVersionCol)); emit changed(!m_checkedPackages.isEmpty()); } void PackageModel::updateCurrentVersion(Transaction::Info info, const QString &packageID, const QString &summary) { Q_UNUSED(info) Q_UNUSED(summary) // if current version is empty don't waste time looking if (!Transaction::packageVersion(packageID).isEmpty()) { for (int i = 0; i < m_packages.size(); ++i) { if (Transaction::packageName(packageID) == Transaction::packageName(m_packages[i].packageID) && Transaction::packageArch(packageID) == m_packages[i].arch) { m_packages[i].currentVersion = Transaction::packageVersion(packageID); if (m_checkable) { // updates the checked packages as well if (m_checkedPackages.contains(m_packages[i].packageID)) { // Avoid checking packages that aren't checked m_checkedPackages[m_packages[i].packageID].currentVersion = Transaction::packageVersion(packageID); } break; } } } } } void PackageModel::getUpdates(bool fetchCurrentVersions, bool selected) { clear(); m_getUpdatesTransaction = Daemon::getUpdates(); if (selected) { connect(m_getUpdatesTransaction, SIGNAL(package(PackageKit::Transaction::Info,QString,QString)), this, SLOT(addSelectedPackage(PackageKit::Transaction::Info,QString,QString))); } else { connect(m_getUpdatesTransaction, SIGNAL(package(PackageKit::Transaction::Info,QString,QString)), this, SLOT(addPackage(PackageKit::Transaction::Info,QString,QString))); } connect(m_getUpdatesTransaction, SIGNAL(errorCode(PackageKit::Transaction::Error,QString)), this, SLOT(errorCode(PackageKit::Transaction::Error,QString))); // connect(m_getUpdatesTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), // m_busySeq, SLOT(stop())); // connect(m_getUpdatesTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), // this, SLOT(finished())); // This is required to estimate download size connect(m_getUpdatesTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), this, SLOT(fetchSizes())); if (fetchCurrentVersions) { connect(m_getUpdatesTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), this, SLOT(fetchCurrentVersions())); } connect(m_getUpdatesTransaction, SIGNAL(finished(PackageKit::Transaction::Exit,uint)), this, SLOT(getUpdatesFinished())); // get all updates } void PackageModel::toggleSelection(const QString &packageID) { if (containsChecked(packageID)) { uncheckPackage(packageID, true); } else { foreach (const InternalPackage &package, m_packages) { if (package.packageID == packageID) { checkPackage(package); break; } } } } QString PackageModel::selectionStateText() const { return headerData(NameCol, Qt::Horizontal).toString(); } bool PackageModel::hasChanges() const { return !m_checkedPackages.isEmpty(); } int PackageModel::countInfo(PackageKit::Transaction::Info info) const { int ret = 0; foreach (const InternalPackage &package, m_packages) { if (package.info == info) { ++ret; } } return ret; } void PackageModel::checkPackage(const InternalPackage &package, bool emitDataChanged) { QString pkgId = package.packageID; if (!containsChecked(pkgId)) { m_checkedPackages[pkgId] = package; // A checkable model does not have duplicated entries if (emitDataChanged || !m_checkable || !m_packages.isEmpty()) { // This is a slow operation so in case the user // is unchecking all of the packages there is // no need to emit data changed for every item for (int i = 0; i < m_packages.size(); ++i) { if (m_packages[i].packageID == pkgId) { QModelIndex index = createIndex(i, 0); emit dataChanged(index, index); } } // The model might not be displayed yet if (m_finished) { emit changed(!m_checkedPackages.isEmpty()); } } } } void PackageModel::uncheckPackage(const QString &packageID, bool forceEmitUnchecked, bool emitDataChanged) { if (containsChecked(packageID)) { m_checkedPackages.remove(packageID); if (forceEmitUnchecked || sender() == 0) { // The package might be removed by rmSelectedPackage // If we don't copy it the browse model won't uncheck there // right package emit packageUnchecked(packageID); } if (emitDataChanged || !m_checkable) { // This is a slow operation so in case the user // is unchecking all of the packages there is // no need to emit data changed for every item for (int i = 0; i < m_packages.size(); ++i) { if (m_packages[i].packageID == packageID) { QModelIndex index = createIndex(i, 0); emit dataChanged(index, index); } } // The model might not be displayed yet if (m_finished) { emit changed(!m_checkedPackages.isEmpty()); } } } } QList PackageModel::internalSelectedPackages() const { QList ret; QHash::const_iterator i = m_checkedPackages.constBegin(); while (i != m_checkedPackages.constEnd()) { ret << i.value(); ++i; } return ret; } bool PackageModel::containsChecked(const QString &pid) const { if (m_checkedPackages.isEmpty()) { return false; } return m_checkedPackages.contains(pid); } void PackageModel::setAllChecked(bool checked) { if (checked) { m_checkedPackages.clear(); foreach (const InternalPackage &package, m_packages) { checkPackage(package, false); } emit dataChanged(createIndex(0, 0), createIndex(m_packages.size(), 0)); } else { // This is a very slow operation, which in here we try to optimize foreach (const InternalPackage &package, m_checkedPackages) { uncheckPackage(package.packageID, true, false); } emit dataChanged(createIndex(0, 0), createIndex(m_packages.size(), 0)); } emit changed(!m_checkedPackages.isEmpty()); } QStringList PackageModel::selectedPackagesToInstall() const { QStringList list; foreach (const InternalPackage &package, m_checkedPackages) { if (package.info != Transaction::InfoInstalled && package.info != Transaction::InfoCollectionInstalled) { // append the packages are not installed list << package.packageID; } } return list; } QStringList PackageModel::selectedPackagesToRemove() const { QStringList list; foreach (const InternalPackage &package, m_checkedPackages) { if (package.info == Transaction::InfoInstalled || package.info == Transaction::InfoCollectionInstalled) { // check what packages are installed and marked to be removed list << package.packageID; } } return list; } QStringList PackageModel::packagesWithInfo(Transaction::Info info) const { QStringList list; foreach (const InternalPackage &package, m_packages) { if (package.info == info) { // Append to the list if the package matches the info value list << package.packageID; } } return list; } QStringList PackageModel::packageIDs() const { QStringList list; foreach (const InternalPackage &package, m_packages) { list << package.packageID; } return list; } unsigned long PackageModel::downloadSize() const { unsigned long size = 0; foreach (const InternalPackage &package, m_checkedPackages) { size += package.size; } return size; } bool PackageModel::allSelected() const { foreach (const InternalPackage &package, m_packages) { if (!containsChecked(package.packageID)) { return false; } } return true; } void PackageModel::setCheckable(bool checkable) { m_checkable = checkable; } #include "PackageModel.moc" diff --git a/libapper/PkStrings.cpp b/libapper/PkStrings.cpp index 171eacd..3ccf6e0 100644 --- a/libapper/PkStrings.cpp +++ b/libapper/PkStrings.cpp @@ -1,1054 +1,1054 @@ /*************************************************************************** * Copyright (C) 2008-2011 by Daniel Nicoletti * * dantti12@gmail.com * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "PkStrings.h" #include #include #include using namespace PackageKit; QString PkStrings::status(Transaction::Status status, uint speed, qulonglong downloadRemaining) { switch (status) { case Transaction::StatusUnknown: return i18nc("This is when the transaction status is not known", "Unknown state"); case Transaction::StatusSetup: return i18nc("transaction state, the daemon is in the process of starting", "Waiting for service to start"); case Transaction::StatusWait: return i18nc("transaction state, the transaction is waiting for another to complete", "Waiting for other tasks"); case Transaction::StatusRunning : return i18nc("transaction state, just started", "Running task"); case Transaction::StatusQuery : return i18nc("transaction state, is querying data", "Querying"); case Transaction::StatusInfo : return i18nc("transaction state, getting data from a server", "Getting information"); case Transaction::StatusRemove : return i18nc("transaction state, removing packages", "Removing packages"); case Transaction::StatusDownload: if (speed != 0 && downloadRemaining != 0) { return i18nc("transaction state, downloading package files", "Downloading at %1/s, %2 remaining", - KGlobal::locale()->formatByteSize(speed), - KGlobal::locale()->formatByteSize(downloadRemaining)); + KLocale::global()->formatByteSize(speed), + KLocale::global()->formatByteSize(downloadRemaining)); } else if (speed != 0 && downloadRemaining == 0) { return i18nc("transaction state, downloading package files", "Downloading at %1/s", - KGlobal::locale()->formatByteSize(speed)); + KLocale::global()->formatByteSize(speed)); } else if (speed == 0 && downloadRemaining != 0) { return i18nc("transaction state, downloading package files", "Downloading, %1 remaining", - KGlobal::locale()->formatByteSize(downloadRemaining)); + KLocale::global()->formatByteSize(downloadRemaining)); } else { return i18nc("transaction state, downloading package files", "Downloading"); } case Transaction::StatusInstall : return i18nc("transaction state, installing packages", "Installing packages"); case Transaction::StatusRefreshCache : return i18nc("transaction state, refreshing internal lists", "Refreshing software list"); case Transaction::StatusUpdate : return i18nc("transaction state, installing updates", "Updating packages"); case Transaction::StatusCleanup : return i18nc("transaction state, removing old packages, and cleaning config files", "Cleaning up packages"); case Transaction::StatusObsolete : return i18nc("transaction state, obsoleting old packages", "Obsoleting packages"); case Transaction::StatusDepResolve : return i18nc("transaction state, checking the transaction before we do it", "Resolving dependencies"); case Transaction::StatusSigCheck : return i18nc("transaction state, checking if we have all the security keys for the operation", "Checking signatures"); case Transaction::StatusTestCommit : return i18nc("transaction state, when we're doing a test transaction", "Testing changes"); case Transaction::StatusCommit : return i18nc("transaction state, when we're writing to the system package database", "Committing changes"); case Transaction::StatusRequest : return i18nc("transaction state, requesting data from a server", "Requesting data"); case Transaction::StatusFinished : return i18nc("transaction state, all done!", "Finished"); case Transaction::StatusCancel : return i18nc("transaction state, in the process of cancelling", "Cancelling"); case Transaction::StatusDownloadRepository : return i18nc("transaction state, downloading metadata", "Downloading repository information"); case Transaction::StatusDownloadPackagelist : return i18nc("transaction state, downloading metadata", "Downloading list of packages"); case Transaction::StatusDownloadFilelist : return i18nc("transaction state, downloading metadata", "Downloading file lists"); case Transaction::StatusDownloadChangelog : return i18nc("transaction state, downloading metadata", "Downloading lists of changes"); case Transaction::StatusDownloadGroup : return i18nc("transaction state, downloading metadata", "Downloading groups"); case Transaction::StatusDownloadUpdateinfo : return i18nc("transaction state, downloading metadata", "Downloading update information"); case Transaction::StatusRepackaging : return i18nc("transaction state, repackaging delta files", "Repackaging files"); case Transaction::StatusLoadingCache : return i18nc("transaction state, loading databases", "Loading cache"); case Transaction::StatusScanApplications : return i18nc("transaction state, scanning for running processes", "Scanning installed applications"); case Transaction::StatusGeneratePackageList : return i18nc("transaction state, generating a list of packages installed on the system", "Generating package lists"); case Transaction::StatusWaitingForLock : return i18nc("transaction state, when we're waiting for the native tools to exit", "Waiting for package manager lock"); case Transaction::StatusWaitingForAuth : return i18nc("waiting for user to type in a password", "Waiting for authentication"); case Transaction::StatusScanProcessList : return i18nc("we are updating the list of processes", "Updating the list of running applications"); case Transaction::StatusCheckExecutableFiles : return i18nc("we are checking executable files in use", "Checking for applications currently in use"); case Transaction::StatusCheckLibraries : return i18nc("we are checking for libraries in use", "Checking for libraries currently in use"); case Transaction::StatusCopyFiles : return i18nc("we are copying package files to prepare to install", "Copying files"); } kWarning() << "status unrecognised: " << status; return QString(); } QString PkStrings::status(int status, uint speed, qulonglong downloadRemaining) { return PkStrings::status(static_cast(status), speed, downloadRemaining); } QString PkStrings::statusPast(Transaction::Status status) { switch (status) { case Transaction::StatusDownload: return i18nc("The action of the package, in past tense", "Downloaded"); case Transaction::StatusUpdate: return i18nc("The action of the package, in past tense", "Updated"); case Transaction::StatusInstall: return i18nc("The action of the package, in past tense", "Installed"); case Transaction::StatusRemove: return i18nc("The action of the package, in past tense", "Removed"); case Transaction::StatusCleanup: return i18nc("The action of the package, in past tense", "Cleaned Up"); case Transaction::StatusObsolete: return i18nc("The action of the package, in past tense", "Obsoleted"); default : // In this case we don't want to map all enums kWarning() << "status unrecognised: " << status; return QString(); } } QString PkStrings::action(Transaction::Role role, Transaction::TransactionFlags flags) { switch (role) { case Transaction::RoleUnknown : return i18nc("The role of the transaction, in present tense", "Unknown role type"); case Transaction::RoleDependsOn : return i18nc("The role of the transaction, in present tense", "Getting dependencies"); case Transaction::RoleGetUpdateDetail : return i18nc("The role of the transaction, in present tense", "Getting update detail"); case Transaction::RoleGetDetails: case Transaction::RoleGetDetailsLocal: return i18nc("The role of the transaction, in present tense", "Getting details"); case Transaction::RoleRequiredBy : return i18nc("The role of the transaction, in present tense", "Getting requires"); case Transaction::RoleGetUpdates : return i18nc("The role of the transaction, in present tense", "Getting updates"); case Transaction::RoleSearchDetails : return i18nc("The role of the transaction, in present tense", "Searching details"); case Transaction::RoleSearchFile : return i18nc("The role of the transaction, in present tense", "Searching for file"); case Transaction::RoleSearchGroup : return i18nc("The role of the transaction, in present tense", "Searching groups"); case Transaction::RoleSearchName : return i18nc("The role of the transaction, in present tense", "Searching by package name"); case Transaction::RoleRemovePackages : if (flags & Transaction::TransactionFlagSimulate) { return i18nc("The role of the transaction, in present tense", "Simulating removal"); } else if (flags & Transaction::TransactionFlagOnlyDownload) { return i18nc("The role of the transaction, in present tense", "Downloading packages"); } return i18nc("The role of the transaction, in present tense", "Removing"); case Transaction::RoleInstallPackages : if (flags & Transaction::TransactionFlagSimulate) { return i18nc("The role of the transaction, in present tense", "Simulating install"); } else if (flags & Transaction::TransactionFlagOnlyDownload) { return i18nc("The role of the transaction, in present tense", "Downloading packages"); } return i18nc("The role of the transaction, in present tense", "Installing"); case Transaction::RoleInstallFiles : if (flags & Transaction::TransactionFlagSimulate) { return i18nc("The role of the transaction, in present tense", "Simulating file install"); } else if (flags & Transaction::TransactionFlagOnlyDownload) { return i18nc("The role of the transaction, in present tense", "Downloading required packages"); } return i18nc("The role of the transaction, in present tense", "Installing file"); case Transaction::RoleRefreshCache : return i18nc("The role of the transaction, in present tense", "Refreshing package cache"); case Transaction::RoleUpdatePackages : if (flags & Transaction::TransactionFlagSimulate) { return i18nc("The role of the transaction, in present tense", "Simulating update"); } else if (flags & Transaction::TransactionFlagOnlyDownload) { return i18nc("The role of the transaction, in present tense", "Downloading updates"); } return i18nc("The role of the transaction, in present tense", "Updating packages"); case Transaction::RoleCancel : return i18nc("The role of the transaction, in present tense", "Canceling"); case Transaction::RoleGetRepoList : return i18nc("The role of the transaction, in present tense", "Getting list of repositories"); case Transaction::RoleRepoEnable : return i18nc("The role of the transaction, in present tense", "Enabling repository"); case Transaction::RoleRepoSetData : return i18nc("The role of the transaction, in present tense", "Setting repository data"); case Transaction::RoleResolve : return i18nc("The role of the transaction, in present tense", "Resolving"); case Transaction::RoleGetFiles: case Transaction::RoleGetFilesLocal: return i18nc("The role of the transaction, in present tense", "Getting file list"); case Transaction::RoleWhatProvides : return i18nc("The role of the transaction, in present tense", "Getting what provides"); case Transaction::RoleInstallSignature : return i18nc("The role of the transaction, in present tense", "Installing signature"); case Transaction::RoleGetPackages : return i18nc("The role of the transaction, in present tense", "Getting package lists"); case Transaction::RoleAcceptEula : return i18nc("The role of the transaction, in present tense", "Accepting EULA"); case Transaction::RoleDownloadPackages : return i18nc("The role of the transaction, in present tense", "Downloading packages"); case Transaction::RoleGetDistroUpgrades : return i18nc("The role of the transaction, in present tense", "Getting distribution upgrade information"); case Transaction::RoleGetCategories : return i18nc("The role of the transaction, in present tense", "Getting categories"); case Transaction::RoleGetOldTransactions : return i18nc("The role of the transaction, in present tense", "Getting old transactions"); case Transaction::RoleRepairSystem : return i18nc("The role of the transaction, in present tense", "Repairing system"); case Transaction::RoleRepoRemove: return i18nc("The role of the transaction, in present tense", "Removing repository"); } kWarning() << "action unrecognised: " << role; return QString(); } QString PkStrings::action(int role, int flags) { return PkStrings::action(static_cast(role), static_cast(flags)); } QString PkStrings::actionPast(Transaction::Role action) { switch (action) { case Transaction::RoleUnknown: return i18nc("The role of the transaction, in past tense", "Unknown role type"); case Transaction::RoleDependsOn : return i18nc("The role of the transaction, in past tense", "Got dependencies"); case Transaction::RoleGetUpdateDetail : return i18nc("The role of the transaction, in past tense", "Got update detail"); case Transaction::RoleGetDetails: case Transaction::RoleGetDetailsLocal: return i18nc("The role of the transaction, in past tense", "Got details"); case Transaction::RoleRequiredBy : return i18nc("The role of the transaction, in past tense", "Got requires"); case Transaction::RoleGetUpdates : return i18nc("The role of the transaction, in past tense", "Got updates"); case Transaction::RoleSearchDetails : return i18nc("The role of the transaction, in past tense", "Searched for package details"); case Transaction::RoleSearchFile : return i18nc("The role of the transaction, in past tense", "Searched for file"); case Transaction::RoleSearchGroup : return i18nc("The role of the transaction, in past tense", "Searched groups"); case Transaction::RoleSearchName : return i18nc("The role of the transaction, in past tense", "Searched for package name"); case Transaction::RoleRemovePackages : return i18nc("The role of the transaction, in past tense", "Removed packages"); case Transaction::RoleInstallPackages : return i18nc("The role of the transaction, in past tense", "Installed packages"); case Transaction::RoleInstallFiles : return i18nc("The role of the transaction, in past tense", "Installed local files"); case Transaction::RoleRefreshCache : return i18nc("The role of the transaction, in past tense", "Refreshed package cache"); case Transaction::RoleUpdatePackages : return i18nc("The role of the transaction, in past tense", "Updated packages"); case Transaction::RoleCancel : return i18nc("The role of the transaction, in past tense", "Canceled"); case Transaction::RoleGetRepoList : return i18nc("The role of the transaction, in past tense", "Got list of repositories"); case Transaction::RoleRepoEnable : return i18nc("The role of the transaction, in past tense", "Enabled repository"); case Transaction::RoleRepoSetData : return i18nc("The role of the transaction, in past tense", "Set repository data"); case Transaction::RoleResolve : return i18nc("The role of the transaction, in past tense", "Resolved"); case Transaction::RoleGetFiles: case Transaction::RoleGetFilesLocal: return i18nc("The role of the transaction, in past tense", "Got file list"); case Transaction::RoleWhatProvides : return i18nc("The role of the transaction, in past tense", "Got what provides"); case Transaction::RoleInstallSignature : return i18nc("The role of the transaction, in past tense", "Installed signature"); case Transaction::RoleGetPackages : return i18nc("The role of the transaction, in past tense", "Got package lists"); case Transaction::RoleAcceptEula : return i18nc("The role of the transaction, in past tense", "Accepted EULA"); case Transaction::RoleDownloadPackages : return i18nc("The role of the transaction, in past tense", "Downloaded packages"); case Transaction::RoleGetDistroUpgrades : return i18nc("The role of the transaction, in past tense", "Got distribution upgrades"); case Transaction::RoleGetCategories : return i18nc("The role of the transaction, in past tense", "Got categories"); case Transaction::RoleGetOldTransactions : return i18nc("The role of the transaction, in past tense", "Got old transactions"); case Transaction::RoleRepairSystem: return i18nc("The role of the transaction, in past tense", "Repaired system"); case Transaction::RoleRepoRemove: return i18nc("The role of the transaction, in past tense", "Removed repository"); } kWarning() << "action unrecognised: " << action; return QString(); } QString PkStrings::infoPresent(Transaction::Info info) { switch (info) { case Transaction::InfoDownloading : return i18n("Downloading"); case Transaction::InfoUpdating : return i18n("Updating"); case Transaction::InfoInstalling : return i18n("Installing"); case Transaction::InfoRemoving : return i18n("Removing"); case Transaction::InfoCleanup : return i18n("Cleaning up"); case Transaction::InfoObsoleting : return i18n("Obsoleting"); case Transaction::InfoReinstalling : return i18n("Reinstalling"); case Transaction::InfoPreparing : return i18n("Preparing"); case Transaction::InfoDecompressing : return i18n("Decompressing"); default : kWarning() << "info unrecognised:" << info; return QString(); } } QString PkStrings::infoPast(Transaction::Info info) { switch (info) { case Transaction::InfoDownloading : return i18n("Downloaded"); case Transaction::InfoUpdating : return i18n("Updated"); case Transaction::InfoInstalling : return i18n("Installed"); case Transaction::InfoRemoving : return i18n("Removed"); case Transaction::InfoCleanup : return i18n("Cleaned up"); case Transaction::InfoObsoleting : return i18n("Obsoleted"); case Transaction::InfoReinstalling : return i18n("Reinstalled"); case Transaction::InfoPreparing : return i18n("Prepared"); case Transaction::InfoDecompressing : return i18n("Decompressed"); default : kWarning() << "info unrecognised: " << info; return QString(); } } QString PkStrings::error(Transaction::Error error) { switch (error) { case Transaction::ErrorNoNetwork : return i18n("No network connection available"); case Transaction::ErrorNoCache : return i18n("No package cache is available"); case Transaction::ErrorOom : return i18n("Out of memory"); case Transaction::ErrorCreateThreadFailed : return i18n("Failed to create a thread"); case Transaction::ErrorNotSupported : return i18n("Not supported by this backend"); case Transaction::ErrorInternalError : return i18n("An internal system error has occurred"); case Transaction::ErrorGpgFailure : return i18n("A security trust relationship is not present"); case Transaction::ErrorPackageNotInstalled : return i18n("The package is not installed"); case Transaction::ErrorPackageNotFound : return i18n("The package was not found"); case Transaction::ErrorPackageAlreadyInstalled : return i18n("The package is already installed"); case Transaction::ErrorPackageDownloadFailed : return i18n("The package download failed"); case Transaction::ErrorGroupNotFound : return i18n("The group was not found"); case Transaction::ErrorGroupListInvalid : return i18n("The group list was invalid"); case Transaction::ErrorDepResolutionFailed : return i18n("Dependency resolution failed"); case Transaction::ErrorFilterInvalid : return i18n("Search filter was invalid"); case Transaction::ErrorPackageIdInvalid : return i18n("The package identifier was not well formed"); case Transaction::ErrorTransactionError : return i18n("Transaction error"); case Transaction::ErrorRepoNotFound : return i18n("Repository name was not found"); case Transaction::ErrorCannotRemoveSystemPackage : return i18n("Could not remove a protected system package"); case Transaction::ErrorTransactionCancelled : return i18n("The task was canceled"); case Transaction::ErrorProcessKill : return i18n("The task was forcibly canceled"); case Transaction::ErrorFailedConfigParsing : return i18n("Reading the config file failed"); case Transaction::ErrorCannotCancel : return i18n("The task cannot be cancelled"); case Transaction::ErrorCannotInstallSourcePackage : return i18n("Source packages cannot be installed"); case Transaction::ErrorNoLicenseAgreement : return i18n("The license agreement failed"); case Transaction::ErrorFileConflicts : return i18n("Local file conflict between packages"); case Transaction::ErrorPackageConflicts : return i18n("Packages are not compatible"); case Transaction::ErrorRepoNotAvailable : return i18n("Problem connecting to a software origin"); case Transaction::ErrorFailedInitialization : return i18n("Failed to initialize"); case Transaction::ErrorFailedFinalise : return i18n("Failed to finalize"); case Transaction::ErrorCannotGetLock : return i18n("Cannot get lock"); case Transaction::ErrorNoPackagesToUpdate : return i18n("No packages to update"); case Transaction::ErrorCannotWriteRepoConfig : return i18n("Cannot write repository configuration"); case Transaction::ErrorLocalInstallFailed : return i18n("Local install failed"); case Transaction::ErrorBadGpgSignature : return i18n("Bad GPG signature"); case Transaction::ErrorMissingGpgSignature : return i18n("Missing GPG signature"); case Transaction::ErrorRepoConfigurationError : return i18n("Repository configuration invalid"); case Transaction::ErrorInvalidPackageFile : return i18n("Invalid package file"); case Transaction::ErrorPackageInstallBlocked : return i18n("Package install blocked"); case Transaction::ErrorPackageCorrupt : return i18n("Package is corrupt"); case Transaction::ErrorAllPackagesAlreadyInstalled : return i18n("All packages are already installed"); case Transaction::ErrorFileNotFound : return i18n("The specified file could not be found"); case Transaction::ErrorNoMoreMirrorsToTry : return i18n("No more mirrors are available"); case Transaction::ErrorNoDistroUpgradeData : return i18n("No distribution upgrade data is available"); case Transaction::ErrorIncompatibleArchitecture : return i18n("Package is incompatible with this system"); case Transaction::ErrorNoSpaceOnDevice : return i18n("No space is left on the disk"); case Transaction::ErrorMediaChangeRequired : return i18n("A media change is required"); case Transaction::ErrorNotAuthorized : return i18n("Authorization failed"); case Transaction::ErrorUpdateNotFound : return i18n("Update not found"); case Transaction::ErrorCannotInstallRepoUnsigned : return i18n("Cannot install from untrusted origin"); case Transaction::ErrorCannotUpdateRepoUnsigned : return i18n("Cannot update from untrusted origin"); case Transaction::ErrorCannotGetFilelist : return i18n("Cannot get the file list"); case Transaction::ErrorCannotGetRequires : return i18n("Cannot get package requires"); case Transaction::ErrorCannotDisableRepository : return i18n("Cannot disable origin"); case Transaction::ErrorRestrictedDownload : return i18n("The download failed"); case Transaction::ErrorPackageFailedToConfigure : return i18n("Package failed to configure"); case Transaction::ErrorPackageFailedToBuild : return i18n("Package failed to build"); case Transaction::ErrorPackageFailedToInstall : return i18n("Package failed to install"); case Transaction::ErrorPackageFailedToRemove : return i18n("Package failed to be removed"); case Transaction::ErrorUpdateFailedDueToRunningProcess : return i18n("Update failed due to running process"); case Transaction::ErrorPackageDatabaseChanged : return i18n("The package database was changed"); case Transaction::ErrorProvideTypeNotSupported : return i18n("Virtual provide type is not supported"); case Transaction::ErrorInstallRootInvalid : return i18n("Install root is invalid"); case Transaction::ErrorCannotFetchSources : return i18n("Cannot fetch install sources"); case Transaction::ErrorCancelledPriority : return i18n("Rescheduled due to priority"); case Transaction::ErrorUnfinishedTransaction: return i18n("Unfinished transaction"); case Transaction::ErrorLockRequired: return i18n("Lock required"); case Transaction::ErrorUnknown: return i18n("Unknown error"); } kWarning() << "error unrecognised: " << error; return QString(); } QString PkStrings::errorMessage(Transaction::Error error) { switch (error) { case Transaction::ErrorNoNetwork : return i18n("There is no network connection available.\n" "Please check your connection settings and try again"); case Transaction::ErrorNoCache : return i18n("The package list needs to be rebuilt.\n" "This should have been done by the backend automatically."); case Transaction::ErrorOom : return i18n("The service that is responsible for handling user requests is out of memory.\n" "Please close some programs or restart your computer."); case Transaction::ErrorCreateThreadFailed : return i18n("A thread could not be created to service the user request."); case Transaction::ErrorNotSupported : return i18n("The action is not supported by this backend.\n" "Please report a bug as this should not have happened."); case Transaction::ErrorInternalError : return i18n("A problem that we were not expecting has occurred.\n" "Please report this bug with the error description."); case Transaction::ErrorGpgFailure : return i18n("A security trust relationship could not be made with the software origin.\n" "Please check your software signature settings."); case Transaction::ErrorPackageNotInstalled : return i18n("The package that is trying to be removed or updated is not already installed."); case Transaction::ErrorPackageNotFound : return i18n("The package that is being modified was not found on your system or in any software origin."); case Transaction::ErrorPackageAlreadyInstalled : return i18n("The package that is trying to be installed is already installed."); case Transaction::ErrorPackageDownloadFailed : return i18n("The package download failed.\n" "Please check your network connectivity."); case Transaction::ErrorGroupNotFound : return i18n("The group type was not found.\n" "Please check your group list and try again."); case Transaction::ErrorGroupListInvalid : return i18n("The group list could not be loaded.\n" "Refreshing your cache may help, although this is normally a software " "origin error."); case Transaction::ErrorDepResolutionFailed : return i18n("A package dependency could not be found.\n" "More information is available in the detailed report."); case Transaction::ErrorFilterInvalid : return i18n("The search filter was not correctly formed."); case Transaction::ErrorPackageIdInvalid : return i18n("The package identifier was not well formed when sent to the system daemon.\n" "This normally indicates an internal bug and should be reported."); case Transaction::ErrorTransactionError : return i18n("An error occurred while running the transaction.\n" "More information is available in the detailed report."); case Transaction::ErrorRepoNotFound : return i18n("The remote software origin name was not found.\n" "You may need to enable an item in Software Origins."); case Transaction::ErrorCannotRemoveSystemPackage : return i18n("Removing a protected system package is not allowed."); case Transaction::ErrorTransactionCancelled : return i18n("The task was canceled successfully and no packages were changed."); case Transaction::ErrorProcessKill : return i18n("The task was canceled successfully and no packages were changed.\n" "The backend did not exit cleanly."); case Transaction::ErrorFailedConfigParsing : return i18n("The native package configuration file could not be opened.\n" "Please make sure your system's configuration is valid."); case Transaction::ErrorCannotCancel : return i18n("The task is not safe to be cancelled at this time."); case Transaction::ErrorCannotInstallSourcePackage : return i18n("Source packages are not normally installed this way.\n" "Check the extension of the file you are trying to install."); case Transaction::ErrorNoLicenseAgreement : return i18n("The license agreement was not agreed to.\n" "To use this software you have to accept the license."); case Transaction::ErrorFileConflicts : return i18n("Two packages provide the same file.\n" "This is usually due to mixing packages for different software origins."); case Transaction::ErrorPackageConflicts : return i18n("Multiple packages exist that are not compatible with each other.\n" "This is usually due to mixing packages from different software origins."); case Transaction::ErrorRepoNotAvailable : return i18n("There was a (possibly temporary) problem connecting to a software origins.\n" "Please check the detailed error for further details."); case Transaction::ErrorFailedInitialization : return i18n("Failed to initialize packaging backend.\n" "This may occur if other packaging tools are being used simultaneously."); case Transaction::ErrorFailedFinalise : return i18n("Failed to close down the backend instance.\n" "This error can normally be ignored."); case Transaction::ErrorCannotGetLock : return i18n("Cannot get the exclusive lock on the packaging backend.\n" "Please close any other legacy packaging tools that may be open."); case Transaction::ErrorNoPackagesToUpdate : return i18n("None of the selected packages could be updated."); case Transaction::ErrorCannotWriteRepoConfig : return i18n("The repository configuration could not be modified."); case Transaction::ErrorLocalInstallFailed : return i18n("Installing the local file failed.\n" "More information is available in the detailed report."); case Transaction::ErrorBadGpgSignature : return i18n("The package signature could not be verified."); case Transaction::ErrorMissingGpgSignature : return i18n("The package signature was missing and this package is untrusted.\n" "This package was not signed with a GPG key when created."); case Transaction::ErrorRepoConfigurationError : return i18n("Repository configuration was invalid and could not be read."); case Transaction::ErrorInvalidPackageFile : return i18n("The package you are attempting to install is not valid.\n" "The package file could be corrupt, or not a proper package."); case Transaction::ErrorPackageInstallBlocked : return i18n("Installation of this package was prevented by your packaging system's configuration."); case Transaction::ErrorPackageCorrupt : return i18n("The package that was downloaded is corrupt and needs to be downloaded again."); case Transaction::ErrorAllPackagesAlreadyInstalled : return i18n("All of the packages selected for install are already installed on the system."); case Transaction::ErrorFileNotFound : return i18n("The specified file could not be found on the system.\n" "Check that the file still exists and has not been deleted."); case Transaction::ErrorNoMoreMirrorsToTry : return i18n("Required data could not be found on any of the configured software origins.\n" "There were no more download mirrors that could be tried."); case Transaction::ErrorNoDistroUpgradeData : return i18n("Required upgrade data could not be found in any of the configured software origins.\n" "The list of distribution upgrades will be unavailable."); case Transaction::ErrorIncompatibleArchitecture : return i18n("The package that is trying to be installed is incompatible with this system."); case Transaction::ErrorNoSpaceOnDevice : return i18n("There is insufficient space on the device.\n" "Free some space on the system disk to perform this operation."); case Transaction::ErrorMediaChangeRequired : return i18n("Additional media is required to complete the transaction."); case Transaction::ErrorNotAuthorized : return i18n("You have failed to provide correct authentication.\n" "Please check any passwords or account settings."); case Transaction::ErrorUpdateNotFound : return i18n("The specified update could not be found.\n" "It could have already been installed or no longer available on the remote server."); case Transaction::ErrorCannotInstallRepoUnsigned : return i18n("The package could not be installed from untrusted origin."); case Transaction::ErrorCannotUpdateRepoUnsigned : return i18n("The package could not be updated from untrusted origin."); case Transaction::ErrorCannotGetFilelist : return i18n("The file list is not available for this package."); case Transaction::ErrorCannotGetRequires : return i18n("The information about what requires this package could not be obtained."); case Transaction::ErrorCannotDisableRepository : return i18n("The specified software origin could not be disabled."); case Transaction::ErrorRestrictedDownload : return i18n("The download could not be done automatically and should be done manually.\n" "More information is available in the detailed report."); case Transaction::ErrorPackageFailedToConfigure : return i18n("One of the selected packages failed to configure correctly.\n" "More information is available in the detailed report."); case Transaction::ErrorPackageFailedToBuild : return i18n("One of the selected packages failed to build correctly.\n" "More information is available in the detailed report."); case Transaction::ErrorPackageFailedToInstall : return i18n("One of the selected packages failed to install correctly.\n" "More information is available in the detailed report."); case Transaction::ErrorPackageFailedToRemove : return i18n("One of the selected packages failed to be removed correctly.\n" "More information is available in the detailed report."); case Transaction::ErrorUpdateFailedDueToRunningProcess : return i18n("A program is running that has to be closed before the update can proceed.\n" "More information is available in the detailed report."); case Transaction::ErrorPackageDatabaseChanged : return i18n("The package database was changed while the request was running."); case Transaction::ErrorProvideTypeNotSupported : return i18n("The virtual provide type is not supported by this system."); case Transaction::ErrorInstallRootInvalid : return i18n("The install root is invalid. Please contact your administrator."); case Transaction::ErrorCannotFetchSources : return i18n("The list of software could not be downloaded."); case Transaction::ErrorCancelledPriority : return i18n("The transaction has been cancelled and will be retried when the system is idle."); case Transaction::ErrorUnfinishedTransaction : return i18n("A previous package management transaction was interrupted."); case Transaction::ErrorLockRequired : return i18n("A package manager lock is required."); case Transaction::ErrorUnknown: return i18n("Unknown error, please report a bug.\n" "More information is available in the detailed report."); } kWarning() << "error unrecognised: " << error; return QString(); } QString PkStrings::groups(Transaction::Group group) { switch (group) { case Transaction::GroupAccessibility : return i18nc("The group type", "Accessibility"); case Transaction::GroupAccessories : return i18nc("The group type", "Accessories"); case Transaction::GroupEducation : return i18nc("The group type", "Education"); case Transaction::GroupGames : return i18nc("The group type", "Games"); case Transaction::GroupGraphics : return i18nc("The group type", "Graphics"); case Transaction::GroupInternet : return i18nc("The group type", "Internet"); case Transaction::GroupOffice : return i18nc("The group type", "Office"); case Transaction::GroupOther : return i18nc("The group type", "Others"); case Transaction::GroupProgramming : return i18nc("The group type", "Development"); case Transaction::GroupMultimedia : return i18nc("The group type", "Multimedia"); case Transaction::GroupSystem : return i18nc("The group type", "System"); case Transaction::GroupDesktopGnome : return i18nc("The group type", "GNOME desktop"); case Transaction::GroupDesktopKde : return i18nc("The group type", "KDE desktop"); case Transaction::GroupDesktopXfce : return i18nc("The group type", "XFCE desktop"); case Transaction::GroupDesktopOther : return i18nc("The group type", "Other desktops"); case Transaction::GroupPublishing : return i18nc("The group type", "Publishing"); case Transaction::GroupServers : return i18nc("The group type", "Servers"); case Transaction::GroupFonts : return i18nc("The group type", "Fonts"); case Transaction::GroupAdminTools : return i18nc("The group type", "Admin tools"); case Transaction::GroupLegacy : return i18nc("The group type", "Legacy"); case Transaction::GroupLocalization : return i18nc("The group type", "Localization"); case Transaction::GroupVirtualization : return i18nc("The group type", "Virtualization"); case Transaction::GroupSecurity : return i18nc("The group type", "Security"); case Transaction::GroupPowerManagement : return i18nc("The group type", "Power management"); case Transaction::GroupCommunication : return i18nc("The group type", "Communication"); case Transaction::GroupNetwork : return i18nc("The group type", "Network"); case Transaction::GroupMaps : return i18nc("The group type", "Maps"); case Transaction::GroupRepos : return i18nc("The group type", "Software sources"); case Transaction::GroupScience : return i18nc("The group type", "Science"); case Transaction::GroupDocumentation : return i18nc("The group type", "Documentation"); case Transaction::GroupElectronics : return i18nc("The group type", "Electronics"); case Transaction::GroupCollections ://TODO check this one return i18nc("The group type", "Package collections"); case Transaction::GroupVendor : return i18nc("The group type", "Vendor"); case Transaction::GroupNewest : return i18nc("The group type", "Newest packages"); case Transaction::GroupUnknown: return i18nc("The group type", "Unknown group"); } kWarning() << "group unrecognised: " << group; return QString(); } QString PkStrings::info(int state) { Transaction::Info stateEnum = static_cast(state); switch (stateEnum) { case Transaction::InfoLow : return i18nc("The type of update", "Trivial update"); case Transaction::InfoNormal : return i18nc("The type of update", "Normal update"); case Transaction::InfoImportant : return i18nc("The type of update", "Important update"); case Transaction::InfoSecurity : return i18nc("The type of update", "Security update"); case Transaction::InfoBugfix : return i18nc("The type of update", "Bug fix update"); case Transaction::InfoEnhancement : return i18nc("The type of update", "Enhancement update"); case Transaction::InfoBlocked : return i18nc("The type of update", "Blocked update"); case Transaction::InfoInstalled : case Transaction::InfoCollectionInstalled : return i18nc("The type of update", "Installed"); case Transaction::InfoAvailable : case Transaction::InfoCollectionAvailable : return i18nc("The type of update", "Available"); case Transaction::InfoUnknown: return i18nc("The type of update", "Unknown update"); default : // In this case we don't want to map all enums kWarning() << "info unrecognised: " << state; return QString(); } } QString PkStrings::packageQuantity(bool updates, int packages, int selected) { if (updates) { if (packages == 0) { return i18n("No Updates Available"); } else if (packages == selected) { return i18ncp("Some updates were selected on the view", "1 Update Selected", "%1 Updates Selected", packages); } else if (selected == 0) { return i18ncp("Some updates are being shown on the screen", "1 Update", "%1 Updates", packages); } else { return i18nc("Type of update, in the case it's just an update", "%1, %2", i18ncp("Part of: %1 Updates, %1 Selected", "%1 Update", "%1 Updates", packages), i18ncp("Part of: %1 Updates, %1 Selected", "%1 Selected", "%1 Selected", selected)); } } else { if (packages == 0) { return i18n("No Packages"); } return i18np("1 Package", "%1 Packages", packages); } } QString PkStrings::restartTypeFuture(Transaction::Restart value) { switch (value) { case Transaction::RestartNone: return i18n("No restart is necessary"); case Transaction::RestartApplication: return i18n("You will be required to restart this application"); case Transaction::RestartSession: return i18n("You will be required to log out and back in"); case Transaction::RestartSystem: return i18n("A restart will be required"); case Transaction::RestartSecuritySession: return i18n("You will be required to log out and back in due to a security update."); case Transaction::RestartSecuritySystem: return i18n("A restart will be required due to a security update."); case Transaction::RestartUnknown: kWarning() << "restartTypeFuture(Transaction::RestartUnknown)"; return QString(); } kWarning() << "restart unrecognised: " << value; return QString(); } QString PkStrings::restartType(Transaction::Restart value) { switch (value) { case Transaction::RestartNone: return i18n("No restart is required"); case Transaction::RestartSystem: return i18n("A restart is required"); case Transaction::RestartSession: return i18n("You need to log out and log back in"); case Transaction::RestartApplication: return i18n("You need to restart the application"); case Transaction::RestartSecuritySession: return i18n("You need to log out and log back in to remain secure."); case Transaction::RestartSecuritySystem: return i18n("A restart is required to remain secure."); case Transaction::RestartUnknown: kWarning() << "restartType(Transaction::RestartUnknown)"; return QString(); } kWarning() << "restart unrecognised: " << value; return QString(); } QString PkStrings::updateState(Transaction::UpdateState value) { switch (value) { case Transaction::UpdateStateStable: return i18n("Stable"); case Transaction::UpdateStateUnstable: return i18n("Unstable"); case Transaction::UpdateStateTesting: return i18n("Testing"); case Transaction::UpdateStateUnknown: kWarning() << "updateState(Transaction::UnknownUpdateState)"; return QString(); } kWarning() << "value unrecognised: " << value; return QString(); } QString PkStrings::mediaMessage(Transaction::MediaType value, const QString &text) { switch (value) { case Transaction::MediaTypeCd : return i18n("Please insert the CD labeled '%1', and press continue.", text); case Transaction::MediaTypeDvd : return i18n("Please insert the DVD labeled '%1', and press continue.", text); case Transaction::MediaTypeDisc : return i18n("Please insert the disc labeled '%1', and press continue.", text); case Transaction::MediaTypeUnknown: return i18n("Please insert the medium labeled '%1', and press continue.", text); } kWarning() << "value unrecognised: " << value; return i18n("Please insert the medium labeled '%1', and press continue.", text); } -QString PkStrings::message(Transaction::Message value) -{ - switch (value) { - case Transaction::MessageBrokenMirror : - return i18n("A mirror is possibly broken"); - case Transaction::MessageConnectionRefused : - return i18n("The connection was refused"); - case Transaction::MessageParameterInvalid : - return i18n("The parameter was invalid"); - case Transaction::MessagePriorityInvalid : - return i18n("The priority was invalid"); - case Transaction::MessageBackendError : - return i18n("Backend warning"); - case Transaction::MessageDaemonError : - return i18n("Daemon warning"); - case Transaction::MessageCacheBeingRebuilt : - return i18n("The package list cache is being rebuilt"); - case Transaction::MessageUntrustedPackage : - return i18n("An untrusted package was installed"); - case Transaction::MessageNewerPackageExists : - return i18n("A newer package exists"); - case Transaction::MessageCouldNotFindPackage : - return i18n("Could not find package"); - case Transaction::MessageConfigFilesChanged : - return i18n("Configuration files were changed"); - case Transaction::MessagePackageAlreadyInstalled : - return i18n("Package is already installed"); - case Transaction::MessageAutoremoveIgnored : - return i18n("Automatic cleanup is being ignored"); - case Transaction::MessageRepoMetadataDownloadFailed : - return i18n("Software source download failed"); - case Transaction::MessageRepoForDevelopersOnly : - return i18n("This software source is for developers only"); - case Transaction::MessageOtherUpdatesHeldBack : - return i18n("Other updates have been held back"); - case Transaction::MessageUnknown: - kWarning() << "message(Enum::UnknownMessageType)"; - return QString(); - } - kWarning() << "value unrecognised: " << value; - return QString(); -} +//QString PkStrings::message(Transaction::Message value) +//{ +// switch (value) { +// case Transaction::MessageBrokenMirror : +// return i18n("A mirror is possibly broken"); +// case Transaction::MessageConnectionRefused : +// return i18n("The connection was refused"); +// case Transaction::MessageParameterInvalid : +// return i18n("The parameter was invalid"); +// case Transaction::MessagePriorityInvalid : +// return i18n("The priority was invalid"); +// case Transaction::MessageBackendError : +// return i18n("Backend warning"); +// case Transaction::MessageDaemonError : +// return i18n("Daemon warning"); +// case Transaction::MessageCacheBeingRebuilt : +// return i18n("The package list cache is being rebuilt"); +// case Transaction::MessageUntrustedPackage : +// return i18n("An untrusted package was installed"); +// case Transaction::MessageNewerPackageExists : +// return i18n("A newer package exists"); +// case Transaction::MessageCouldNotFindPackage : +// return i18n("Could not find package"); +// case Transaction::MessageConfigFilesChanged : +// return i18n("Configuration files were changed"); +// case Transaction::MessagePackageAlreadyInstalled : +// return i18n("Package is already installed"); +// case Transaction::MessageAutoremoveIgnored : +// return i18n("Automatic cleanup is being ignored"); +// case Transaction::MessageRepoMetadataDownloadFailed : +// return i18n("Software source download failed"); +// case Transaction::MessageRepoForDevelopersOnly : +// return i18n("This software source is for developers only"); +// case Transaction::MessageOtherUpdatesHeldBack : +// return i18n("Other updates have been held back"); +// case Transaction::MessageUnknown: +// kWarning() << "message(Enum::UnknownMessageType)"; +// return QString(); +// } +// kWarning() << "value unrecognised: " << value; +// return QString(); +//} QString PkStrings::daemonError(int value) { Transaction::InternalError statusEnum = static_cast(value); switch (statusEnum) { case Transaction::InternalErrorFailedAuth : return i18n("You do not have the necessary privileges to perform this action."); case Transaction::InternalErrorNoTid : return i18n("Could not get a transaction id from packagekitd."); case Transaction::InternalErrorAlreadyTid : return i18n("Cannot connect to this transaction id."); case Transaction::InternalErrorRoleUnkown : return i18n("This action is unknown."); case Transaction::InternalErrorCannotStartDaemon : return i18n("The packagekitd service could not be started."); case Transaction::InternalErrorInvalidInput : return i18n("The query is not valid."); case Transaction::InternalErrorInvalidFile : return i18n("The file is not valid."); case Transaction::InternalErrorFunctionNotSupported : return i18n("This function is not yet supported."); case Transaction::InternalErrorDaemonUnreachable : return i18n("Could not talk to packagekitd."); case Transaction::InternalErrorFailed: return i18n("Error talking to packagekitd."); case Transaction::InternalErrorNone: case Transaction::InternalErrorUnkown : return i18n("An unknown error happened."); } kWarning() << "value unrecognised: " << value; return i18n("An unknown error happened."); } QString PkStrings::prettyFormatDuration(unsigned long mSec) { - return KGlobal::locale()->prettyFormatDuration(mSec); + return KLocale::global()->prettyFormatDuration(mSec); } QString PkStrings::lastCacheRefreshTitle(uint lastTime) { unsigned long fifteen = 60 * 60 * 24 * 15; unsigned long tirty = 60 * 60 * 24 * 30; if (lastTime != UINT_MAX && lastTime < fifteen) { return i18n("Your system is up to date"); } else if (lastTime != UINT_MAX && lastTime > fifteen && lastTime < tirty) { return i18n("You have no updates"); } return i18n("Last check for updates was more than a month ago"); } QString PkStrings::lastCacheRefreshSubTitle(uint lastTime) { unsigned long tirty = 60 * 60 * 24 * 30; if (lastTime != UINT_MAX && lastTime < tirty) { return i18n("Verified %1 ago", PkStrings::prettyFormatDuration(lastTime * 1000)); } return i18n("It's strongly recommended that you check for new updates now"); } diff --git a/libapper/PkStrings.h b/libapper/PkStrings.h index 1ceb269..e701816 100644 --- a/libapper/PkStrings.h +++ b/libapper/PkStrings.h @@ -1,57 +1,57 @@ /*************************************************************************** * Copyright (C) 2008-2012 by Daniel Nicoletti * * dantti12@gmail.com * * * * 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) 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 General Public License * * along with this program; see the file COPYING. If not, write to * * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef PK_STRINGS_H #define PK_STRINGS_H #include #include class Q_DECL_EXPORT PkStrings : public QObject { Q_OBJECT public Q_SLOTS: static QString infoPresent(PackageKit::Transaction::Info info); static QString infoPast(PackageKit::Transaction::Info info); static QString error(PackageKit::Transaction::Error error); static QString errorMessage(PackageKit::Transaction::Error error); - static QString message(PackageKit::Transaction::Message type); +// static QString message(PackageKit::Transaction::Message type); static QString status(PackageKit::Transaction::Status status, uint speed = 0, qulonglong downloadRemaining = 0); static QString statusPast(PackageKit::Transaction::Status status); static QString groups(PackageKit::Transaction::Group group); static QString info(int state); static QString packageQuantity(bool updates, int packages, int selected); static QString updateState(PackageKit::Transaction::UpdateState value); static QString restartType(PackageKit::Transaction::Restart value); static QString restartTypeFuture(PackageKit::Transaction::Restart value); static QString action(PackageKit::Transaction::Role role, PackageKit::Transaction::TransactionFlags flags); static QString actionPast(PackageKit::Transaction::Role action); static QString mediaMessage(PackageKit::Transaction::MediaType value, const QString &text); static QString daemonError(int value); static QString prettyFormatDuration(unsigned long mSec); static QString lastCacheRefreshTitle(uint lastTime); static QString lastCacheRefreshSubTitle(uint lastTime); // the following are needed to be able to use the functions from QML (bug#344639) static QString status(int status, uint speed = 0, qulonglong downloadRemaining = 0); static QString action(int role, int flags); }; #endif