From 0f1473e212be15d2797bf45c553c975afca7e618 Mon Sep 17 00:00:00 2001 From: Christophe Dumez Date: Sun, 6 Feb 2011 14:27:34 +0000 Subject: [PATCH] FEATURE: Inhibit system sleep when torrents are active (Vladimir Golovnev) Remove visual style settings --- Changelog | 1 + src/lang/qbittorrent_ru.ts | 127 ++++++-------- src/main.cpp | 10 -- src/mainwindow.cpp | 31 +++- src/mainwindow.h | 6 + src/powermanagement/powermanagement.cpp | 90 ++++++++++ src/powermanagement/powermanagement.h | 70 ++++++++ src/powermanagement/powermanagement.pri | 9 + src/powermanagement/powermanagement_x11.cpp | 185 ++++++++++++++++++++ src/powermanagement/powermanagement_x11.h | 69 ++++++++ src/preferences/advancedsettings.h | 2 +- src/preferences/options.ui | 105 +++++------ src/preferences/options_imp.cpp | 28 +-- src/preferences/options_imp.h | 4 +- src/preferences/preferences.h | 17 +- src/src.pro | 1 + 16 files changed, 573 insertions(+), 182 deletions(-) create mode 100644 src/powermanagement/powermanagement.cpp create mode 100644 src/powermanagement/powermanagement.h create mode 100644 src/powermanagement/powermanagement.pri create mode 100644 src/powermanagement/powermanagement_x11.cpp create mode 100644 src/powermanagement/powermanagement_x11.h diff --git a/Changelog b/Changelog index 4cbc20159..b9b522c92 100644 --- a/Changelog +++ b/Changelog @@ -2,6 +2,7 @@ - FEATURE: Added auto-shutdown confirmation dialog - FEATURE: Added option to skip torrent deletion confirmation (Ville Kiiskinen) - FEATURE: IP address reported to trackers is now customizable + - FEATURE: Inhibit system sleep when torrents are active (Vladimir Golovnev) * Sun Jan 9 2011 - Christophe Dumez - v2.6.0 - FEATURE: Use system icons (Linux, Qt >= 4.6) diff --git a/src/lang/qbittorrent_ru.ts b/src/lang/qbittorrent_ru.ts index 07ca325cc..8c488a7ef 100644 --- a/src/lang/qbittorrent_ru.ts +++ b/src/lang/qbittorrent_ru.ts @@ -168,13 +168,9 @@ p, li { white-space: pre-wrap; } Use system icon theme Использовать системные иконки - - Confirm torrent deletion - Подтверждать удаление торрента - IP Address to report to trackers (requires restart) - + IP адрес для сообщения трекерам (требуется перезапуск) @@ -593,95 +589,95 @@ You should get this information from your Web browser preferences. DownloadThread I/O Error - Ошибка ввода/вывода + Ошибка ввода/вывода The remote host name was not found (invalid hostname) - Удаленный хост не был найден (неправильное имя хоста) + Удаленный хост не был найден (неправильное имя хоста) The operation was canceled - Операция была отменена + Операция была отменена The remote server closed the connection prematurely, before the entire reply was received and processed - Удаленный сервер закрыл соединение, прежде чем весь ответ был принят и обработан + Удаленный сервер закрыл соединение, прежде чем весь ответ был принят и обработан The connection to the remote server timed out - Время соединения с удаленным сервером вышло + Время соединения с удаленным сервером вышло SSL/TLS handshake failed - Соединение SSL/TLS не удалось + Соединение SSL/TLS не удалось The remote server refused the connection - Удаленный сервер отклонил соединение + Удаленный сервер отклонил соединение The connection to the proxy server was refused - Прокси-сервер отклонил соединение + Прокси-сервер отклонил соединение The proxy server closed the connection prematurely - Прокси-сервер преждевременно закрыл соединение + Прокси-сервер преждевременно закрыл соединение The proxy host name was not found - Имя прокси-сервера не было найдено + Имя прокси-сервера не было найдено The connection to the proxy timed out or the proxy did not reply in time to the request sent - Подключение к прокси-серверу истекло или прокси-сервер не ответил на запрос + Подключение к прокси-серверу истекло или прокси-сервер не ответил на запрос The proxy requires authentication in order to honour the request but did not accept any credentials offered - Прокси-сервер требует аутентификации, но не принял указанные учетные данные + Прокси-сервер требует аутентификации, но не принял указанные учетные данные The access to the remote content was denied (401) - В доступе к данным было отказано (401) + В доступе к данным было отказано (401) The operation requested on the remote content is not permitted - В данной операции над данными отказано + В данной операции над данными отказано The remote content was not found at the server (404) - Данные не были найдены на сервере (404) + Данные не были найдены на сервере (404) The remote server requires authentication to serve the content but the credentials provided were not accepted - Удаленный сервер требует аутентификацию для отдачи данных, но указанные учетные данные не были приняты + Удаленный сервер требует аутентификацию для отдачи данных, но указанные учетные данные не были приняты The Network Access API cannot honor the request because the protocol is not known - API сетевого доступа не может выполнить запрос, потому что протокол не известен + API сетевого доступа не может выполнить запрос, потому что протокол не известен The requested operation is invalid for this protocol - Запрошенная операция не поддерживается данным протоколом + Запрошенная операция не поддерживается данным протоколом An unknown network-related error was detected - Неизвестная сетевая ошибка + Неизвестная сетевая ошибка An unknown proxy-related error was detected - Неизвестная ошибка прокси-сервера + Неизвестная ошибка прокси-сервера An unknown error related to the remote content was detected - Неизвестная ошибка данных + Неизвестная ошибка данных A breakdown in protocol was detected - Ошибка в протоколе + Ошибка в протоколе Unknown error - Неизвестная ошибка + Неизвестная ошибка @@ -2615,6 +2611,10 @@ Would you like to update qBittorrent to version %1? Reload the filter Перезагрузить фильтр + + Prevent system from suspend + Предотвращать переход в спящий режим + PreviewSelect @@ -3190,19 +3190,7 @@ Would you like to update qBittorrent to version %1? Reporting IP address %1 to trackers... - - - - The computer will now go to sleep mode unless you cancel within the next 15 seconds... - - - - The computer will now be switched off unless you cancel within the next 15 seconds... - - - - qBittorrent will now exit unless you cancel within the next 15 seconds... - + Сообщаю IP адрес %1 трекерам... @@ -3643,13 +3631,6 @@ Do you want to install it now? Поисковый движок - - ShutdownConfirmDlg - - Shutdown confirmation - - - SpeedLimitDialog @@ -4808,95 +4789,95 @@ Do you want to install it now? downloadThread I/O Error - Ошибка ввода/вывода + Ошибка ввода/вывода The remote host name was not found (invalid hostname) - Удаленный хост не был найден (неправильное имя хоста) + Имя удалённого хоста не было найдено (неправильное имя хоста) The operation was canceled - Операция была отменена + Операция была отменена The remote server closed the connection prematurely, before the entire reply was received and processed - Удаленный сервер закрыл соединение навсегда, прежде чем весь ответ был принят и обработан + Удаленный сервер преждевременно закрыл соединение, прежде чем весь ответ был принят и обработан The connection to the remote server timed out - Время соединения с удаленным сервером вышло + Время соединения с удаленным сервером вышло SSL/TLS handshake failed - Соединение SSL/TLS не удалось + Соединение SSL/TLS не удалось The remote server refused the connection - Удаленный сервер отклонил соединение + Удаленный сервер отклонил соединение The connection to the proxy server was refused - Прокси-сервер отклонил соединение + Соединение с прокси-сервером отклонено The proxy server closed the connection prematurely - Прокси-сервер закрыл соединение навсегда + Прокси-сервер преждевременно закрыл соединение The proxy host name was not found - Имя прокси-сервера не найдено + Имя прокси-сервера не было найдено The connection to the proxy timed out or the proxy did not reply in time to the request sent - Подключение к прокси-серверу истекло или прокси-сервер не ответил на запрос + Подключение к прокси-серверу истекло или прокси-сервер не ответил на запрос The proxy requires authentication in order to honour the request but did not accept any credentials offered - Прокси-сервер требует аутентификации но не принял указанные учетные данные + Прокси-сервер требует аутентификации, но не принял указанные учетные данные The access to the remote content was denied (401) - В доступе к данным было отказано (401) + В доступе к данным было отказано (401) The operation requested on the remote content is not permitted - В данной операции над данными отказано + Запрошенная операция над данными запрещена The remote content was not found at the server (404) - Данные не были найдены на сервере (404) + Данные не были найдены на сервере (404) The remote server requires authentication to serve the content but the credentials provided were not accepted - Удаленный сервер требует аутентификацию для отдачи данных, но указанные учетные данные не были приняты + Удаленный сервер требует аутентификацию для отдачи данных, но указанные учетные данные не были приняты The Network Access API cannot honor the request because the protocol is not known - API сетевого доступа не может выполнить запрос потому что протокол не известен + API сетевого доступа не может выполнить запрос, потому что протокол не известен The requested operation is invalid for this protocol - Запрошенная операция не поддерживается данным протоколом + Запрошенная операция не поддерживается данным протоколом An unknown network-related error was detected - Неизвестная сетевая ошибка + Неизвестная сетевая ошибка An unknown proxy-related error was detected - Неизвестная ошибка прокси-сервера + Неизвестная ошибка прокси-сервера An unknown error related to the remote content was detected - Неизвестная ошибка данных + Неизвестная ошибка данных A breakdown in protocol was detected - Ошибка в протоколе + Ошибка в протоколе Unknown error - Неизвестная ошибка + Неизвестная ошибка @@ -5160,7 +5141,7 @@ However, those plugins were disabled. Succesfully refreshed - Успешно обновлен + Успешно обновлен Successfuly parsed the provided IP filter: %1 rules were applied. @@ -5169,7 +5150,7 @@ However, those plugins were disabled. Successfully refreshed - Успешно обновлён + Успешно обновлён diff --git a/src/main.cpp b/src/main.cpp index 3048279fe..269ca02dc 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -153,15 +153,6 @@ void sigabrtHandler(int) { } #endif -#ifndef DISABLE_GUI -void useStyle(QString style){ - if(!style.isEmpty()) { - QApplication::setStyle(QStyleFactory::create(style)); - } - Preferences().setStyle(QApplication::style()->objectName()); -} -#endif - // Main int main(int argc, char *argv[]){ // Create Application @@ -286,7 +277,6 @@ int main(int argc, char *argv[]){ } #ifndef DISABLE_GUI - useStyle(pref.getStyle()); app.setStyleSheet("QStatusBar::item { border-width: 0; }"); #endif diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp index af1a8047b..d39d7e7b6 100644 --- a/src/mainwindow.cpp +++ b/src/mainwindow.cpp @@ -43,6 +43,9 @@ #include #include #include +#ifdef Q_WS_X11 +#include +#endif #include "mainwindow.h" #include "transferlistwidget.h" @@ -80,10 +83,12 @@ void qt_mac_set_dock_menu(QMenu *menu); #if defined(Q_WS_WIN) || defined(Q_WS_MAC) #include "programupdater.h" #endif +#include "powermanagement.h" using namespace libtorrent; #define TIME_TRAY_BALLOON 5000 +#define PREVENT_SUSPEND_INTERVAL 60000 /***************************************************** * * @@ -192,6 +197,10 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo connect(actionIncreasePriority, SIGNAL(triggered()), transferList, SLOT(increasePrioSelectedTorrents())); connect(actionDecreasePriority, SIGNAL(triggered()), transferList, SLOT(decreasePrioSelectedTorrents())); + m_pwr = new PowerManagement(this); + preventTimer = new QTimer(this); + connect(preventTimer, SIGNAL(timeout()), SLOT(checkForActiveTorrents())); + // Configure BT session according to options loadPreferences(false); @@ -290,13 +299,13 @@ MainWindow::MainWindow(QWidget *parent, QStringList torrentCmdLine) : QMainWindo updater->checkForUpdates(); } #endif - } void MainWindow::deleteBTSession() { guiUpdater->stop(); status_bar->stopTimer(); QBtSession::drop(); + m_pwr->setActivityState(false); QTimer::singleShot(0, this, SLOT(close())); } @@ -985,6 +994,17 @@ void MainWindow::loadPreferences(bool configure_session) { search_filter->clear(); toolBar->setVisible(false); } + + if(pref.preventFromSuspend()) + { + preventTimer->start(PREVENT_SUSPEND_INTERVAL); + } + else + { + preventTimer->stop(); + m_pwr->setActivityState(false); + } + const uint new_refreshInterval = pref.getRefreshInterval(); transferList->setRefreshInterval(new_refreshInterval); transferList->setAlternatingRowColors(pref.useAlternatingRowColors()); @@ -1313,3 +1333,12 @@ void MainWindow::on_actionAutoShutdown_system_toggled(bool enabled) qDebug() << Q_FUNC_INFO << enabled; Preferences().setShutdownWhenDownloadsComplete(enabled); } + +void MainWindow::checkForActiveTorrents() +{ + const TorrentStatusReport report = transferList->getSourceModel()->getTorrentStatusReport(); + if(report.nb_active > 0) // Active torrents are present; prevent system from suspend + m_pwr->setActivityState(true); + else + m_pwr->setActivityState(false); +} diff --git a/src/mainwindow.h b/src/mainwindow.h index 0416e4c08..fc335fc6a 100644 --- a/src/mainwindow.h +++ b/src/mainwindow.h @@ -60,6 +60,7 @@ class HidableTabWidget; class LineEdit; class QFileSystemWatcher; class ExecutionLog; +class PowerManagement; class MainWindow : public QMainWindow, private Ui::MainWindow{ Q_OBJECT @@ -182,6 +183,9 @@ private: QPointer rssWidget; // Execution Log QPointer m_executionLog; + // Power Management + PowerManagement *m_pwr; + QTimer *preventTimer; private slots: void on_actionSearch_engine_triggered(); @@ -194,6 +198,8 @@ private slots: void on_actionAutoExit_qBittorrent_toggled(bool ); void on_actionAutoSuspend_system_toggled(bool ); void on_actionAutoShutdown_system_toggled(bool ); + // Check for active torrents and set preventing from suspend state + void checkForActiveTorrents(); }; #endif diff --git a/src/powermanagement/powermanagement.cpp b/src/powermanagement/powermanagement.cpp new file mode 100644 index 000000000..6105ea47a --- /dev/null +++ b/src/powermanagement/powermanagement.cpp @@ -0,0 +1,90 @@ +/* + * Bittorrent Client using Qt4 and libtorrent. + * Copyright (C) 2011 Vladimir Golovnev + * + * 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. + * + * In addition, as a special exception, the copyright holders give permission to + * link this program with the OpenSSL project's "OpenSSL" library (or with + * modified versions of it that use the same license as the "OpenSSL" library), + * and distribute the linked executables. You must obey the GNU General Public + * License in all respects for all of the code used other than "OpenSSL". If you + * modify file(s), you may extend this exception to your version of the file(s), + * but you are not obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * Contact : chris@qbittorrent.org + */ + +#include + +#ifdef Q_WS_X11 +#include "powermanagement_x11.h" +#endif +#include "powermanagement.h" + +#ifdef Q_WS_MAC +#include +#endif + +#ifdef Q_WS_WIN +#include +#endif + +PowerManagement::PowerManagement(QObject *parent) : QObject(parent), m_busy(false) +{ +#ifdef Q_WS_X11 + m_inhibitor = new PowerManagementInhibitor(this); +#endif +} + +PowerManagement::~PowerManagement() +{ +} + +void PowerManagement::setActivityState(bool busy) +{ + if(busy) setBusy(); + else setIdle(); +} + +void PowerManagement::setBusy() +{ + if(m_busy) return; + m_busy = true; + +#ifdef Q_WS_WIN + SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED); +#elif defined(Q_WS_X11) + m_inhibitor->RequestBusy(); +#elif defined(Q_WS_MAC) + IOReturn success = IOPMAssertionCreate(kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn, &m_assertionID); + if(success != kIOReturnSuccess) m_busy = false; +#endif +} + +void PowerManagement::setIdle() +{ + if(!m_busy) return; + m_busy = false; + +#ifdef Q_WS_WIN + SetThreadExecutionState(ES_CONTINUOUS); +#elif defined(Q_WS_X11) + m_inhibitor->RequestIdle(); +#elif defined(Q_WS_MAC) + IOPMAssertionRelease(m_assertionID); +#endif +} diff --git a/src/powermanagement/powermanagement.h b/src/powermanagement/powermanagement.h new file mode 100644 index 000000000..5397957f0 --- /dev/null +++ b/src/powermanagement/powermanagement.h @@ -0,0 +1,70 @@ +/* + * Bittorrent Client using Qt4 and libtorrent. + * Copyright (C) 2011 Vladimir Golovnev + * + * 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. + * + * In addition, as a special exception, the copyright holders give permission to + * link this program with the OpenSSL project's "OpenSSL" library (or with + * modified versions of it that use the same license as the "OpenSSL" library), + * and distribute the linked executables. You must obey the GNU General Public + * License in all respects for all of the code used other than "OpenSSL". If you + * modify file(s), you may extend this exception to your version of the file(s), + * but you are not obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * Contact : chris@qbittorrent.org + */ + +#ifndef POWERMANAGEMENT_H +#define POWERMANAGEMENT_H + +#include + +#ifdef Q_WS_MAC +// Require Mac OS X >= 10.5 +#include +#endif + +#ifdef Q_WS_X11 +// Require DBus +class PowerManagementInhibitor; +#endif + +class PowerManagement : public QObject +{ + Q_OBJECT + +public: + PowerManagement(QObject *parent = 0); + virtual ~PowerManagement(); + + void setActivityState(bool busy); + +private: + bool m_busy; + + void setBusy(); + void setIdle(); + +#ifdef Q_WS_X11 + PowerManagementInhibitor *m_inhibitor; +#endif +#ifdef Q_WS_MAC + IOPMAssertionID m_assertionID; +#endif +}; + +#endif // POWERMANAGEMENT_H diff --git a/src/powermanagement/powermanagement.pri b/src/powermanagement/powermanagement.pri new file mode 100644 index 000000000..42602b0d1 --- /dev/null +++ b/src/powermanagement/powermanagement.pri @@ -0,0 +1,9 @@ +INCLUDEPATH += $$PWD + +HEADERS += $$PWD/powermanagement.h +SOURCES += $$PWD/powermanagement.cpp + +unix:!macx { + HEADERS += $$PWD/powermanagement_x11.h + SOURCES += $$PWD/powermanagement_x11.cpp +} diff --git a/src/powermanagement/powermanagement_x11.cpp b/src/powermanagement/powermanagement_x11.cpp new file mode 100644 index 000000000..2e90c32ee --- /dev/null +++ b/src/powermanagement/powermanagement_x11.cpp @@ -0,0 +1,185 @@ +/* + * Bittorrent Client using Qt4 and libtorrent. + * Copyright (C) 2011 Vladimir Golovnev + * + * 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. + * + * In addition, as a special exception, the copyright holders give permission to + * link this program with the OpenSSL project's "OpenSSL" library (or with + * modified versions of it that use the same license as the "OpenSSL" library), + * and distribute the linked executables. You must obey the GNU General Public + * License in all respects for all of the code used other than "OpenSSL". If you + * modify file(s), you may extend this exception to your version of the file(s), + * but you are not obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * Contact : chris@qbittorrent.org + */ + +#include +#include +#include +#include + +#include "powermanagement_x11.h" + +PowerManagementInhibitor::PowerManagementInhibitor(QObject *parent) : QObject(parent) +{ + if(!QDBusConnection::sessionBus().isConnected()) + { + qDebug("D-Bus: Could not connect to session bus"); + m_state = error; + } + else + { + m_state = idle; + } + + m_intended_state = idle; + m_cookie = 0; + m_use_gsm = false; +} + +PowerManagementInhibitor::~PowerManagementInhibitor() +{ +} + +void PowerManagementInhibitor::RequestIdle() +{ + m_intended_state = idle; + if (m_state == error || m_state == idle || m_state == request_idle || m_state == request_busy) + return; + + qDebug("D-Bus: PowerManagementInhibitor: Requesting idle"); + + QDBusMessage call; + if (!m_use_gsm) + call = QDBusMessage::createMethodCall( + "org.freedesktop.PowerManagement", + "/org/freedesktop/PowerManagement/Inhibit", + "org.freedesktop.PowerManagement.Inhibit", + "UnInhibit"); + else + call = QDBusMessage::createMethodCall( + "org.gnome.SessionManager", + "/org/gnome/SessionManager", + "org.gnome.SessionManager", + "Uninhibit"); + + m_state = request_idle; + + QList args; + args << m_cookie; + call.setArguments(args); + + QDBusPendingCall pcall = QDBusConnection::sessionBus().asyncCall(call, 1000); + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this); + connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), + this, SLOT(OnAsyncReply(QDBusPendingCallWatcher*))); +} + + +void PowerManagementInhibitor::RequestBusy() +{ + m_intended_state = busy; + if (m_state == error || m_state == busy || m_state == request_busy || m_state == request_idle) + return; + + qDebug("D-Bus: PowerManagementInhibitor: Requesting busy"); + + QDBusMessage call; + if (!m_use_gsm) + call = QDBusMessage::createMethodCall( + "org.freedesktop.PowerManagement", + "/org/freedesktop/PowerManagement/Inhibit", + "org.freedesktop.PowerManagement.Inhibit", + "Inhibit"); + else + call = QDBusMessage::createMethodCall( + "org.gnome.SessionManager", + "/org/gnome/SessionManager", + "org.gnome.SessionManager", + "Inhibit"); + + m_state = request_busy; + + QList args; + args << "qBittorrent"; + if (m_use_gsm) args << (uint)0; + args << "Active torrents are presented"; + if (m_use_gsm) args << (uint)8; + call.setArguments(args); + + QDBusPendingCall pcall = QDBusConnection::sessionBus().asyncCall(call, 1000); + QDBusPendingCallWatcher *watcher = new QDBusPendingCallWatcher(pcall, this); + connect(watcher, SIGNAL(finished(QDBusPendingCallWatcher*)), + this, SLOT(OnAsyncReply(QDBusPendingCallWatcher*))); +} + +void PowerManagementInhibitor::OnAsyncReply(QDBusPendingCallWatcher *call) +{ + if (m_state == request_idle) + { + QDBusPendingReply<> reply = *call; + + if(reply.isError()) + { + qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message())); + m_state = error; + } + else + { + m_state = idle; + qDebug("D-Bus: PowerManagementInhibitor: Request successful"); + if (m_intended_state == busy) RequestBusy(); + } + } + else if (m_state == request_busy) + { + QDBusPendingReply reply = *call; + + if(reply.isError()) + { + qDebug("D-Bus: Reply: Error: %s", qPrintable(reply.error().message())); + + if (!m_use_gsm) + { + qDebug("D-Bus: Falling back to org.gnome.SessionManager"); + m_use_gsm = true; + m_state = idle; + if (m_intended_state == busy) + RequestBusy(); + } + else + { + m_state = error; + } + } + else + { + m_state = busy; + m_cookie = reply.value(); + qDebug("D-Bus: PowerManagementInhibitor: Request successful, cookie is %d", m_cookie); + if (m_intended_state == idle) RequestIdle(); + } + } + else + { + qDebug("D-Bus: Unexpected reply in state %d", m_state); + m_state = error; + } + + call->deleteLater(); +} diff --git a/src/powermanagement/powermanagement_x11.h b/src/powermanagement/powermanagement_x11.h new file mode 100644 index 000000000..ecd68506d --- /dev/null +++ b/src/powermanagement/powermanagement_x11.h @@ -0,0 +1,69 @@ +/* + * Bittorrent Client using Qt4 and libtorrent. + * Copyright (C) 2011 Vladimir Golovnev + * + * 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. + * + * In addition, as a special exception, the copyright holders give permission to + * link this program with the OpenSSL project's "OpenSSL" library (or with + * modified versions of it that use the same license as the "OpenSSL" library), + * and distribute the linked executables. You must obey the GNU General Public + * License in all respects for all of the code used other than "OpenSSL". If you + * modify file(s), you may extend this exception to your version of the file(s), + * but you are not obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * Contact : chris@qbittorrent.org + */ + +#ifndef POWERMANAGEMENTINHIBITOR_H +#define POWERMANAGEMENTINHIBITOR_H + +#include + +class QDBusPendingCallWatcher; + +class PowerManagementInhibitor : public QObject +{ + Q_OBJECT + +public: + PowerManagementInhibitor(QObject *parent = 0); + virtual ~PowerManagementInhibitor(); + + void RequestIdle(); + void RequestBusy(); + +private slots: + void OnAsyncReply(QDBusPendingCallWatcher *call); + +private: + enum _state + { + error, + idle, + request_busy, + busy, + request_idle + }; + + enum _state m_state; + enum _state m_intended_state; + unsigned int m_cookie; + + bool m_use_gsm; +}; + +#endif // POWERMANAGEMENTINHIBITOR_H diff --git a/src/preferences/advancedsettings.h b/src/preferences/advancedsettings.h index d1998b42c..8ff18f286 100644 --- a/src/preferences/advancedsettings.h +++ b/src/preferences/advancedsettings.h @@ -241,7 +241,7 @@ protected slots: connect(txt_network_address, SIGNAL(textChanged(QString)), this, SLOT(emitSettingsChanged())); setCellWidget(NETWORK_ADDRESS, VALUE, txt_network_address); // Program notifications - setItem(PROGRAM_NOTIFICATIONS, PROPERTY, new QTableWidgetItem(tr("Display program notification balloons"))); + setItem(PROGRAM_NOTIFICATIONS, PROPERTY, new QTableWidgetItem(tr("Display program on-screen notifications"))); cb_program_notifications = new QCheckBox(); connect(cb_program_notifications, SIGNAL(toggled(bool)), this, SLOT(emitSettingsChanged())); cb_program_notifications->setChecked(pref.useProgramNotification()); diff --git a/src/preferences/options.ui b/src/preferences/options.ui index 8c838d546..16bd764f0 100644 --- a/src/preferences/options.ui +++ b/src/preferences/options.ui @@ -40,16 +40,10 @@ - 30 - 30 + 32 + 32 - - Qt::ElideNone - - - QListView::Static - QListView::LeftToRight @@ -59,24 +53,18 @@ QListView::Adjust - - QListView::SinglePass - - 0 + 4 - 107 + 110 60 QListView::IconMode - - false - false @@ -88,10 +76,10 @@ - UI + Behavior - User Interface + Behavior AlignHCenter|AlignVCenter|AlignCenter @@ -126,6 +114,9 @@ Speed + + AlignHCenter|AlignVCenter|AlignCenter + @@ -153,6 +144,9 @@ Advanced + + AlignHCenter|AlignVCenter|AlignCenter + @@ -176,16 +170,16 @@ 0 - 0 - 506 - 430 + -45 + 499 + 459 - Visual Appearance + Language @@ -193,13 +187,6 @@ - - - - Language: - - - @@ -247,33 +234,6 @@ - - - - - - Visual style: - - - - - - - - - - Qt::Horizontal - - - - 40 - 20 - - - - - - @@ -450,6 +410,22 @@ + + + + Power Management + + + + + + Inhibit system sleep when torrents are active + + + + + + @@ -481,7 +457,7 @@ 0 0 - 506 + 440 698 @@ -924,7 +900,7 @@ QGroupBox { 0 0 - 506 + 447 457 @@ -1404,8 +1380,8 @@ QGroupBox { 0 0 - 524 - 414 + 404 + 334 @@ -1793,7 +1769,7 @@ QGroupBox { 0 0 - 581 + 542 422 @@ -2176,7 +2152,7 @@ QGroupBox { 0 0 - 377 + 378 229 @@ -2339,8 +2315,8 @@ QGroupBox { 0 0 - 98 - 28 + 80 + 18 @@ -2387,7 +2363,6 @@ QGroupBox { tabOption comboI18n - comboStyle checkCloseToSystray checkMinimizeToSysTray textSavePath diff --git a/src/preferences/options_imp.cpp b/src/preferences/options_imp.cpp index 1d0f6ea34..d70c9561f 100644 --- a/src/preferences/options_imp.cpp +++ b/src/preferences/options_imp.cpp @@ -36,7 +36,6 @@ #include #include #include -#include #include #include @@ -88,7 +87,6 @@ options_imp::options_imp(QWidget *parent): connect(scanFoldersView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(handleScanFolderViewSelectionChanged())); connect(buttonBox, SIGNAL(clicked(QAbstractButton*)), this, SLOT(applySettings(QAbstractButton*))); - comboStyle->addItems(QStyleFactory::keys()); // Languages supported initializeLanguageCombo(); @@ -126,13 +124,13 @@ options_imp::options_imp(QWidget *parent): // Apply button is activated when a value is changed // General tab connect(comboI18n, SIGNAL(currentIndexChanged(int)), this, SLOT(enableApplyButton())); - connect(comboStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(enableApplyButton())); connect(checkAltRowColors, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); connect(checkShowSystray, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); connect(checkCloseToSystray, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); connect(checkMinimizeToSysTray, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); connect(checkStartMinimized, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); connect(checkShowSplash, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); + connect(checkPreventFromSuspend, SIGNAL(toggled(bool)), this, SLOT(enableApplyButton())); // Downloads tab connect(textSavePath, SIGNAL(textChanged(QString)), this, SLOT(enableApplyButton())); connect(textTempPath, SIGNAL(textChanged(QString)), this, SLOT(enableApplyButton())); @@ -251,10 +249,6 @@ void options_imp::changePage(QListWidgetItem *current, QListWidgetItem *previous tabOption->setCurrentIndex(tabSelection->row(current)); } -void options_imp::useStyle() { - QApplication::setStyle(QStyleFactory::create(comboStyle->itemText(comboStyle->currentIndex()))); -} - void options_imp::loadWindowState() { QIniSettings settings(QString::fromUtf8("qBittorrent"), QString::fromUtf8("qBittorrent")); resize(settings.value(QString::fromUtf8("Preferences/State/size"), sizeFittingScreen()).toSize()); @@ -308,8 +302,6 @@ QSize options_imp::sizeFittingScreen() { void options_imp::saveOptions(){ applyButton->setEnabled(false); Preferences pref; - // Apply style - useStyle(); // Load the translation QString locale = getLocale(); if(pref.getLocale() != locale) { @@ -324,13 +316,13 @@ void options_imp::saveOptions(){ // General preferences pref.setLocale(locale); - pref.setStyle(getStyle()); pref.setAlternatingRowColors(checkAltRowColors->isChecked()); pref.setSystrayIntegration(systrayIntegration()); pref.setCloseToTray(closeToTray()); pref.setMinimizeToTray(minimizeToTray()); pref.setStartMinimized(startMinimized()); pref.setSplashScreenDisabled(isSlashScreenDisabled()); + pref.setPreventFromSuspend(preventFromSuspend()); // End General preferences // Downloads preferences @@ -455,16 +447,6 @@ int options_imp::getProxyType() const{ } } -QString options_imp::getStyle() const{ - return comboStyle->itemText(comboStyle->currentIndex()); -} - -void options_imp::setStyle(QString style) { - int index = comboStyle->findText(style, Qt::MatchFixedString); - if(index > 0) - comboStyle->setCurrentIndex(index); -} - void options_imp::loadOptions(){ int intValue; qreal floatValue; @@ -472,7 +454,6 @@ void options_imp::loadOptions(){ // General preferences const Preferences pref; setLocale(pref.getLocale()); - setStyle(pref.getStyle()); checkAltRowColors->setChecked(pref.useAlternatingRowColors()); checkShowSystray->setChecked(pref.systrayIntegration()); checkShowSplash->setChecked(!pref.isSlashScreenDisabled()); @@ -484,6 +465,7 @@ void options_imp::loadOptions(){ checkMinimizeToSysTray->setChecked(pref.minimizeToTray()); checkStartMinimized->setChecked(pref.startMinimized()); } + checkPreventFromSuspend->setChecked(pref.preventFromSuspend()); // End General preferences // Downloads preferences QString save_path = pref.getSavePath(); @@ -928,6 +910,10 @@ bool options_imp::isSlashScreenDisabled() const { return !checkShowSplash->isChecked(); } +bool options_imp::preventFromSuspend() const { + return checkPreventFromSuspend->isChecked(); +} + bool options_imp::preAllocateAllFiles() const { return checkPreallocateAll->isChecked(); } diff --git a/src/preferences/options_imp.h b/src/preferences/options_imp.h index c77a327f1..0e29334e2 100644 --- a/src/preferences/options_imp.h +++ b/src/preferences/options_imp.h @@ -60,7 +60,6 @@ protected slots: void enableMaxConnecsLimitPerTorrent(bool checked); void enableMaxUploadsLimitPerTorrent(bool checked); void enableMaxRatio(bool checked); - void setStyle(QString style); void on_buttonBox_accepted(); void closeEvent(QCloseEvent *e); void on_buttonBox_rejected(); @@ -85,7 +84,6 @@ protected slots: public slots: void setLocale(QString locale); - void useStyle(); void showConnectionTab(); signals: @@ -100,12 +98,12 @@ private: static QString languageToLocalizedString(QLocale::Language language, const QString& country); // General options QString getLocale() const; - QString getStyle() const; bool systrayIntegration() const; bool minimizeToTray() const; bool closeToTray() const; bool startMinimized() const; bool isSlashScreenDisabled() const; + bool preventFromSuspend() const; // Downloads QString getSavePath() const; bool isTempPathEnabled() const; diff --git a/src/preferences/preferences.h b/src/preferences/preferences.h index 79905cb02..c17745571 100644 --- a/src/preferences/preferences.h +++ b/src/preferences/preferences.h @@ -77,14 +77,6 @@ public: setValue(QString::fromUtf8("Preferences/General/Locale"), locale); } - QString getStyle() const { - return value(QString::fromUtf8("Preferences/General/Style"), "").toString(); - } - - void setStyle(const QString &style) { - setValue(QString::fromUtf8("Preferences/General/Style"), style); - } - bool useProgramNotification() const { return value(QString::fromUtf8("Preferences/General/ProgramNotification"), true).toBool(); } @@ -173,6 +165,15 @@ public: setValue("Preferences/General/NoSplashScreen", b); } + // Preventing from system suspend while active torrents are presented. + bool preventFromSuspend() const { + return value(QString::fromUtf8("Preferences/General/PreventFromSuspend"), false).toBool(); + } + + void setPreventFromSuspend(bool b) { + setValue("Preferences/General/PreventFromSuspend", b); + } + // Downloads QString getSavePath() const { #ifdef Q_WS_WIN diff --git a/src/src.pro b/src/src.pro index 0dacf35c4..1f7cb6e15 100644 --- a/src/src.pro +++ b/src/src.pro @@ -87,6 +87,7 @@ include (preferences/preferences.pri) include(rss/rss.pri) include(torrentcreator/torrentcreator.pri) include(geoip/geoip.pri) + include(powermanagement/powermanagement.pri) } HEADERS += misc.h \