::const_iterator itEnd = transfers.constEnd();
for (it = transfers.constBegin(); it != itEnd; ++it)
{
TransferHandler::ChangesFlags transferFlags = *it;
TransferHandler *transfer = it.key();
if (transferFlags & Transfer::Tc_Status) {
if ((transfer->status() == Job::Finished) && (transfer->startStatus() != Job::Finished)) {
KGet::showNotification(KGet::m_mainWindow, "finished",
i18n("The following file has finished downloading:
%1
", transfer->dest().fileName()),
"kget", i18n("Download completed"));
} else if (transfer->status() == Job::Running) {
KGet::showNotification(KGet::m_mainWindow, "started",
i18n("The following transfer has been started:
%1
", transfer->source().toString()),
"kget", i18n("Download started"));
} else if (transfer->status() == Job::Aborted && transfer->error().type != Job::AutomaticRetry) {
KNotification * notification = KNotification::event("error", i18n("Error"), i18n("There has been an error in the following transfer:
%1
"
"The error message is:
%2
", transfer->source().toString(), transfer->error().text),
transfer->error().pixmap, KGet::m_mainWindow, KNotification::CloseOnTimeout);
if (transfer->error().type == Job::ManualSolve) {
m_notifications.insert(notification, transfer);
notification->setActions(QStringList() << i18n("Resolve"));
connect(notification, SIGNAL(action1Activated()), SLOT(slotResolveTransferError()));
connect(notification, SIGNAL(closed()), SLOT(slotNotificationClosed()));
}
}
}
if (transferFlags & Transfer::Tc_Status) {
checkSysTray = true;
requestSave();
}
if (transferFlags & Transfer::Tc_Percent) {
transfer->group()->setGroupChange(TransferGroup::Gc_Percent, true);
transfer->checkShareRatio();
}
if (transferFlags & Transfer::Tc_DownloadSpeed) {
transfer->group()->setGroupChange(TransferGroup::Gc_DownloadSpeed, true);
}
if (transferFlags & Transfer::Tc_UploadSpeed) {
transfer->group()->setGroupChange(TransferGroup::Gc_UploadSpeed, true);
}
if ((transfer->status() == Job::Finished) || (transfer->status() == Job::FinishedKeepAlive)) {
requestSave();
} else {
allFinished = false;
}
}
allFinished = allFinished && allTransfersFinished();
if (checkSysTray)
KGet::checkSystemTray();
//only perform after finished actions if actually the status changed (that is the
//case if checkSysTray is set to true)
if (checkSysTray && Settings::afterFinishActionEnabled() && allFinished)
{
qCDebug(KGET_DEBUG) << "All finished";
KNotification *notification = nullptr;
if (!m_finishAction) {
m_finishAction = new QTimer(this);
m_finishAction->setSingleShot(true);
m_finishAction->setInterval(10000);
connect(m_finishAction, SIGNAL(timeout()), this, SLOT(slotAfterFinishAction()));
}
switch (Settings::afterFinishAction()) {
case KGet::Quit:
notification = KGet::showNotification(KGet::m_mainWindow, "notification", i18n("KGet is now closing, as all downloads have completed."), "kget", "KGet", KNotification::Persistent | KNotification::CloseWhenWidgetActivated);
break;
#ifdef HAVE_KWORKSPACE
case KGet::Shutdown:
notification = KGet::showNotification(KGet::m_mainWindow, "notification", i18n("The computer will now turn off, as all downloads have completed."), "system-shutdown", i18nc("Shutting down computer", "Shutdown"), KNotification::Persistent | KNotification::CloseWhenWidgetActivated);
break;
case KGet::Hibernate:
notification = KGet::showNotification(KGet::m_mainWindow, "notification", i18n("The computer will now suspend to disk, as all downloads have completed."), "system-suspend-hibernate", i18nc("Hibernating computer", "Hibernating"), KNotification::Persistent | KNotification::CloseWhenWidgetActivated);
break;
case KGet::Suspend:
notification = KGet::showNotification(KGet::m_mainWindow, "notification", i18n("The computer will now suspend to RAM, as all downloads have completed."), "system-suspend", i18nc("Suspending computer", "Suspending"), KNotification::Persistent | KNotification::CloseWhenWidgetActivated);
break;
#endif
default:
break;
}
if (notification) {
notification->setActions(QStringList() << i18nc("abort the proposed action", "Abort"));
connect(notification, SIGNAL(action1Activated()), this, SLOT(slotAbortAfterFinishAction()));
connect(m_finishAction, SIGNAL(timeout()), notification, SLOT(close()));
if (!m_finishAction->isActive()) {
m_finishAction->start();
}
}
} else if (allFinished) {
KGet::showNotification(KGet::m_mainWindow, "finishedall",
i18n("All transfers have been finished.
"),
"kget", i18n("Downloads completed"));
}
}
void GenericObserver::slotResolveTransferError()
{
KNotification * notification = static_cast(QObject::sender());
if (notification) {
TransferHandler * handler = m_notifications[notification];
qDebug() << "Resolve error for" << handler->source().toString() << "with id" << handler->error().id;
handler->resolveError(handler->error().id);
m_notifications.remove(notification);
}
}
void GenericObserver::slotNotificationClosed()
{
qDebug() << "Remove notification";
KNotification * notification = static_cast(QObject::sender());
if (notification)
m_notifications.remove(notification);
}
void GenericObserver::slotNetworkStatusChanged(bool online)
{
KGet::setHasNetworkConnection(online);
}
void GenericObserver::groupsChangedEvent(QMap groups)
{
bool recalculate = false;
foreach (const TransferGroup::ChangesFlags &flags, groups)
{
if (flags & TransferGroup::Gc_Percent || flags & TransferGroup::Gc_Status) {
recalculate = true;
break;
}
}
qDebug() << "Recalculate limits?" << recalculate;
if (recalculate)
KGet::calculateGlobalSpeedLimits();
}
bool GenericObserver::allTransfersFinished()
{
bool quitFlag = true;
// if all the downloads had state finished from
// the beginning
bool allWereFinished = true;
foreach(TransferGroup *transferGroup, KGet::model()->transferGroups()) {
foreach(TransferHandler *transfer, transferGroup->handler()->transfers()) {
if ((transfer->status() != Job::Finished) && (transfer->status() != Job::FinishedKeepAlive)) {
quitFlag = false;
}
if ((transfer->status() == Job::Finished || transfer->status() == Job::FinishedKeepAlive) &&
(transfer->startStatus() != Job::Finished && transfer->startStatus() != Job::FinishedKeepAlive)) {
allWereFinished = false;
}
}
}
// if the only downloads in the queue
// are those that are already finished
// before the current KGet instance
// we don't want to quit
if (allWereFinished)
{
return false;
}
// otherwise, we did some downloads right now, let quitFlag decide
return quitFlag;
}
void GenericObserver::slotAfterFinishAction()
{
qCDebug(KGET_DEBUG);
switch (Settings::afterFinishAction()) {
case KGet::Quit:
qCDebug(KGET_DEBUG) << "Quit Kget.";
QTimer::singleShot(0, KGet::m_mainWindow, SLOT(slotQuit()));
break;
#ifdef HAVE_KWORKSPACE
case KGet::Shutdown:
QTimer::singleShot(0, KGet::m_mainWindow, SLOT(slotQuit()));
KWorkSpace::requestShutDown(KWorkSpace::ShutdownConfirmNo,
KWorkSpace::ShutdownTypeHalt,
KWorkSpace::ShutdownModeForceNow);
break;
case KGet::Hibernate: {
QDBusMessage call;
call = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.PowerManagement"),
QStringLiteral("/org/freedesktop/PowerManagement"),
QStringLiteral("org.freedesktop.PowerManagement"),
QStringLiteral("Hibernate"));
QDBusConnection::sessionBus().asyncCall(call);
break;
}
case KGet::Suspend: {
QDBusMessage call;
call = QDBusMessage::createMethodCall(QStringLiteral("org.freedesktop.PowerManagement"),
QStringLiteral("/org/freedesktop/PowerManagement"),
QStringLiteral("org.freedesktop.PowerManagement"),
QStringLiteral("Suspend"));
QDBusConnection::sessionBus().asyncCall(call);
break;
}
#endif
default:
break;
}
}
void GenericObserver::slotAbortAfterFinishAction()
{
qCDebug(KGET_DEBUG);
m_finishAction->stop();
}
diff --git a/core/kget.h b/core/kget.h
index 0bc6c522..bd36a5dc 100644
--- a/core/kget.h
+++ b/core/kget.h
@@ -1,503 +1,501 @@
/* This file is part of the KDE project
Copyright (C) 2005 Dario Massarin
Copyright (C) 2009 Lukas Appelhans
Copyright (C) 2009 Matthias Fuchs
Based on:
kmainwidget.{h,cpp}
Copyright (C) 2002 by Patrick Charbonnier
that was based On Caitoo v.0.7.3 (c) 1998 - 2000, Matej Koss
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.
*/
#ifndef KGET_H
#define KGET_H
-#include
-#include
-#include
+#include
+#include
#include
-#include
-#include
+#include
#include
#include
#include
#include "kuiserverjobs.h"
#include "scheduler.h"
#include "kget_export.h"
#include "transfer.h"
#include "transfergrouphandler.h"
class QDomElement;
class TransferDataSource;
class TransferGroup;
class TransferHandler;
class TransferFactory;
class TransferTreeModel;
class TransferTreeSelectionModel;
class KGetPlugin;
class MainWindow;
class NewTransferDialog;
class TransferGroupScheduler;
class TransferHistoryStore;
/**
* This is our KGet class. This is where the user's transfers and searches are
* stored and organized.
* Use this class from the views to add or remove transfers or searches
* In order to organize the transfers inside categories we have a TransferGroup
* class. By definition, a transfer must always belong to a TransferGroup. If we
* don't want it to be displayed by the gui inside a specific group, we will put
* it in the group named "Not grouped" (better name?).
**/
class KGET_EXPORT KGet
{
friend class NewTransferDialog;
friend class NewTransferDialogHandler;
friend class GenericObserver;
friend class TransferTreeModel;
friend class UrlChecker;
public:
enum AfterFinishAction {
Quit = 0,
Shutdown = 1,
Hibernate = 2,
Suspend = 3
};
enum DeleteMode {
AutoDelete,
DeleteFiles
};
~KGet();
static KGet* self( MainWindow * mainWindow = nullptr );
/**
* Adds a new group to the KGet.
*
* @param groupName The name of the new group
*
* @returns true if the group has been successully added, otherwise
* it returns false, probably because a group with that named
* already exists
*/
static bool addGroup(const QString& groupName);
/**
* Removes a group from the KGet.
*
* @param group The name of the group to be deleted
* @param askUser Whether to ask user about the deletion
*/
static void delGroup(TransferGroupHandler * group, bool askUser = true);
/**
* Removes specific groups from the KGet.
*
* @param groups The names of the groups to be deleted.
* @param askUser Whether to ask user about the deletion
*/
static void delGroups(QList groups, bool askUser = true);
/**
* Changes the name of the group
*
* @param oldName the name of the group to be changed
* @param newName the new name of the group
*/
static void renameGroup(const QString& oldName, const QString& newName);
/**
* @returns the name of the available transfers groups
*/
static QStringList transferGroupNames();
/**
* Adds a new transfer to the KGet
*
* @param srcUrl The url to be downloaded
* @param destDir The destination directory. If empty we show a dialog
* where the user can choose it.
* @param suggestedFileName a suggestion of a simple filename to be saved in destDir
* @param groupName The name of the group the new transfer will belong to
* @param start Specifies if the newly added transfers should be started.
* If the group queue is already in a running state, this flag does nothing
*/
static TransferHandler * addTransfer(QUrl srcUrl, QString destDir = QString(), QString suggestedFileName = QString(),
QString groupName = QString(), bool start = false);
/**
* Adds new transfers to the KGet, it is assumed that this takes place because of loading
* that results in less checks for loaction etc.
*
* @param elements The dom elements of the transfers to add
* @param groupName The name of the group the new transfer will belong to
*/
static QList addTransfers(const QList &elements, const QString &groupName = QString());
/**
* Adds new transfers to the KGet
*
* @param srcUrls The urls to be downloaded
* @param destDir The destination directory. If empty we show a dialog
* where the user can choose it.
* @param groupName The name of the group the new transfer will belong to
* @param start Specifies if the newly added transfers should be started.
* If the group queue is already in a running state, this flag does nothing
*/
static const QList addTransfer(QList srcUrls, QString destDir = QString(),
QString groupName = QString(), bool start=false);
/**
* Removes a transfer from the KGet
*
* @param transfer The transfer to be removed
* @param mode The deletion mode
*/
static bool delTransfer(TransferHandler * transfer, DeleteMode mode = AutoDelete);
/**
* Removes multiple transfers from the KGet
*
* @param transfers The transfers to be removed
* @param mode The deletion mode
*/
static bool delTransfers(const QList &transfers, DeleteMode mode = AutoDelete);
/**
* Moves a transfer to a new group
*
* @param transfer The transfer to be moved
* @param groupName The name of the new transfer's group
*/
static void moveTransfer(TransferHandler * transfer, const QString& groupName);
/**
* Redownload a transfer
* @param transfer the transfer to redownload
*/
static void redownloadTransfer(TransferHandler * transfer);
/**
* @returns the list of selected transfers
*/
static QList selectedTransfers();
/**
* @returns the list of the finished transfers
*/
static QList finishedTransfers();
/**
* @returns the list of selected groups
*/
static QList
selectedTransferGroups();
/**
* @returns a pointer to the TransferTreeModel object
*/
static TransferTreeModel * model();
/**
* @returns a pointer to the QItemSelectionModel object
*/
static TransferTreeSelectionModel * selectionModel();
/**
* Imports the transfers and groups included in the provided xml file
*
* @param filename the file name to
*/
static void load( QString filename=QString() );
/**
* Exports all the transfers and groups to the given file
*
* @param filename the file name
* @param plain should list be in plain mode or kget mode
*/
static void save( QString filename=QString(), bool plain=false );
/**
* @returns a list of all transferfactories
*/
static QList factories();
/**
* @returns a list of pluginInfos associated with all transferFactories
*/
static KPluginInfo::List pluginInfos();
/**
* @returns The factory of a given transfer
*
* @param transfer the transfer about which we want to have the factory
*/
static TransferFactory * factory(TransferHandler * transfer);
/**
* @return a pointer to the KActionCollection objects
*/
static KActionCollection * actionCollection();
/**
* if running == true starts the scheduler
* if running == false stops the scheduler
*/
static void setSchedulerRunning(bool running=true);
/**
* Returns true if the scheduler has running jobs.
*/
static bool schedulerRunning();
/**
* true suspends the scheduler, any events that would result in a reschedule are ignored
* false wakes up the scheduler, events result in reschedule again
* NOTE this is a HACK for cases where the scheduler is the bottleneck, e.g. when stopping
* a lot of running transfers, or starting a lot transfers
*/
static void setSuspendScheduler(bool isSuspended);
/**
* Gets all transfers
*/
static QList allTransfers();
/**
* Gets all transfer-groups
*/
static QList allTransferGroups();
/**
* Get the transfer with the given url
* @param src the url
*/
static TransferHandler * findTransfer(const QUrl &src);
/**
* Get the group with the given name
* @param name the name
*/
static TransferGroupHandler * findGroup(const QString &name);
/**
* Run this function for enabling the systemTray
* (will be automatically done, if there is download running)
*/
static void checkSystemTray();
/**
* This will be called when the settings have been changed
*/
static void settingsChanged();
/**
* @return a list of the groups assigned to the filename of a transfer
*/
static QList groupsFromExceptions(const QUrl &filename);
/**
* Returns @c true if sourceUrl matches any of the patterns
*/
static bool matchesExceptions(const QUrl &sourceUrl, const QStringList &patterns);
/**
* Scans for all the available plugins and creates the proper
* transfer DataSource object for transfers Containers
*
* @param src Source Url
* @param type the type of the DataSource that should be created e.g. \
* this is only needed when creating a "special" TransferDataSource like the search for Urls
* you can set additional information and the TransferDataSource will use it if it can
* @param parent the parent QObject
*/
static TransferDataSource * createTransferDataSource(const QUrl &src, const QDomElement &type = QDomElement(), QObject *parent = nullptr);
/**
* Sets the global download limit
* @param limit the new global download limit
*/
static void setGlobalDownloadLimit(int limit);
/**
* Sets the global upload limit
* @param limit the new global upload limit
*/
static void setGlobalUploadLimit(int limit);
/**
* Recalculates the global speedlimits
*/
static void calculateGlobalSpeedLimits();
/**
* Recalculates the global download-limit
*/
static void calculateGlobalDownloadLimit();
/**
* Recalculates the global upload-limit
*/
static void calculateGlobalUploadLimit();
/**
* Shows a knotification
* @param parent QWidget parent of the notification
* @param eventType Notification type
* @param text Description of the information showed by the notification
* @param icon Pixmap showed in the notification, by default 'dialog-error'
* @param title Notification window title
* @param flags Notification flags
*/
static KNotification *showNotification(QWidget *parent, const QString &eventType,
const QString &text,
const QString &icon = QString("dialog-error"),
const QString &title = i18n("KGet"),
const KNotification::NotificationFlags &flags = KNotification::CloseOnTimeout);
static void loadPlugins();
/**
* Returns a download directory
* @param preferXDGDownloadDir if true the XDG_DOWNLOAD_DIR will be taken if it is not empty
* @note depending if the directories exist it will return them in the following order:
* (preferXDGDownloadDirectory >) lastDirectory > XDG_DOWNLOAD_DIR
*/
static QString generalDestDir(bool preferXDGDownloadDir = false);
private:
KGet();
class TransferData;
/**
* Scans for all the available plugins and creates the proper
* transfer object for the given src url
*
* @param src the source url
* @param dest the destination url
* @param groupName the group name
* @param start Specifies if the newly added transfers should be started.
*/
static TransferHandler * createTransfer(const QUrl &src, const QUrl &dest, const QString& groupName = QString(), bool start = false, const QDomElement * e = nullptr);
/**
* Creates multiple transfers with transferData
*/
static QList createTransfers(const QList &transferData);
static QUrl urlInputDialog();
static QString destDirInputDialog();
static QUrl destFileInputDialog(QString destDir = QString(), const QString& suggestedFileName = QString());
static bool isValidSource(const QUrl &source);
static bool isValidDestDirectory(const QString& destDir);
static QUrl getValidDestUrl(const QUrl& destDir, const QUrl &srcUrl);
//Plugin-related functions
static KGetPlugin* loadPlugin(const KPluginMetaData& md);
/**
* Stops all downloads if there is no connection and also displays
* a message.
* If there is a connection, then the downloads will be started again
*/
static void setHasNetworkConnection(bool hasConnection);
/**
* Deletes the given file, if possible.
*
* @param url The file to delete
*
* @return true if the file was successully deleted: if the given url
* is a directory or if it is not local it returns false and shows a
* warning message.
*/
static bool safeDeleteFile( const QUrl& url );
//Interview models
static TransferTreeModel * m_transferTreeModel;
static TransferTreeSelectionModel * m_selectionModel;
//Lists of available plugins
static KPluginInfo::List m_pluginInfoList;
static QList m_transferFactories;
//pointer to the Main window
static MainWindow * m_mainWindow;
//Scheduler object
static TransferGroupScheduler * m_scheduler;
//pointer to the kget uiserver jobs manager
static KUiServerJobs *m_jobManager;
//pointer to the used TransferHistoryStore
static TransferHistoryStore *m_store;
static bool m_hasConnection;
};
class KGET_EXPORT KGet::TransferData
{
public:
TransferData(const QUrl &src, const QUrl &dest, const QString &groupName = QString(), bool start = false, const QDomElement *e = nullptr);
QUrl src;
QUrl dest;
QString groupName;
bool start;
const QDomElement *e;
};
class GenericObserver : public QObject
{
Q_OBJECT
public:
GenericObserver(QObject *parent = nullptr);
virtual ~GenericObserver ();
public slots:
void groupAddedEvent(TransferGroupHandler *handler);
void groupRemovedEvent(TransferGroupHandler *handler);
void transfersAddedEvent(const QList &handlers);
void transfersRemovedEvent(const QList &handlers);
void transfersChangedEvent(QMap transfers);
void groupsChangedEvent(QMap groups);
void transferMovedEvent(TransferHandler *, TransferGroupHandler *);
private slots:
void slotSave();
void slotAfterFinishAction();
void slotAbortAfterFinishAction();
void slotResolveTransferError();
void slotNotificationClosed();
void slotNetworkStatusChanged(bool online);
private:
bool allTransfersFinished();
void requestSave();
private:
QTimer *m_save;
QTimer *m_finishAction;
QHash m_notifications;
QNetworkConfigurationManager m_networkConfig;
};
#endif
diff --git a/core/kgetglobaljob.cpp b/core/kgetglobaljob.cpp
index 3f780b97..08acf355 100644
--- a/core/kgetglobaljob.cpp
+++ b/core/kgetglobaljob.cpp
@@ -1,72 +1,72 @@
/* This file is part of the KDE project
Copyright (C) 2007 by Javier Goday
Copyright (C) 2009 by Dario Massarin
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.
*/
#include "kgetglobaljob.h"
#include "transferhandler.h"
#include "kget.h"
#include "kget_debug.h"
-#include
+#include
#include
#include
KGetGlobalJob::KGetGlobalJob(QObject *parent)
: KJob(parent)
{
setCapabilities(Killable);
}
KGetGlobalJob::~KGetGlobalJob()
{
}
void KGetGlobalJob::update()
{
int runningTransfers = 0;
qulonglong processedAmount = 0;
qulonglong totalAmount = 0;
unsigned long speed = 0;
unsigned long percent = 0;
foreach(TransferHandler * transfer, KGet::allTransfers()) {
if(transfer->status() == Job::Running) {
runningTransfers++;
processedAmount += transfer->downloadedSize();
speed += transfer->downloadSpeed();
totalAmount += transfer->totalSize();
}
}
// qCDebug(KGET_DEBUG) << totalAmount;
if (totalAmount > 0)
percent = 100 * processedAmount / totalAmount;
else
percent = 0;
emit description(this, "KGet global information",
qMakePair(QString("source"), i18np("KGet is downloading %1 file", "KGet is downloading %1 files", runningTransfers)));
emitSpeed(speed);
setTotalAmount(KJob::Bytes, totalAmount);
setProcessedAmount(KJob::Bytes, processedAmount);
setPercent(percent);
}
bool KGetGlobalJob::doKill()
{
qCDebug(KGET_DEBUG) << "Kill of global job called:" << this;
emit requestStop(this, nullptr);
return KJob::doKill();
}
diff --git a/core/kgetglobaljob.h b/core/kgetglobaljob.h
index ed1204e5..7e8d65df 100644
--- a/core/kgetglobaljob.h
+++ b/core/kgetglobaljob.h
@@ -1,43 +1,43 @@
/* This file is part of the KDE project
Copyright (C) 2007 by Javier Goday
Copyright (C) 2009 by Dario Massarin
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.
*/
#ifndef KGETGLOBALJOB_H
#define KGETGLOBALJOB_H
-#include
+#include
class TransferHandler;
class KGetGlobalJob : public KJob
{
Q_OBJECT
public:
KGetGlobalJob(QObject *parent = nullptr);
~KGetGlobalJob();
void update();
void start() override {};
signals:
/**
* Emitted when doKill is called, e.g. when the gui is closed.
* Not handling this signal might lead to a crash if something tries to
* access the then non-existing gui.
* @param job is this
* @param handler is always nullptr suggesting that all TransferHandlers should be stopped
*/
void requestStop(KJob *job, TransferHandler *handler);
protected:
virtual bool doKill() override;
};
#endif
diff --git a/core/kgetkjobadapter.cpp b/core/kgetkjobadapter.cpp
index 381a0376..558f979a 100644
--- a/core/kgetkjobadapter.cpp
+++ b/core/kgetkjobadapter.cpp
@@ -1,78 +1,78 @@
/* This file is part of the KDE project
Copyright (C) 2008 Javier Goday
Idea by Copyright (C) 2008 Lukas Appelhans
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.
*/
#include "kgetkjobadapter.h"
#include "kget_debug.h"
-#include
+#include
#include
KGetKJobAdapter::KGetKJobAdapter(QObject *parent, TransferHandler *transfer)
: KJob(parent),
m_transferHandler(transfer)
{
setCapabilities(Killable | Suspendable);
}
KGetKJobAdapter::~KGetKJobAdapter()
{
}
qulonglong KGetKJobAdapter::processedAmount(Unit unit) const
{
Q_UNUSED(unit)
return m_transferHandler->downloadedSize();
}
qulonglong KGetKJobAdapter::totalAmount(Unit unit) const
{
Q_UNUSED(unit)
return m_transferHandler->totalSize();
}
unsigned long KGetKJobAdapter::percent() const
{
return m_transferHandler->percent();
}
void KGetKJobAdapter::slotUpdateDescription()
{
emit description(this, i18n("KGet Transfer"),
qMakePair(QString("source"), m_transferHandler->source().toString()),
qMakePair(QString("destination"), m_transferHandler->dest().toString()));
emitSpeed(m_transferHandler->downloadSpeed());
setProcessedAmount(KJob::Bytes, processedAmount(KJob::Bytes));
setTotalAmount(KJob::Bytes, totalAmount(KJob::Bytes));
setPercent(percent());
}
bool KGetKJobAdapter::doKill()
{
qCDebug(KGET_DEBUG) << "Kill of job adapter called:" << this << m_transferHandler->dest();
emit requestStop(this, m_transferHandler);
return KJob::doKill();
}
bool KGetKJobAdapter::doSuspend()
{
if (m_transferHandler->capabilities() & Transfer::Cap_Resuming) {
emit requestSuspend(this, m_transferHandler);
return true;
}
return false;
}
bool KGetKJobAdapter::doResume()
{
emit requestResume(this, m_transferHandler);
return true;
}
diff --git a/core/kgetkjobadapter.h b/core/kgetkjobadapter.h
index 717a868c..ac878f79 100644
--- a/core/kgetkjobadapter.h
+++ b/core/kgetkjobadapter.h
@@ -1,57 +1,57 @@
/* This file is part of the KDE project
Copyright (C) 2008 Javier Goday
Idea by Copyright (C) 2008 Lukas Appelhans
Copyright (C) 2010 Matthias Fuchs
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.
*/
#ifndef KGETKJOBADAPTER_H
#define KGETKJOBADAPTER_H
#include "transferhandler.h"
-#include
+#include
/**
* Allows kget to register all transfers in kuiserver as kjobs
*/
class KGetKJobAdapter : public KJob
{
Q_OBJECT
public:
KGetKJobAdapter(QObject *parent, TransferHandler *transfer);
~KGetKJobAdapter();
void start() override {};
qulonglong processedAmount(Unit unit) const;
qulonglong totalAmount(Unit unit) const;
unsigned long percent() const;
public slots:
void slotUpdateDescription();
signals:
/**
* Emitted when doKill is called, e.g. when the gui is closed.
* Not handling this signal might lead to a crash if something tries to
* access the then non-existing gui.
*/
void requestStop(KJob *job, TransferHandler *handler);
void requestSuspend(KJob *job, TransferHandler *handler);
void requestResume(KJob *job, TransferHandler *handler);
protected:
virtual bool doKill() override;
virtual bool doSuspend() override;
virtual bool doResume() override;
private:
TransferHandler *m_transferHandler;
};
#endif
diff --git a/core/kuiserverjobs.cpp b/core/kuiserverjobs.cpp
index faf579b4..d61f4321 100644
--- a/core/kuiserverjobs.cpp
+++ b/core/kuiserverjobs.cpp
@@ -1,226 +1,226 @@
/* This file is part of the KDE project
Copyright (C) 2007 by Javier Goday
Copyright (C) 2009 by Dario Massarin
Copyright (C) 2010 by Matthias Fuchs
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.
*/
#include "kuiserverjobs.h"
#include "kgetglobaljob.h"
#include "kgetkjobadapter.h"
#include "transferhandler.h"
#include "settings.h"
#include "kget.h"
#include "kget_debug.h"
-#include
-#include
+#include
+#include
KUiServerJobs::KUiServerJobs(QObject *parent)
: QObject(parent), m_globalJob(nullptr)
{
}
KUiServerJobs::~KUiServerJobs()
{
while(m_registeredJobs.size()) {
unregisterJob(m_registeredJobs.begin().value(), m_registeredJobs.begin().key());
}
delete m_globalJob;
}
void KUiServerJobs::settingsChanged()
{
QList transfers = KGet::allTransfers();
foreach(TransferHandler * transfer, transfers) {
if(shouldBeShown(transfer))
registerJob(transfer->kJobAdapter(), transfer);
else
unregisterJob(transfer->kJobAdapter(), transfer);
}
// GlobalJob is associated to a virtual transfer pointer of value == nullptr
if(shouldBeShown(nullptr))
registerJob(globalJob(), nullptr);
else
unregisterJob(globalJob(), nullptr);
}
void KUiServerJobs::slotTransfersAdded(QList transfers)
{
qCDebug(KGET_DEBUG);
foreach (TransferHandler *transfer, transfers) {
if(shouldBeShown(transfer))
registerJob(transfer->kJobAdapter(), transfer);
if(shouldBeShown(nullptr)) {
globalJob()->update();
registerJob(globalJob(), nullptr);
}
else
unregisterJob(globalJob(), nullptr);
}
}
void KUiServerJobs::slotTransfersAboutToBeRemoved(const QList &transfers)
{
qCDebug(KGET_DEBUG);
m_invalidTransfers << transfers;
foreach (TransferHandler *transfer, transfers) {
unregisterJob(transfer->kJobAdapter(), transfer);
if (shouldBeShown(nullptr)) {
globalJob()->update();
registerJob(globalJob(), nullptr);
} else {
unregisterJob(globalJob(), nullptr);
}
}
}
void KUiServerJobs::slotTransfersChanged(QMap transfers)
{
qCDebug(KGET_DEBUG);
if(!Settings::enableKUIServerIntegration())
return;
QMapIterator i(transfers);
while (i.hasNext()) {
i.next();
// if(!m_invalidTransfers.contains(i.key()))
{
TransferHandler * transfer = i.key();
if (shouldBeShown(transfer)) {
registerJob(transfer->kJobAdapter(), transfer);
} else {
unregisterJob(transfer->kJobAdapter(), transfer);
}
}
}
if(shouldBeShown(nullptr)) {
globalJob()->update();
registerJob(globalJob(), nullptr);
}
else
unregisterJob(globalJob(), nullptr);
}
void KUiServerJobs::registerJob(KGetKJobAdapter *job, TransferHandler *transfer)
{
if (m_registeredJobs.contains(transfer) || !job) {
return;
}
connect(job, SIGNAL(requestStop(KJob*,TransferHandler*)), this, SLOT(slotRequestStop(KJob*,TransferHandler*)));
connect(job, SIGNAL(requestSuspend(KJob*,TransferHandler*)), this, SLOT(slotRequestSuspend(KJob*,TransferHandler*)));
connect(job, SIGNAL(requestResume(KJob*,TransferHandler*)), this, SLOT(slotRequestResume(KJob*,TransferHandler*)));
KJob *j = job;
registerJob(j, transfer);
}
void KUiServerJobs::registerJob(KJob * job, TransferHandler * transfer)
{
if(m_registeredJobs.contains(transfer) || !job)
return;
KIO::getJobTracker()->registerJob(job);
m_registeredJobs[transfer] = job;
}
bool KUiServerJobs::unregisterJob(KJob * job, TransferHandler * transfer)
{
if (!m_registeredJobs.contains(transfer) || !job)
return false;
//Transfer should only be suspended, thus still show the job tracker
if (m_suspendRequested.contains(transfer)) {
m_suspendRequested.removeAll(transfer);
return false;
}
//unregister the job if it was a single adaptor
if (job != m_globalJob) {
disconnect(job);
}
KIO::getJobTracker()->unregisterJob(m_registeredJobs[transfer]);
m_registeredJobs.remove(transfer);
return true;
}
void KUiServerJobs::slotRequestStop(KJob *job, TransferHandler *transfer)
{
if (unregisterJob(job, transfer)) {
if (transfer) {
transfer->stop();
} else {
foreach (TransferHandler *t, KGet::allTransfers()) {
t->stop();
}
}
}
}
bool KUiServerJobs::shouldBeShown(TransferHandler * transfer)
{
if(!Settings::enableKUIServerIntegration())
return false;
if(Settings::exportGlobalJob() && (transfer == nullptr) && existRunningTransfers())
return true;
if(!Settings::exportGlobalJob() && (transfer) && (transfer->status() == Job::Running))
return true;
return false;
}
bool KUiServerJobs::existRunningTransfers()
{
foreach(TransferHandler * transfer, KGet::allTransfers()) {
//if added to m_invalidTransfers it means that the job is about to be removed
if ((transfer->status() == Job::Running) && !m_invalidTransfers.contains(transfer)) {
return true;
}
}
return false;
}
KGetGlobalJob * KUiServerJobs::globalJob()
{
if (!m_globalJob) {
m_globalJob = new KGetGlobalJob();
connect(m_globalJob, SIGNAL(requestStop(KJob*,TransferHandler*)), this, SLOT(slotRequestStop(KJob*,TransferHandler*)));
}
return m_globalJob;
}
void KUiServerJobs::slotRequestSuspend(KJob *job, TransferHandler *transfer)
{
Q_UNUSED(job)
if (transfer) {
m_suspendRequested << transfer;
transfer->stop();
}
}
void KUiServerJobs::slotRequestResume(KJob *job, TransferHandler *transfer)
{
Q_UNUSED(job)
if (transfer) {
transfer->start();
}
}
diff --git a/core/linkimporter.cpp b/core/linkimporter.cpp
index e439e2f3..961b144c 100644
--- a/core/linkimporter.cpp
+++ b/core/linkimporter.cpp
@@ -1,141 +1,141 @@
/* This file is part of the KDE project
Copyright (C) 2008 Javier Goday
First Url regular expression taken from urlview tool by Michael Elkins .
Regular expression improved by FiNex.
Improvements to regular expression and slotReadFile by Frantisek Ziacik
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.
*/
#include "linkimporter.h"
+#include
#include
#include
#include
#include
#include
#include
-#include
#include
-#include
+#include
//static QString REGULAR_EXPRESSION = "(((https?|ftp|gopher)://|(mailto|file|news):)[^’ <>\"]+|(www|web|w3).[-a-z0-9.]+)[^’ .,;<>\":]";
// static QString REGULAR_EXPRESSION = "((http|https|ftp|ftps)+([\\:\\w\\d:#@%/;$()~_?\\+-=\\\\.&])*)";
static QString REGULAR_EXPRESSION = "(\\w+[:]//)?(((([\\w-]+[.]){1,}(ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|int|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|sv|st|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw|aero|biz|coop|info|museum|name|pro|travel))|([0-9]+[.][0-9]+[.][0-9]+[.][0-9]+)))([:][0-9]*)?([?/][\\w~#\\-;%?@&=/.+]*)?(?!\\w)";
LinkImporter::LinkImporter(const QUrl &url, QObject *parent) : QThread(parent),
m_url(url),
m_transfers(),
m_tempFile()
{
}
LinkImporter::LinkImporter(QObject *parent) : QThread(parent),
m_url(),
m_transfers(),
m_tempFile()
{
}
LinkImporter::~LinkImporter()
{
}
void LinkImporter::checkClipboard(const QString &clipboardContent)
{
QRegExp rx(REGULAR_EXPRESSION);
int regexPos = 0;
while ((regexPos = rx.indexIn(clipboardContent, regexPos)) > -1) {
QString link = rx.capturedTexts()[0];
addTransfer(link);
regexPos += rx.matchedLength();
}
}
void LinkImporter::run()
{
if(!m_url.isLocalFile() && !m_tempFile.isEmpty()) {
slotReadFile(QUrl(m_tempFile));
}
else {
slotReadFile(m_url);
}
quit();
}
void LinkImporter::copyRemoteFile()
{
m_tempFile = QString("%1/%2.tmp").arg(QDir::tempPath()).arg("importer_aux");
QUrl aux(m_tempFile);
KIO::CopyJob *job = KIO::copy(m_url, aux, KIO::HideProgressInfo);
if(!job->exec()) {
emit error(ki18n("Error trying to get %1").subs(m_url.url()));
}
}
void LinkImporter::slotReadFile(const QUrl &url)
{
QRegExp rx(REGULAR_EXPRESSION);
QFile file(url.toLocalFile());
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return;
QTextStream in(&file);
quint64 size = file.size();
quint64 position = 0;
while (!in.atEnd()) {
QString line = in.readLine();
int regexPos = 0;
quint64 lastPosition = position;
while ((regexPos = rx.indexIn(line, regexPos)) > -1) {
QString link = rx.capturedTexts()[0];
addTransfer(link);
regexPos += rx.matchedLength();
position = lastPosition + regexPos;
emit progress(position * 100 / size);
}
position += line.size();
emit progress(position * 100 / size);
}
if(!m_url.isLocalFile()) {
file.remove();
}
}
void LinkImporter::addTransfer(QString &link)
{
QUrl auxUrl;
if (link.contains("://")) {
auxUrl = QUrl(link);
} else {
auxUrl = QUrl(QString("http://") + link);
}
if(!link.isEmpty() && auxUrl.isValid() && m_transfers.indexOf(link) < 0 &&
!auxUrl.scheme().isEmpty() && !auxUrl.host().isEmpty()) {
m_transfers << link;
}
}
diff --git a/core/plugin/transferfactory.cpp b/core/plugin/transferfactory.cpp
index 385e6239..8a8d9834 100644
--- a/core/plugin/transferfactory.cpp
+++ b/core/plugin/transferfactory.cpp
@@ -1,86 +1,86 @@
/* This file is part of the KDE project
Copyright (C) 2004 Dario Massarin
Copyright (C) 2009 Lukas Appelhans
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.
*/
#include "transferfactory.h"
#include "kget.h"
-#include
+#include
#include
TransferFactory::TransferFactory(QObject *parent, const QVariantList &args)
: KGetPlugin(parent, args)
{
}
Transfer * TransferFactory::createTransfer(const QUrl &srcUrl, const QUrl &destUrl,
TransferGroup * parent,
Scheduler * scheduler,
const QDomElement * n)
{
Q_UNUSED(srcUrl)
Q_UNUSED(destUrl)
Q_UNUSED(parent)
Q_UNUSED(scheduler)
Q_UNUSED(n)
return 0;
}
TransferHandler * TransferFactory::createTransferHandler(Transfer * transfer, Scheduler * scheduler)
{
return new TransferHandler(transfer, scheduler);
}
QWidget * TransferFactory::createDetailsWidget(TransferHandler * transfer)
{
Q_UNUSED(transfer)
return 0;
}
QDialog * TransferFactory::createNewTransferDialog(const QUrl &srcUrl, const QString &suggestedFileName, TransferGroupHandler * defaultGroup)
{
Q_UNUSED(srcUrl)
Q_UNUSED(suggestedFileName)
Q_UNUSED(defaultGroup)
return 0;
}
const QList TransferFactory::actions(TransferHandler *handler)
{
Q_UNUSED(handler)
return QList();
}
TransferDataSource * TransferFactory::createTransferDataSource(const QUrl &srcUrl, const QDomElement &type, QObject *parent)
{
Q_UNUSED(srcUrl)
Q_UNUSED(type)
Q_UNUSED(parent)
return 0;
}
bool TransferFactory::isSupported(const QUrl &url) const
{
Q_UNUSED(url)
return false;
}
QStringList TransferFactory::addsProtocols() const
{
return QStringList();
}
QString TransferFactory::displayName() const
{
return "Undefined";
}
diff --git a/core/scheduler.cpp b/core/scheduler.cpp
index 9f803aa4..9bff3142 100644
--- a/core/scheduler.cpp
+++ b/core/scheduler.cpp
@@ -1,441 +1,441 @@
/* This file is part of the KDE project
Copyright (C) 2004 Dario Massarin
Copyright (C) 2010 Matthias Fuchs
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.
*/
#include "core/scheduler.h"
#include "core/transferhandler.h"
#include "settings.h"
#include
#include