Move some functions into Utils::OS namespace
[qBittorrent.git] / src / app / application.cpp
bloba715b60fc653233b40bb2a703bdea1576e626cef
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2015 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * In addition, as a special exception, the copyright holders give permission to
21 * link this program with the OpenSSL project's "OpenSSL" library (or with
22 * modified versions of it that use the same license as the "OpenSSL" library),
23 * and distribute the linked executables. You must obey the GNU General Public
24 * License in all respects for all of the code used other than "OpenSSL". If you
25 * modify file(s), you may extend this exception to your version of the file(s),
26 * but you are not obligated to do so. If you do not wish to do so, delete this
27 * exception statement from your version.
30 #include "application.h"
32 #include <algorithm>
34 #ifdef DISABLE_GUI
35 #include <cstdio>
36 #endif
38 #ifdef Q_OS_WIN
39 #include <memory>
40 #include <windows.h>
41 #include <shellapi.h>
42 #elif defined(Q_OS_UNIX)
43 #include <sys/resource.h>
44 #endif
46 #include <QByteArray>
47 #include <QDebug>
48 #include <QLibraryInfo>
49 #include <QMetaObject>
50 #include <QProcess>
52 #ifndef DISABLE_GUI
53 #include <QAbstractButton>
54 #include <QMenu>
55 #include <QMessageBox>
56 #include <QPixmapCache>
57 #include <QProgressDialog>
58 #ifdef Q_OS_WIN
59 #include <QSessionManager>
60 #include <QSharedMemory>
61 #endif // Q_OS_WIN
62 #ifdef Q_OS_MACOS
63 #include <QFileOpenEvent>
64 #endif // Q_OS_MACOS
65 #endif
67 #include "base/addtorrentmanager.h"
68 #include "base/bittorrent/infohash.h"
69 #include "base/bittorrent/session.h"
70 #include "base/bittorrent/torrent.h"
71 #include "base/exceptions.h"
72 #include "base/global.h"
73 #include "base/iconprovider.h"
74 #include "base/logger.h"
75 #include "base/net/downloadmanager.h"
76 #include "base/net/geoipmanager.h"
77 #include "base/net/proxyconfigurationmanager.h"
78 #include "base/net/smtp.h"
79 #include "base/preferences.h"
80 #include "base/profile.h"
81 #include "base/rss/rss_autodownloader.h"
82 #include "base/rss/rss_session.h"
83 #include "base/search/searchpluginmanager.h"
84 #include "base/settingsstorage.h"
85 #include "base/torrentfileswatcher.h"
86 #include "base/utils/fs.h"
87 #include "base/utils/misc.h"
88 #include "base/utils/os.h"
89 #include "base/utils/string.h"
90 #include "base/version.h"
91 #include "applicationinstancemanager.h"
92 #include "filelogger.h"
93 #include "upgrade.h"
95 #ifndef DISABLE_GUI
96 #include "gui/guiaddtorrentmanager.h"
97 #include "gui/desktopintegration.h"
98 #include "gui/mainwindow.h"
99 #include "gui/shutdownconfirmdialog.h"
100 #include "gui/uithememanager.h"
101 #include "gui/utils.h"
102 #include "gui/windowstate.h"
103 #endif // DISABLE_GUI
105 #ifndef DISABLE_WEBUI
106 #include "webui/webui.h"
107 #endif
109 namespace
111 #define SETTINGS_KEY(name) u"Application/" name
112 #define FILELOGGER_SETTINGS_KEY(name) (SETTINGS_KEY(u"FileLogger/") name)
113 #define NOTIFICATIONS_SETTINGS_KEY(name) (SETTINGS_KEY(u"GUI/Notifications/"_s) name)
115 const QString LOG_FOLDER = u"logs"_s;
116 const QChar PARAMS_SEPARATOR = u'|';
118 const Path DEFAULT_PORTABLE_MODE_PROFILE_DIR {u"profile"_s};
120 const int MIN_FILELOG_SIZE = 1024; // 1KiB
121 const int MAX_FILELOG_SIZE = 1000 * 1024 * 1024; // 1000MiB
122 const int DEFAULT_FILELOG_SIZE = 65 * 1024; // 65KiB
124 #ifndef DISABLE_GUI
125 const int PIXMAP_CACHE_SIZE = 64 * 1024 * 1024; // 64MiB
126 #endif
128 QString serializeParams(const QBtCommandLineParameters &params)
130 QStringList result;
131 // Because we're passing a string list to the currently running
132 // qBittorrent process, we need some way of passing along the options
133 // the user has specified. Here we place special strings that are
134 // almost certainly not going to collide with a file path or URL
135 // specified by the user, and placing them at the beginning of the
136 // string list so that they will be processed before the list of
137 // torrent paths or URLs.
139 const BitTorrent::AddTorrentParams &addTorrentParams = params.addTorrentParams;
141 if (!addTorrentParams.savePath.isEmpty())
142 result.append(u"@savePath=" + addTorrentParams.savePath.data());
144 if (addTorrentParams.addPaused.has_value())
145 result.append(*addTorrentParams.addPaused ? u"@addPaused=1"_s : u"@addPaused=0"_s);
147 if (addTorrentParams.skipChecking)
148 result.append(u"@skipChecking"_s);
150 if (!addTorrentParams.category.isEmpty())
151 result.append(u"@category=" + addTorrentParams.category);
153 if (addTorrentParams.sequential)
154 result.append(u"@sequential"_s);
156 if (addTorrentParams.firstLastPiecePriority)
157 result.append(u"@firstLastPiecePriority"_s);
159 if (params.skipDialog.has_value())
160 result.append(*params.skipDialog ? u"@skipDialog=1"_s : u"@skipDialog=0"_s);
162 result += params.torrentSources;
164 return result.join(PARAMS_SEPARATOR);
167 QBtCommandLineParameters parseParams(const QString &str)
169 QBtCommandLineParameters parsedParams;
170 BitTorrent::AddTorrentParams &addTorrentParams = parsedParams.addTorrentParams;
172 for (QString param : asConst(str.split(PARAMS_SEPARATOR, Qt::SkipEmptyParts)))
174 param = param.trimmed();
176 // Process strings indicating options specified by the user.
178 if (param.startsWith(u"@savePath="))
180 addTorrentParams.savePath = Path(param.mid(10));
181 continue;
184 if (param.startsWith(u"@addPaused="))
186 addTorrentParams.addPaused = (QStringView(param).mid(11).toInt() != 0);
187 continue;
190 if (param == u"@skipChecking")
192 addTorrentParams.skipChecking = true;
193 continue;
196 if (param.startsWith(u"@category="))
198 addTorrentParams.category = param.mid(10);
199 continue;
202 if (param == u"@sequential")
204 addTorrentParams.sequential = true;
205 continue;
208 if (param == u"@firstLastPiecePriority")
210 addTorrentParams.firstLastPiecePriority = true;
211 continue;
214 if (param.startsWith(u"@skipDialog="))
216 parsedParams.skipDialog = (QStringView(param).mid(12).toInt() != 0);
217 continue;
220 parsedParams.torrentSources.append(param);
223 return parsedParams;
227 Application::Application(int &argc, char **argv)
228 : BaseApplication(argc, argv)
229 , m_commandLineArgs(parseCommandLine(Application::arguments()))
230 , m_storeFileLoggerEnabled(FILELOGGER_SETTINGS_KEY(u"Enabled"_s))
231 , m_storeFileLoggerBackup(FILELOGGER_SETTINGS_KEY(u"Backup"_s))
232 , m_storeFileLoggerDeleteOld(FILELOGGER_SETTINGS_KEY(u"DeleteOld"_s))
233 , m_storeFileLoggerMaxSize(FILELOGGER_SETTINGS_KEY(u"MaxSizeBytes"_s))
234 , m_storeFileLoggerAge(FILELOGGER_SETTINGS_KEY(u"Age"_s))
235 , m_storeFileLoggerAgeType(FILELOGGER_SETTINGS_KEY(u"AgeType"_s))
236 , m_storeFileLoggerPath(FILELOGGER_SETTINGS_KEY(u"Path"_s))
237 , m_storeMemoryWorkingSetLimit(SETTINGS_KEY(u"MemoryWorkingSetLimit"_s))
238 #ifdef Q_OS_WIN
239 , m_processMemoryPriority(SETTINGS_KEY(u"ProcessMemoryPriority"_s))
240 #endif
241 #ifndef DISABLE_GUI
242 , m_startUpWindowState(u"GUI/StartUpWindowState"_s)
243 , m_storeNotificationTorrentAdded(NOTIFICATIONS_SETTINGS_KEY(u"TorrentAdded"_s))
244 #endif
246 qRegisterMetaType<Log::Msg>("Log::Msg");
247 qRegisterMetaType<Log::Peer>("Log::Peer");
249 setApplicationName(u"qBittorrent"_s);
250 setOrganizationDomain(u"qbittorrent.org"_s);
251 #if !defined(DISABLE_GUI)
252 setDesktopFileName(u"org.qbittorrent.qBittorrent"_s);
253 setQuitOnLastWindowClosed(false);
254 QPixmapCache::setCacheLimit(PIXMAP_CACHE_SIZE);
255 #endif
257 Logger::initInstance();
259 const auto portableProfilePath = Path(QCoreApplication::applicationDirPath()) / DEFAULT_PORTABLE_MODE_PROFILE_DIR;
260 const bool portableModeEnabled = m_commandLineArgs.profileDir.isEmpty() && portableProfilePath.exists();
262 const Path profileDir = portableModeEnabled
263 ? portableProfilePath
264 : m_commandLineArgs.profileDir;
265 Profile::initInstance(profileDir, m_commandLineArgs.configurationName,
266 (m_commandLineArgs.relativeFastresumePaths || portableModeEnabled));
268 m_instanceManager = new ApplicationInstanceManager(Profile::instance()->location(SpecialFolder::Config), this);
270 SettingsStorage::initInstance();
271 Preferences::initInstance();
273 const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal();
274 if (!firstTimeUser)
276 if (!upgrade())
277 throw RuntimeError(u"Failed migration of old settings"_s); // Not translatable. Translation isn't configured yet.
278 handleChangedDefaults(DefaultPreferencesMode::Legacy);
280 else
282 handleChangedDefaults(DefaultPreferencesMode::Current);
285 initializeTranslation();
287 connect(this, &QCoreApplication::aboutToQuit, this, &Application::cleanup);
288 connect(m_instanceManager, &ApplicationInstanceManager::messageReceived, this, &Application::processMessage);
289 #if defined(Q_OS_WIN) && !defined(DISABLE_GUI)
290 connect(this, &QGuiApplication::commitDataRequest, this, &Application::shutdownCleanup, Qt::DirectConnection);
291 #endif
293 LogMsg(tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(QStringLiteral(QBT_VERSION)));
294 if (portableModeEnabled)
296 LogMsg(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir.toString()));
297 if (m_commandLineArgs.relativeFastresumePaths)
298 LogMsg(tr("Redundant command line flag detected: \"%1\". Portable mode implies relative fastresume.").arg(u"--relative-fastresume"_s), Log::WARNING); // to avoid translating the `--relative-fastresume` string
300 else
302 LogMsg(tr("Using config directory: %1").arg(Profile::instance()->location(SpecialFolder::Config).toString()));
305 if (isFileLoggerEnabled())
306 m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
308 if (m_commandLineArgs.webUiPort > 0) // it will be -1 when user did not set any value
309 Preferences::instance()->setWebUiPort(m_commandLineArgs.webUiPort);
311 if (m_commandLineArgs.torrentingPort > 0) // it will be -1 when user did not set any value
313 SettingValue<int> port {u"BitTorrent/Session/Port"_s};
314 port = m_commandLineArgs.torrentingPort;
318 Application::~Application()
320 // we still need to call cleanup()
321 // in case the App failed to start
322 cleanup();
325 #ifndef DISABLE_GUI
326 DesktopIntegration *Application::desktopIntegration()
328 return m_desktopIntegration;
331 MainWindow *Application::mainWindow()
333 return m_window;
336 WindowState Application::startUpWindowState() const
338 return m_startUpWindowState;
341 void Application::setStartUpWindowState(const WindowState windowState)
343 m_startUpWindowState = windowState;
346 bool Application::isTorrentAddedNotificationsEnabled() const
348 return m_storeNotificationTorrentAdded;
351 void Application::setTorrentAddedNotificationsEnabled(const bool value)
353 m_storeNotificationTorrentAdded = value;
355 #endif
357 const QBtCommandLineParameters &Application::commandLineArgs() const
359 return m_commandLineArgs;
362 int Application::memoryWorkingSetLimit() const
364 return m_storeMemoryWorkingSetLimit.get(512);
367 void Application::setMemoryWorkingSetLimit(const int size)
369 if (size == memoryWorkingSetLimit())
370 return;
372 m_storeMemoryWorkingSetLimit = size;
373 #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
374 applyMemoryWorkingSetLimit();
375 #endif
378 bool Application::isFileLoggerEnabled() const
380 return m_storeFileLoggerEnabled.get(true);
383 void Application::setFileLoggerEnabled(const bool value)
385 if (value && !m_fileLogger)
386 m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
387 else if (!value)
388 delete m_fileLogger;
389 m_storeFileLoggerEnabled = value;
392 Path Application::fileLoggerPath() const
394 return m_storeFileLoggerPath.get(specialFolderLocation(SpecialFolder::Data) / Path(LOG_FOLDER));
397 void Application::setFileLoggerPath(const Path &path)
399 if (m_fileLogger)
400 m_fileLogger->changePath(path);
401 m_storeFileLoggerPath = path;
404 bool Application::isFileLoggerBackup() const
406 return m_storeFileLoggerBackup.get(true);
409 void Application::setFileLoggerBackup(const bool value)
411 if (m_fileLogger)
412 m_fileLogger->setBackup(value);
413 m_storeFileLoggerBackup = value;
416 bool Application::isFileLoggerDeleteOld() const
418 return m_storeFileLoggerDeleteOld.get(true);
421 void Application::setFileLoggerDeleteOld(const bool value)
423 if (value && m_fileLogger)
424 m_fileLogger->deleteOld(fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
425 m_storeFileLoggerDeleteOld = value;
428 int Application::fileLoggerMaxSize() const
430 const int val = m_storeFileLoggerMaxSize.get(DEFAULT_FILELOG_SIZE);
431 return std::clamp(val, MIN_FILELOG_SIZE, MAX_FILELOG_SIZE);
434 void Application::setFileLoggerMaxSize(const int bytes)
436 const int clampedValue = std::clamp(bytes, MIN_FILELOG_SIZE, MAX_FILELOG_SIZE);
437 if (m_fileLogger)
438 m_fileLogger->setMaxSize(clampedValue);
439 m_storeFileLoggerMaxSize = clampedValue;
442 int Application::fileLoggerAge() const
444 const int val = m_storeFileLoggerAge.get(1);
445 return std::clamp(val, 1, 365);
448 void Application::setFileLoggerAge(const int value)
450 m_storeFileLoggerAge = std::clamp(value, 1, 365);
453 int Application::fileLoggerAgeType() const
455 const int val = m_storeFileLoggerAgeType.get(1);
456 return ((val < 0) || (val > 2)) ? 1 : val;
459 void Application::setFileLoggerAgeType(const int value)
461 m_storeFileLoggerAgeType = ((value < 0) || (value > 2)) ? 1 : value;
464 void Application::processMessage(const QString &message)
466 #ifndef DISABLE_GUI
467 if (message.isEmpty())
469 if (BitTorrent::Session::instance()->isRestored()) [[likely]]
471 m_window->activate(); // show UI
473 else if (m_startupProgressDialog)
475 m_startupProgressDialog->show();
476 m_startupProgressDialog->activateWindow();
477 m_startupProgressDialog->raise();
479 else
481 createStartupProgressDialog();
484 return;
486 #endif
488 const QBtCommandLineParameters params = parseParams(message);
489 // If Application is not allowed to process params immediately
490 // (i.e., other components are not ready) store params
491 if (m_isProcessingParamsAllowed)
492 processParams(params);
493 else
494 m_paramsQueue.append(params);
497 void Application::runExternalProgram(const QString &programTemplate, const BitTorrent::Torrent *torrent) const
499 // Cannot give users shell environment by default, as doing so could
500 // enable command injection via torrent name and other arguments
501 // (especially when some automated download mechanism has been setup).
502 // See: https://github.com/qbittorrent/qBittorrent/issues/10925
504 const auto replaceVariables = [torrent](QString str) -> QString
506 for (int i = (str.length() - 2); i >= 0; --i)
508 if (str[i] != u'%')
509 continue;
511 const ushort specifier = str[i + 1].unicode();
512 switch (specifier)
514 case u'C':
515 str.replace(i, 2, QString::number(torrent->filesCount()));
516 break;
517 case u'D':
518 str.replace(i, 2, torrent->savePath().toString());
519 break;
520 case u'F':
521 str.replace(i, 2, torrent->contentPath().toString());
522 break;
523 case u'G':
524 str.replace(i, 2, torrent->tags().join(u","_s));
525 break;
526 case u'I':
527 str.replace(i, 2, (torrent->infoHash().v1().isValid() ? torrent->infoHash().v1().toString() : u"-"_s));
528 break;
529 case u'J':
530 str.replace(i, 2, (torrent->infoHash().v2().isValid() ? torrent->infoHash().v2().toString() : u"-"_s));
531 break;
532 case u'K':
533 str.replace(i, 2, torrent->id().toString());
534 break;
535 case u'L':
536 str.replace(i, 2, torrent->category());
537 break;
538 case u'N':
539 str.replace(i, 2, torrent->name());
540 break;
541 case u'R':
542 str.replace(i, 2, torrent->rootPath().toString());
543 break;
544 case u'T':
545 str.replace(i, 2, torrent->currentTracker());
546 break;
547 case u'Z':
548 str.replace(i, 2, QString::number(torrent->totalSize()));
549 break;
550 default:
551 // do nothing
552 break;
555 // decrement `i` to avoid unwanted replacement, example pattern: "%%N"
556 --i;
559 return str;
562 const QString logMsg = tr("Running external program. Torrent: \"%1\". Command: `%2`");
563 const QString logMsgError = tr("Failed to run external program. Torrent: \"%1\". Command: `%2`");
565 // The processing sequenece is different for Windows and other OS, this is intentional
566 #if defined(Q_OS_WIN)
567 const QString program = replaceVariables(programTemplate);
568 const std::wstring programWStr = program.toStdWString();
570 // Need to split arguments manually because QProcess::startDetached(QString)
571 // will strip off empty parameters.
572 // E.g. `python.exe "1" "" "3"` will become `python.exe "1" "3"`
573 int argCount = 0;
574 std::unique_ptr<LPWSTR[], decltype(&::LocalFree)> args {::CommandLineToArgvW(programWStr.c_str(), &argCount), ::LocalFree};
576 if (argCount <= 0)
577 return;
579 QStringList argList;
580 for (int i = 1; i < argCount; ++i)
581 argList += QString::fromWCharArray(args[i]);
583 QProcess proc;
584 proc.setProgram(QString::fromWCharArray(args[0]));
585 proc.setArguments(argList);
586 proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments *args)
588 if (Preferences::instance()->isAutoRunConsoleEnabled())
590 args->flags |= CREATE_NEW_CONSOLE;
591 args->flags &= ~(CREATE_NO_WINDOW | DETACHED_PROCESS);
593 else
595 args->flags |= CREATE_NO_WINDOW;
596 args->flags &= ~(CREATE_NEW_CONSOLE | DETACHED_PROCESS);
598 args->inheritHandles = false;
599 args->startupInfo->dwFlags &= ~STARTF_USESTDHANDLES;
600 ::CloseHandle(args->startupInfo->hStdInput);
601 ::CloseHandle(args->startupInfo->hStdOutput);
602 ::CloseHandle(args->startupInfo->hStdError);
603 args->startupInfo->hStdInput = nullptr;
604 args->startupInfo->hStdOutput = nullptr;
605 args->startupInfo->hStdError = nullptr;
608 if (proc.startDetached())
609 LogMsg(logMsg.arg(torrent->name(), program));
610 else
611 LogMsg(logMsgError.arg(torrent->name(), program));
612 #else // Q_OS_WIN
613 QStringList args = Utils::String::splitCommand(programTemplate);
615 if (args.isEmpty())
616 return;
618 for (QString &arg : args)
620 // strip redundant quotes
621 if (arg.startsWith(u'"') && arg.endsWith(u'"'))
622 arg = arg.mid(1, (arg.size() - 2));
624 arg = replaceVariables(arg);
627 const QString command = args.takeFirst();
628 QProcess proc;
629 proc.setProgram(command);
630 proc.setArguments(args);
632 if (proc.startDetached())
634 // show intended command in log
635 LogMsg(logMsg.arg(torrent->name(), replaceVariables(programTemplate)));
637 else
639 // show intended command in log
640 LogMsg(logMsgError.arg(torrent->name(), replaceVariables(programTemplate)));
642 #endif
645 void Application::sendNotificationEmail(const BitTorrent::Torrent *torrent)
647 // Prepare mail content
648 const QString content = tr("Torrent name: %1").arg(torrent->name()) + u'\n'
649 + tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + u'\n'
650 + tr("Save path: %1").arg(torrent->savePath().toString()) + u"\n\n"
651 + tr("The torrent was downloaded in %1.", "The torrent was downloaded in 1 hour and 20 seconds")
652 .arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + u"\n\n\n"
653 + tr("Thank you for using qBittorrent.") + u'\n';
655 // Send the notification email
656 const Preferences *pref = Preferences::instance();
657 auto *smtp = new Net::Smtp(this);
658 smtp->sendMail(pref->getMailNotificationSender(),
659 pref->getMailNotificationEmail(),
660 tr("Torrent \"%1\" has finished downloading").arg(torrent->name()),
661 content);
664 void Application::torrentAdded(const BitTorrent::Torrent *torrent) const
666 const Preferences *pref = Preferences::instance();
668 // AutoRun program
669 if (pref->isAutoRunOnTorrentAddedEnabled())
670 runExternalProgram(pref->getAutoRunOnTorrentAddedProgram().trimmed(), torrent);
673 void Application::torrentFinished(const BitTorrent::Torrent *torrent)
675 const Preferences *pref = Preferences::instance();
677 // AutoRun program
678 if (pref->isAutoRunOnTorrentFinishedEnabled())
679 runExternalProgram(pref->getAutoRunOnTorrentFinishedProgram().trimmed(), torrent);
681 // Mail notification
682 if (pref->isMailNotificationEnabled())
684 LogMsg(tr("Torrent: %1, sending mail notification").arg(torrent->name()));
685 sendNotificationEmail(torrent);
688 #ifndef DISABLE_GUI
689 if (Preferences::instance()->isRecursiveDownloadEnabled())
691 // Check whether it contains .torrent files
692 for (const Path &torrentRelpath : asConst(torrent->filePaths()))
694 if (torrentRelpath.hasExtension(u".torrent"_s))
696 askRecursiveTorrentDownloadConfirmation(torrent);
697 break;
701 #endif
704 void Application::allTorrentsFinished()
706 Preferences *const pref = Preferences::instance();
707 bool isExit = pref->shutdownqBTWhenDownloadsComplete();
708 bool isShutdown = pref->shutdownWhenDownloadsComplete();
709 bool isSuspend = pref->suspendWhenDownloadsComplete();
710 bool isHibernate = pref->hibernateWhenDownloadsComplete();
712 bool haveAction = isExit || isShutdown || isSuspend || isHibernate;
713 if (!haveAction) return;
715 ShutdownDialogAction action = ShutdownDialogAction::Exit;
716 if (isSuspend)
717 action = ShutdownDialogAction::Suspend;
718 else if (isHibernate)
719 action = ShutdownDialogAction::Hibernate;
720 else if (isShutdown)
721 action = ShutdownDialogAction::Shutdown;
723 #ifndef DISABLE_GUI
724 // ask confirm
725 if ((action == ShutdownDialogAction::Exit) && (pref->dontConfirmAutoExit()))
727 // do nothing & skip confirm
729 else
731 if (!ShutdownConfirmDialog::askForConfirmation(m_window, action)) return;
733 #endif // DISABLE_GUI
735 // Actually shut down
736 if (action != ShutdownDialogAction::Exit)
738 qDebug("Preparing for auto-shutdown because all downloads are complete!");
739 // Disabling it for next time
740 pref->setShutdownWhenDownloadsComplete(false);
741 pref->setSuspendWhenDownloadsComplete(false);
742 pref->setHibernateWhenDownloadsComplete(false);
743 // Make sure preferences are synced before exiting
744 m_shutdownAct = action;
747 qDebug("Exiting the application");
748 exit();
751 bool Application::callMainInstance()
753 return m_instanceManager->sendMessage(serializeParams(commandLineArgs()));
756 void Application::processParams(const QBtCommandLineParameters &params)
758 #ifndef DISABLE_GUI
759 // There are two circumstances in which we want to show the torrent
760 // dialog. One is when the application settings specify that it should
761 // be shown and skipTorrentDialog is undefined. The other is when
762 // skipTorrentDialog is false, meaning that the application setting
763 // should be overridden.
764 AddTorrentOption addTorrentOption = AddTorrentOption::Default;
765 if (params.skipDialog.has_value())
766 addTorrentOption = params.skipDialog.value() ? AddTorrentOption::SkipDialog : AddTorrentOption::ShowDialog;
767 for (const QString &torrentSource : params.torrentSources)
768 m_addTorrentManager->addTorrent(torrentSource, params.addTorrentParams, addTorrentOption);
769 #else
770 for (const QString &torrentSource : params.torrentSources)
771 m_addTorrentManager->addTorrent(torrentSource, params.addTorrentParams);
772 #endif
775 int Application::exec()
777 #if !defined(DISABLE_WEBUI) && defined(DISABLE_GUI)
778 const QString loadingStr = tr("WebUI will be started shortly after internal preparations. Please wait...");
779 printf("%s\n", qUtf8Printable(loadingStr));
780 #endif
782 #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
783 applyMemoryWorkingSetLimit();
784 #endif
786 #ifdef Q_OS_WIN
787 applyMemoryPriority();
788 adjustThreadPriority();
789 #endif
791 Net::ProxyConfigurationManager::initInstance();
792 Net::DownloadManager::initInstance();
793 IconProvider::initInstance();
795 BitTorrent::Session::initInstance();
796 #ifndef DISABLE_GUI
797 UIThemeManager::initInstance();
799 m_desktopIntegration = new DesktopIntegration;
800 m_desktopIntegration->setToolTip(tr("Loading torrents..."));
801 #ifndef Q_OS_MACOS
802 auto *desktopIntegrationMenu = new QMenu;
803 auto *actionExit = new QAction(tr("E&xit"), desktopIntegrationMenu);
804 actionExit->setIcon(UIThemeManager::instance()->getIcon(u"application-exit"_s));
805 actionExit->setMenuRole(QAction::QuitRole);
806 actionExit->setShortcut(Qt::CTRL | Qt::Key_Q);
807 connect(actionExit, &QAction::triggered, this, []
809 QApplication::exit();
811 desktopIntegrationMenu->addAction(actionExit);
813 m_desktopIntegration->setMenu(desktopIntegrationMenu);
815 const bool isHidden = m_desktopIntegration->isActive() && (startUpWindowState() == WindowState::Hidden);
816 #else
817 const bool isHidden = false;
818 #endif
820 if (!isHidden)
822 createStartupProgressDialog();
823 // Add a small delay to avoid "flashing" the progress dialog in case there are not many torrents to restore.
824 m_startupProgressDialog->setMinimumDuration(1000);
825 if (startUpWindowState() != WindowState::Normal)
826 m_startupProgressDialog->setWindowState(Qt::WindowMinimized);
828 else
830 connect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
832 #endif
833 connect(BitTorrent::Session::instance(), &BitTorrent::Session::restored, this, [this]()
835 connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentAdded, this, &Application::torrentAdded);
836 connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentFinished, this, &Application::torrentFinished);
837 connect(BitTorrent::Session::instance(), &BitTorrent::Session::allTorrentsFinished, this, &Application::allTorrentsFinished, Qt::QueuedConnection);
839 m_addTorrentManager = new AddTorrentManagerImpl(this, BitTorrent::Session::instance(), this);
841 Net::GeoIPManager::initInstance();
842 TorrentFilesWatcher::initInstance();
844 new RSS::Session; // create RSS::Session singleton
845 new RSS::AutoDownloader(this); // create RSS::AutoDownloader singleton
847 #ifndef DISABLE_GUI
848 const auto *btSession = BitTorrent::Session::instance();
849 connect(btSession, &BitTorrent::Session::fullDiskError, this
850 , [this](const BitTorrent::Torrent *torrent, const QString &msg)
852 m_desktopIntegration->showNotification(tr("I/O Error", "i.e: Input/Output Error")
853 , tr("An I/O error occurred for torrent '%1'.\n Reason: %2"
854 , "e.g: An error occurred for torrent 'xxx.avi'.\n Reason: disk is full.").arg(torrent->name(), msg));
856 connect(btSession, &BitTorrent::Session::torrentFinished, this
857 , [this](const BitTorrent::Torrent *torrent)
859 m_desktopIntegration->showNotification(tr("Download completed"), tr("'%1' has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(torrent->name()));
861 connect(m_addTorrentManager, &AddTorrentManager::torrentAdded, this
862 , [this]([[maybe_unused]] const QString &source, const BitTorrent::Torrent *torrent)
864 if (isTorrentAddedNotificationsEnabled())
865 m_desktopIntegration->showNotification(tr("Torrent added"), tr("'%1' was added.", "e.g: xxx.avi was added.").arg(torrent->name()));
867 connect(m_addTorrentManager, &AddTorrentManager::addTorrentFailed, this
868 , [this](const QString &source, const QString &reason)
870 m_desktopIntegration->showNotification(tr("Add torrent failed")
871 , tr("Couldn't add torrent '%1', reason: %2.").arg(source, reason));
874 disconnect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
875 #ifndef Q_OS_MACOS
876 const WindowState windowState = !m_startupProgressDialog ? WindowState::Hidden
877 : (m_startupProgressDialog->windowState() & Qt::WindowMinimized) ? WindowState::Minimized
878 : WindowState::Normal;
879 #else
880 const WindowState windowState = (m_startupProgressDialog->windowState() & Qt::WindowMinimized)
881 ? WindowState::Minimized : WindowState::Normal;
882 #endif
883 m_window = new MainWindow(this, windowState);
884 delete m_startupProgressDialog;
885 #endif // DISABLE_GUI
887 #ifndef DISABLE_WEBUI
888 m_webui = new WebUI(this);
889 #ifdef DISABLE_GUI
890 connect(m_webui, &WebUI::error, this, [](const QString &message) { fprintf(stderr, "%s\n", qUtf8Printable(message)); });
892 printf("%s", qUtf8Printable(u"\n******** %1 ********\n"_s.arg(tr("Information"))));
894 if (m_webui->isErrored())
896 const QString error = m_webui->errorMessage() + u'\n'
897 + tr("To fix the error, you may need to edit the config file manually.");
898 fprintf(stderr, "%s\n", qUtf8Printable(error));
900 else if (m_webui->isEnabled())
902 const QHostAddress address = m_webui->hostAddress();
903 const QString url = u"%1://%2:%3"_s.arg((m_webui->isHttps() ? u"https"_s : u"http"_s)
904 , (address.isEqual(QHostAddress::Any, QHostAddress::ConvertUnspecifiedAddress) ? u"localhost"_s : address.toString())
905 , QString::number(m_webui->port()));
906 printf("%s\n", qUtf8Printable(tr("To control qBittorrent, access the WebUI at: %1").arg(url)));
908 const Preferences *pref = Preferences::instance();
909 if (pref->getWebUIPassword() == QByteArrayLiteral("ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ=="))
911 const QString warning = tr("The Web UI administrator username is: %1").arg(pref->getWebUiUsername()) + u'\n'
912 + tr("The Web UI administrator password has not been changed from the default: %1").arg(u"adminadmin"_s) + u'\n'
913 + tr("This is a security risk, please change your password in program preferences.") + u'\n';
914 printf("%s", qUtf8Printable(warning));
917 else
919 printf("%s\n", qUtf8Printable(tr("The WebUI is disabled! To enable the WebUI, edit the config file manually.")));
921 #endif // DISABLE_GUI
922 #endif // DISABLE_WEBUI
924 m_isProcessingParamsAllowed = true;
925 for (const QBtCommandLineParameters &params : m_paramsQueue)
926 processParams(params);
927 m_paramsQueue.clear();
930 const QBtCommandLineParameters params = commandLineArgs();
931 if (!params.torrentSources.isEmpty())
932 m_paramsQueue.append(params);
934 return BaseApplication::exec();
937 bool Application::isRunning()
939 return !m_instanceManager->isFirstInstance();
942 #ifndef DISABLE_GUI
943 void Application::createStartupProgressDialog()
945 Q_ASSERT(!m_startupProgressDialog);
946 Q_ASSERT(m_desktopIntegration);
948 disconnect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
950 m_startupProgressDialog = new QProgressDialog(tr("Loading torrents..."), tr("Exit"), 0, 100);
951 m_startupProgressDialog->setAttribute(Qt::WA_DeleteOnClose);
952 m_startupProgressDialog->setWindowFlag(Qt::WindowMinimizeButtonHint);
953 m_startupProgressDialog->setMinimumDuration(0); // Show dialog immediately by default
954 m_startupProgressDialog->setAutoReset(false);
955 m_startupProgressDialog->setAutoClose(false);
957 connect(m_startupProgressDialog, &QProgressDialog::canceled, this, []()
959 QApplication::exit();
962 connect(BitTorrent::Session::instance(), &BitTorrent::Session::startupProgressUpdated, m_startupProgressDialog, &QProgressDialog::setValue);
964 connect(m_desktopIntegration, &DesktopIntegration::activationRequested, m_startupProgressDialog, [this]()
966 #ifdef Q_OS_MACOS
967 if (!m_startupProgressDialog->isVisible())
969 m_startupProgressDialog->show();
970 m_startupProgressDialog->activateWindow();
971 m_startupProgressDialog->raise();
973 #else
974 if (m_startupProgressDialog->isHidden())
976 // Make sure the window is not minimized
977 m_startupProgressDialog->setWindowState((m_startupProgressDialog->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
979 // Then show it
980 m_startupProgressDialog->show();
981 m_startupProgressDialog->raise();
982 m_startupProgressDialog->activateWindow();
984 else
986 m_startupProgressDialog->hide();
988 #endif
992 void Application::askRecursiveTorrentDownloadConfirmation(const BitTorrent::Torrent *torrent)
994 const auto torrentID = torrent->id();
996 QMessageBox *confirmBox = new QMessageBox(QMessageBox::Question, tr("Recursive download confirmation")
997 , tr("The torrent '%1' contains .torrent files, do you want to proceed with their downloads?").arg(torrent->name())
998 , (QMessageBox::Yes | QMessageBox::No | QMessageBox::NoToAll), mainWindow());
999 confirmBox->setAttribute(Qt::WA_DeleteOnClose);
1001 const QAbstractButton *yesButton = confirmBox->button(QMessageBox::Yes);
1002 QAbstractButton *neverButton = confirmBox->button(QMessageBox::NoToAll);
1003 neverButton->setText(tr("Never"));
1005 connect(confirmBox, &QMessageBox::buttonClicked, this
1006 , [this, torrentID, yesButton, neverButton](const QAbstractButton *button)
1008 if (button == yesButton)
1010 recursiveTorrentDownload(torrentID);
1012 else if (button == neverButton)
1014 Preferences::instance()->setRecursiveDownloadEnabled(false);
1017 confirmBox->open();
1020 void Application::recursiveTorrentDownload(const BitTorrent::TorrentID &torrentID)
1022 const BitTorrent::Torrent *torrent = BitTorrent::Session::instance()->getTorrent(torrentID);
1023 if (!torrent)
1024 return;
1026 for (const Path &torrentRelpath : asConst(torrent->filePaths()))
1028 if (torrentRelpath.hasExtension(u".torrent"_s))
1030 const Path torrentFullpath = torrent->savePath() / torrentRelpath;
1032 LogMsg(tr("Recursive download .torrent file within torrent. Source torrent: \"%1\". File: \"%2\"")
1033 .arg(torrent->name(), torrentFullpath.toString()));
1035 BitTorrent::AddTorrentParams params;
1036 // Passing the save path along to the sub torrent file
1037 params.savePath = torrent->savePath();
1038 addTorrentManager()->addTorrent(torrentFullpath.data(), params, AddTorrentOption::SkipDialog);
1043 #ifdef Q_OS_MACOS
1044 bool Application::event(QEvent *ev)
1046 if (ev->type() == QEvent::FileOpen)
1048 QString path = static_cast<QFileOpenEvent *>(ev)->file();
1049 if (path.isEmpty())
1050 // Get the url instead
1051 path = static_cast<QFileOpenEvent *>(ev)->url().toString();
1052 qDebug("Received a mac file open event: %s", qUtf8Printable(path));
1054 QBtCommandLineParameters params;
1055 params.torrentSources.append(path);
1056 // If Application is not allowed to process params immediately
1057 // (i.e., other components are not ready) store params
1058 if (m_isProcessingParamsAllowed)
1059 processParams(params);
1060 else
1061 m_paramsQueue.append(params);
1063 return true;
1066 return BaseApplication::event(ev);
1068 #endif // Q_OS_MACOS
1069 #endif // DISABLE_GUI
1071 void Application::initializeTranslation()
1073 Preferences *const pref = Preferences::instance();
1074 // Load translation
1075 const QString localeStr = pref->getLocale();
1077 if (m_qtTranslator.load((u"qtbase_" + localeStr), QLibraryInfo::path(QLibraryInfo::TranslationsPath))
1078 || m_qtTranslator.load((u"qt_" + localeStr), QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
1080 qDebug("Qt %s locale recognized, using translation.", qUtf8Printable(localeStr));
1082 else
1084 qDebug("Qt %s locale unrecognized, using default (en).", qUtf8Printable(localeStr));
1087 installTranslator(&m_qtTranslator);
1089 if (m_translator.load(u":/lang/qbittorrent_" + localeStr))
1090 qDebug("%s locale recognized, using translation.", qUtf8Printable(localeStr));
1091 else
1092 qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(localeStr));
1093 installTranslator(&m_translator);
1095 #ifndef DISABLE_GUI
1096 if (localeStr.startsWith(u"ar") || localeStr.startsWith(u"he"))
1098 qDebug("Right to Left mode");
1099 setLayoutDirection(Qt::RightToLeft);
1101 else
1103 setLayoutDirection(Qt::LeftToRight);
1105 #endif
1108 #if (!defined(DISABLE_GUI) && defined(Q_OS_WIN))
1109 void Application::shutdownCleanup([[maybe_unused]] QSessionManager &manager)
1111 // This is only needed for a special case on Windows XP.
1112 // (but is called for every Windows version)
1113 // If a process takes too much time to exit during OS
1114 // shutdown, the OS presents a dialog to the user.
1115 // That dialog tells the user that qbt is blocking the
1116 // shutdown, it shows a progress bar and it offers
1117 // a "Terminate Now" button for the user. However,
1118 // after the progress bar has reached 100% another button
1119 // is offered to the user reading "Cancel". With this the
1120 // user can cancel the **OS** shutdown. If we don't do
1121 // the cleanup by handling the commitDataRequest() signal
1122 // and the user clicks "Cancel", it will result in qbt being
1123 // killed and the shutdown proceeding instead. Apparently
1124 // aboutToQuit() is emitted too late in the shutdown process.
1125 cleanup();
1127 // According to the qt docs we shouldn't call quit() inside a slot.
1128 // aboutToQuit() is never emitted if the user hits "Cancel" in
1129 // the above dialog.
1130 QMetaObject::invokeMethod(qApp, &QCoreApplication::quit, Qt::QueuedConnection);
1132 #endif
1134 #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
1135 void Application::applyMemoryWorkingSetLimit() const
1137 const size_t MiB = 1024 * 1024;
1138 const QString logMessage = tr("Failed to set physical memory (RAM) usage limit. Error code: %1. Error message: \"%2\"");
1140 #ifdef Q_OS_WIN
1141 const SIZE_T maxSize = memoryWorkingSetLimit() * MiB;
1142 const auto minSize = std::min<SIZE_T>((64 * MiB), (maxSize / 2));
1143 if (!::SetProcessWorkingSetSizeEx(::GetCurrentProcess(), minSize, maxSize, QUOTA_LIMITS_HARDWS_MAX_ENABLE))
1145 const DWORD errorCode = ::GetLastError();
1146 QString message;
1147 LPVOID lpMsgBuf = nullptr;
1148 const DWORD msgLength = ::FormatMessageW((FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS)
1149 , nullptr, errorCode, LANG_USER_DEFAULT, reinterpret_cast<LPWSTR>(&lpMsgBuf), 0, nullptr);
1150 if (msgLength > 0)
1152 message = QString::fromWCharArray(reinterpret_cast<LPWSTR>(lpMsgBuf)).trimmed();
1153 ::LocalFree(lpMsgBuf);
1155 LogMsg(logMessage.arg(QString::number(errorCode), message), Log::WARNING);
1157 #elif defined(Q_OS_UNIX)
1158 // has no effect on linux but it might be meaningful for other OS
1159 rlimit limit {};
1161 if (::getrlimit(RLIMIT_RSS, &limit) != 0)
1162 return;
1164 const size_t newSize = memoryWorkingSetLimit() * MiB;
1165 if (newSize > limit.rlim_max)
1167 // try to raise the hard limit
1168 rlimit newLimit = limit;
1169 newLimit.rlim_max = newSize;
1170 if (::setrlimit(RLIMIT_RSS, &newLimit) != 0)
1172 const auto message = QString::fromLocal8Bit(strerror(errno));
1173 LogMsg(tr("Failed to set physical memory (RAM) usage hard limit. Requested size: %1. System hard limit: %2. Error code: %3. Error message: \"%4\"")
1174 .arg(QString::number(newSize), QString::number(limit.rlim_max), QString::number(errno), message), Log::WARNING);
1175 return;
1179 limit.rlim_cur = newSize;
1180 if (::setrlimit(RLIMIT_RSS, &limit) != 0)
1182 const auto message = QString::fromLocal8Bit(strerror(errno));
1183 LogMsg(logMessage.arg(QString::number(errno), message), Log::WARNING);
1185 #endif
1187 #endif
1189 #ifdef Q_OS_WIN
1190 MemoryPriority Application::processMemoryPriority() const
1192 return m_processMemoryPriority.get(MemoryPriority::BelowNormal);
1195 void Application::setProcessMemoryPriority(const MemoryPriority priority)
1197 if (processMemoryPriority() == priority)
1198 return;
1200 m_processMemoryPriority = priority;
1201 applyMemoryPriority();
1204 void Application::applyMemoryPriority() const
1206 using SETPROCESSINFORMATION = BOOL (WINAPI *)(HANDLE, PROCESS_INFORMATION_CLASS, LPVOID, DWORD);
1207 const auto setProcessInformation = Utils::OS::loadWinAPI<SETPROCESSINFORMATION>(u"Kernel32.dll"_s, "SetProcessInformation");
1208 if (!setProcessInformation) // only available on Windows >= 8
1209 return;
1211 using SETTHREADINFORMATION = BOOL (WINAPI *)(HANDLE, THREAD_INFORMATION_CLASS, LPVOID, DWORD);
1212 const auto setThreadInformation = Utils::OS::loadWinAPI<SETTHREADINFORMATION>(u"Kernel32.dll"_s, "SetThreadInformation");
1213 if (!setThreadInformation) // only available on Windows >= 8
1214 return;
1216 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
1217 // this dummy struct is required to compile successfully when targeting older Windows version
1218 struct MEMORY_PRIORITY_INFORMATION
1220 ULONG MemoryPriority;
1223 #define MEMORY_PRIORITY_LOWEST 0
1224 #define MEMORY_PRIORITY_VERY_LOW 1
1225 #define MEMORY_PRIORITY_LOW 2
1226 #define MEMORY_PRIORITY_MEDIUM 3
1227 #define MEMORY_PRIORITY_BELOW_NORMAL 4
1228 #define MEMORY_PRIORITY_NORMAL 5
1229 #endif
1231 MEMORY_PRIORITY_INFORMATION prioInfo {};
1232 switch (processMemoryPriority())
1234 case MemoryPriority::Normal:
1235 default:
1236 prioInfo.MemoryPriority = MEMORY_PRIORITY_NORMAL;
1237 break;
1238 case MemoryPriority::BelowNormal:
1239 prioInfo.MemoryPriority = MEMORY_PRIORITY_BELOW_NORMAL;
1240 break;
1241 case MemoryPriority::Medium:
1242 prioInfo.MemoryPriority = MEMORY_PRIORITY_MEDIUM;
1243 break;
1244 case MemoryPriority::Low:
1245 prioInfo.MemoryPriority = MEMORY_PRIORITY_LOW;
1246 break;
1247 case MemoryPriority::VeryLow:
1248 prioInfo.MemoryPriority = MEMORY_PRIORITY_VERY_LOW;
1249 break;
1251 setProcessInformation(::GetCurrentProcess(), ProcessMemoryPriority, &prioInfo, sizeof(prioInfo));
1253 // To avoid thrashing/sluggishness of the app, set "main event loop" thread to normal memory priority
1254 // which is higher/equal than other threads
1255 prioInfo.MemoryPriority = MEMORY_PRIORITY_NORMAL;
1256 setThreadInformation(::GetCurrentThread(), ThreadMemoryPriority, &prioInfo, sizeof(prioInfo));
1259 void Application::adjustThreadPriority() const
1261 // Workaround for improving responsiveness of qbt when CPU resources are scarce.
1262 // Raise main event loop thread to be just one level higher than libtorrent threads.
1263 // Also note that on *nix platforms there is no easy way to achieve it,
1264 // so implementation is omitted.
1266 ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
1268 #endif
1270 void Application::cleanup()
1272 // cleanup() can be called multiple times during shutdown. We only need it once.
1273 if (m_isCleanupRun.exchange(true, std::memory_order_acquire))
1274 return;
1276 LogMsg(tr("qBittorrent termination initiated"));
1278 #ifndef DISABLE_GUI
1279 if (m_desktopIntegration)
1281 m_desktopIntegration->disconnect();
1282 m_desktopIntegration->setToolTip(tr("qBittorrent is shutting down..."));
1283 if (m_desktopIntegration->menu())
1284 m_desktopIntegration->menu()->setEnabled(false);
1287 if (m_window)
1289 // Hide the window and don't leave it on screen as
1290 // unresponsive. Also for Windows take the WinId
1291 // after it's hidden, because hide() may cause a
1292 // WinId change.
1293 m_window->hide();
1295 #ifdef Q_OS_WIN
1296 const std::wstring msg = tr("Saving torrent progress...").toStdWString();
1297 ::ShutdownBlockReasonCreate(reinterpret_cast<HWND>(m_window->effectiveWinId())
1298 , msg.c_str());
1299 #endif // Q_OS_WIN
1301 // Do manual cleanup in MainWindow to force widgets
1302 // to save their Preferences, stop all timers and
1303 // delete as many widgets as possible to leave only
1304 // a 'shell' MainWindow.
1305 // We need a valid window handle for Windows Vista+
1306 // otherwise the system shutdown will continue even
1307 // though we created a ShutdownBlockReason
1308 m_window->cleanup();
1310 #endif // DISABLE_GUI
1312 #ifndef DISABLE_WEBUI
1313 delete m_webui;
1314 #endif
1316 delete RSS::AutoDownloader::instance();
1317 delete RSS::Session::instance();
1319 TorrentFilesWatcher::freeInstance();
1320 delete m_addTorrentManager;
1321 BitTorrent::Session::freeInstance();
1322 Net::GeoIPManager::freeInstance();
1323 Net::DownloadManager::freeInstance();
1324 Net::ProxyConfigurationManager::freeInstance();
1325 Preferences::freeInstance();
1326 SettingsStorage::freeInstance();
1327 IconProvider::freeInstance();
1328 SearchPluginManager::freeInstance();
1329 Utils::Fs::removeDirRecursively(Utils::Fs::tempPath());
1331 LogMsg(tr("qBittorrent is now ready to exit"));
1332 Logger::freeInstance();
1333 delete m_fileLogger;
1335 #ifndef DISABLE_GUI
1336 if (m_window)
1338 #ifdef Q_OS_WIN
1339 ::ShutdownBlockReasonDestroy(reinterpret_cast<HWND>(m_window->effectiveWinId()));
1340 #endif // Q_OS_WIN
1341 delete m_window;
1342 delete m_desktopIntegration;
1343 UIThemeManager::freeInstance();
1345 #endif // DISABLE_GUI
1347 Profile::freeInstance();
1349 if (m_shutdownAct != ShutdownDialogAction::Exit)
1351 qDebug() << "Sending computer shutdown/suspend/hibernate signal...";
1352 Utils::OS::shutdownComputer(m_shutdownAct);
1356 AddTorrentManagerImpl *Application::addTorrentManager() const
1358 return m_addTorrentManager;