Don't forget to delete TorrentContentAdaptor instance
[qBittorrent.git] / src / app / application.cpp
blob1b98f7b80e28c94c39870f8e81b811a2747fa25b
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/string.h"
89 #include "base/version.h"
90 #include "applicationinstancemanager.h"
91 #include "filelogger.h"
92 #include "upgrade.h"
94 #ifndef DISABLE_GUI
95 #include "gui/guiaddtorrentmanager.h"
96 #include "gui/desktopintegration.h"
97 #include "gui/mainwindow.h"
98 #include "gui/shutdownconfirmdialog.h"
99 #include "gui/uithememanager.h"
100 #include "gui/utils.h"
101 #include "gui/windowstate.h"
103 #ifdef Q_OS_WIN
104 #include "base/utils/os.h"
105 #endif // Q_OS_WIN
106 #endif // DISABLE_GUI
108 #ifndef DISABLE_WEBUI
109 #include "webui/webui.h"
110 #endif
112 namespace
114 #define SETTINGS_KEY(name) u"Application/" name
115 #define FILELOGGER_SETTINGS_KEY(name) (SETTINGS_KEY(u"FileLogger/") name)
116 #define NOTIFICATIONS_SETTINGS_KEY(name) (SETTINGS_KEY(u"GUI/Notifications/"_s) name)
118 const QString LOG_FOLDER = u"logs"_s;
119 const QChar PARAMS_SEPARATOR = u'|';
121 const Path DEFAULT_PORTABLE_MODE_PROFILE_DIR {u"profile"_s};
123 const int MIN_FILELOG_SIZE = 1024; // 1KiB
124 const int MAX_FILELOG_SIZE = 1000 * 1024 * 1024; // 1000MiB
125 const int DEFAULT_FILELOG_SIZE = 65 * 1024; // 65KiB
127 #ifndef DISABLE_GUI
128 const int PIXMAP_CACHE_SIZE = 64 * 1024 * 1024; // 64MiB
129 #endif
131 QString serializeParams(const QBtCommandLineParameters &params)
133 QStringList result;
134 // Because we're passing a string list to the currently running
135 // qBittorrent process, we need some way of passing along the options
136 // the user has specified. Here we place special strings that are
137 // almost certainly not going to collide with a file path or URL
138 // specified by the user, and placing them at the beginning of the
139 // string list so that they will be processed before the list of
140 // torrent paths or URLs.
142 const BitTorrent::AddTorrentParams &addTorrentParams = params.addTorrentParams;
144 if (!addTorrentParams.savePath.isEmpty())
145 result.append(u"@savePath=" + addTorrentParams.savePath.data());
147 if (addTorrentParams.addPaused.has_value())
148 result.append(*addTorrentParams.addPaused ? u"@addPaused=1"_s : u"@addPaused=0"_s);
150 if (addTorrentParams.skipChecking)
151 result.append(u"@skipChecking"_s);
153 if (!addTorrentParams.category.isEmpty())
154 result.append(u"@category=" + addTorrentParams.category);
156 if (addTorrentParams.sequential)
157 result.append(u"@sequential"_s);
159 if (addTorrentParams.firstLastPiecePriority)
160 result.append(u"@firstLastPiecePriority"_s);
162 if (params.skipDialog.has_value())
163 result.append(*params.skipDialog ? u"@skipDialog=1"_s : u"@skipDialog=0"_s);
165 result += params.torrentSources;
167 return result.join(PARAMS_SEPARATOR);
170 QBtCommandLineParameters parseParams(const QString &str)
172 QBtCommandLineParameters parsedParams;
173 BitTorrent::AddTorrentParams &addTorrentParams = parsedParams.addTorrentParams;
175 for (QString param : asConst(str.split(PARAMS_SEPARATOR, Qt::SkipEmptyParts)))
177 param = param.trimmed();
179 // Process strings indicating options specified by the user.
181 if (param.startsWith(u"@savePath="))
183 addTorrentParams.savePath = Path(param.mid(10));
184 continue;
187 if (param.startsWith(u"@addPaused="))
189 addTorrentParams.addPaused = (QStringView(param).mid(11).toInt() != 0);
190 continue;
193 if (param == u"@skipChecking")
195 addTorrentParams.skipChecking = true;
196 continue;
199 if (param.startsWith(u"@category="))
201 addTorrentParams.category = param.mid(10);
202 continue;
205 if (param == u"@sequential")
207 addTorrentParams.sequential = true;
208 continue;
211 if (param == u"@firstLastPiecePriority")
213 addTorrentParams.firstLastPiecePriority = true;
214 continue;
217 if (param.startsWith(u"@skipDialog="))
219 parsedParams.skipDialog = (QStringView(param).mid(12).toInt() != 0);
220 continue;
223 parsedParams.torrentSources.append(param);
226 return parsedParams;
230 Application::Application(int &argc, char **argv)
231 : BaseApplication(argc, argv)
232 , m_commandLineArgs(parseCommandLine(Application::arguments()))
233 , m_storeFileLoggerEnabled(FILELOGGER_SETTINGS_KEY(u"Enabled"_s))
234 , m_storeFileLoggerBackup(FILELOGGER_SETTINGS_KEY(u"Backup"_s))
235 , m_storeFileLoggerDeleteOld(FILELOGGER_SETTINGS_KEY(u"DeleteOld"_s))
236 , m_storeFileLoggerMaxSize(FILELOGGER_SETTINGS_KEY(u"MaxSizeBytes"_s))
237 , m_storeFileLoggerAge(FILELOGGER_SETTINGS_KEY(u"Age"_s))
238 , m_storeFileLoggerAgeType(FILELOGGER_SETTINGS_KEY(u"AgeType"_s))
239 , m_storeFileLoggerPath(FILELOGGER_SETTINGS_KEY(u"Path"_s))
240 , m_storeMemoryWorkingSetLimit(SETTINGS_KEY(u"MemoryWorkingSetLimit"_s))
241 #ifdef Q_OS_WIN
242 , m_processMemoryPriority(SETTINGS_KEY(u"ProcessMemoryPriority"_s))
243 #endif
244 #ifndef DISABLE_GUI
245 , m_startUpWindowState(u"GUI/StartUpWindowState"_s)
246 , m_storeNotificationTorrentAdded(NOTIFICATIONS_SETTINGS_KEY(u"TorrentAdded"_s))
247 #endif
249 qRegisterMetaType<Log::Msg>("Log::Msg");
250 qRegisterMetaType<Log::Peer>("Log::Peer");
252 setApplicationName(u"qBittorrent"_s);
253 setOrganizationDomain(u"qbittorrent.org"_s);
254 #if !defined(DISABLE_GUI)
255 setDesktopFileName(u"org.qbittorrent.qBittorrent"_s);
256 setQuitOnLastWindowClosed(false);
257 QPixmapCache::setCacheLimit(PIXMAP_CACHE_SIZE);
258 #endif
260 Logger::initInstance();
262 const auto portableProfilePath = Path(QCoreApplication::applicationDirPath()) / DEFAULT_PORTABLE_MODE_PROFILE_DIR;
263 const bool portableModeEnabled = m_commandLineArgs.profileDir.isEmpty() && portableProfilePath.exists();
265 const Path profileDir = portableModeEnabled
266 ? portableProfilePath
267 : m_commandLineArgs.profileDir;
268 Profile::initInstance(profileDir, m_commandLineArgs.configurationName,
269 (m_commandLineArgs.relativeFastresumePaths || portableModeEnabled));
271 m_instanceManager = new ApplicationInstanceManager(Profile::instance()->location(SpecialFolder::Config), this);
273 SettingsStorage::initInstance();
274 Preferences::initInstance();
276 const bool firstTimeUser = !Preferences::instance()->getAcceptedLegal();
277 if (!firstTimeUser)
279 if (!upgrade())
280 throw RuntimeError(u"Failed migration of old settings"_s); // Not translatable. Translation isn't configured yet.
281 handleChangedDefaults(DefaultPreferencesMode::Legacy);
283 else
285 handleChangedDefaults(DefaultPreferencesMode::Current);
288 initializeTranslation();
290 connect(this, &QCoreApplication::aboutToQuit, this, &Application::cleanup);
291 connect(m_instanceManager, &ApplicationInstanceManager::messageReceived, this, &Application::processMessage);
292 #if defined(Q_OS_WIN) && !defined(DISABLE_GUI)
293 connect(this, &QGuiApplication::commitDataRequest, this, &Application::shutdownCleanup, Qt::DirectConnection);
294 #endif
296 LogMsg(tr("qBittorrent %1 started", "qBittorrent v3.2.0alpha started").arg(QStringLiteral(QBT_VERSION)));
297 if (portableModeEnabled)
299 LogMsg(tr("Running in portable mode. Auto detected profile folder at: %1").arg(profileDir.toString()));
300 if (m_commandLineArgs.relativeFastresumePaths)
301 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
303 else
305 LogMsg(tr("Using config directory: %1").arg(Profile::instance()->location(SpecialFolder::Config).toString()));
308 if (isFileLoggerEnabled())
309 m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
311 if (m_commandLineArgs.webUiPort > 0) // it will be -1 when user did not set any value
312 Preferences::instance()->setWebUiPort(m_commandLineArgs.webUiPort);
314 if (m_commandLineArgs.torrentingPort > 0) // it will be -1 when user did not set any value
316 SettingValue<int> port {u"BitTorrent/Session/Port"_s};
317 port = m_commandLineArgs.torrentingPort;
321 Application::~Application()
323 // we still need to call cleanup()
324 // in case the App failed to start
325 cleanup();
328 #ifndef DISABLE_GUI
329 DesktopIntegration *Application::desktopIntegration()
331 return m_desktopIntegration;
334 MainWindow *Application::mainWindow()
336 return m_window;
339 WindowState Application::startUpWindowState() const
341 return m_startUpWindowState;
344 void Application::setStartUpWindowState(const WindowState windowState)
346 m_startUpWindowState = windowState;
349 bool Application::isTorrentAddedNotificationsEnabled() const
351 return m_storeNotificationTorrentAdded;
354 void Application::setTorrentAddedNotificationsEnabled(const bool value)
356 m_storeNotificationTorrentAdded = value;
358 #endif
360 const QBtCommandLineParameters &Application::commandLineArgs() const
362 return m_commandLineArgs;
365 int Application::memoryWorkingSetLimit() const
367 return m_storeMemoryWorkingSetLimit.get(512);
370 void Application::setMemoryWorkingSetLimit(const int size)
372 if (size == memoryWorkingSetLimit())
373 return;
375 m_storeMemoryWorkingSetLimit = size;
376 #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
377 applyMemoryWorkingSetLimit();
378 #endif
381 bool Application::isFileLoggerEnabled() const
383 return m_storeFileLoggerEnabled.get(true);
386 void Application::setFileLoggerEnabled(const bool value)
388 if (value && !m_fileLogger)
389 m_fileLogger = new FileLogger(fileLoggerPath(), isFileLoggerBackup(), fileLoggerMaxSize(), isFileLoggerDeleteOld(), fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
390 else if (!value)
391 delete m_fileLogger;
392 m_storeFileLoggerEnabled = value;
395 Path Application::fileLoggerPath() const
397 return m_storeFileLoggerPath.get(specialFolderLocation(SpecialFolder::Data) / Path(LOG_FOLDER));
400 void Application::setFileLoggerPath(const Path &path)
402 if (m_fileLogger)
403 m_fileLogger->changePath(path);
404 m_storeFileLoggerPath = path;
407 bool Application::isFileLoggerBackup() const
409 return m_storeFileLoggerBackup.get(true);
412 void Application::setFileLoggerBackup(const bool value)
414 if (m_fileLogger)
415 m_fileLogger->setBackup(value);
416 m_storeFileLoggerBackup = value;
419 bool Application::isFileLoggerDeleteOld() const
421 return m_storeFileLoggerDeleteOld.get(true);
424 void Application::setFileLoggerDeleteOld(const bool value)
426 if (value && m_fileLogger)
427 m_fileLogger->deleteOld(fileLoggerAge(), static_cast<FileLogger::FileLogAgeType>(fileLoggerAgeType()));
428 m_storeFileLoggerDeleteOld = value;
431 int Application::fileLoggerMaxSize() const
433 const int val = m_storeFileLoggerMaxSize.get(DEFAULT_FILELOG_SIZE);
434 return std::clamp(val, MIN_FILELOG_SIZE, MAX_FILELOG_SIZE);
437 void Application::setFileLoggerMaxSize(const int bytes)
439 const int clampedValue = std::clamp(bytes, MIN_FILELOG_SIZE, MAX_FILELOG_SIZE);
440 if (m_fileLogger)
441 m_fileLogger->setMaxSize(clampedValue);
442 m_storeFileLoggerMaxSize = clampedValue;
445 int Application::fileLoggerAge() const
447 const int val = m_storeFileLoggerAge.get(1);
448 return std::clamp(val, 1, 365);
451 void Application::setFileLoggerAge(const int value)
453 m_storeFileLoggerAge = std::clamp(value, 1, 365);
456 int Application::fileLoggerAgeType() const
458 const int val = m_storeFileLoggerAgeType.get(1);
459 return ((val < 0) || (val > 2)) ? 1 : val;
462 void Application::setFileLoggerAgeType(const int value)
464 m_storeFileLoggerAgeType = ((value < 0) || (value > 2)) ? 1 : value;
467 void Application::processMessage(const QString &message)
469 #ifndef DISABLE_GUI
470 if (message.isEmpty())
472 if (BitTorrent::Session::instance()->isRestored()) [[likely]]
474 m_window->activate(); // show UI
476 else if (m_startupProgressDialog)
478 m_startupProgressDialog->show();
479 m_startupProgressDialog->activateWindow();
480 m_startupProgressDialog->raise();
482 else
484 createStartupProgressDialog();
487 return;
489 #endif
491 const QBtCommandLineParameters params = parseParams(message);
492 // If Application is not allowed to process params immediately
493 // (i.e., other components are not ready) store params
494 if (m_isProcessingParamsAllowed)
495 processParams(params);
496 else
497 m_paramsQueue.append(params);
500 void Application::runExternalProgram(const QString &programTemplate, const BitTorrent::Torrent *torrent) const
502 // Cannot give users shell environment by default, as doing so could
503 // enable command injection via torrent name and other arguments
504 // (especially when some automated download mechanism has been setup).
505 // See: https://github.com/qbittorrent/qBittorrent/issues/10925
507 const auto replaceVariables = [torrent](QString str) -> QString
509 for (int i = (str.length() - 2); i >= 0; --i)
511 if (str[i] != u'%')
512 continue;
514 const ushort specifier = str[i + 1].unicode();
515 switch (specifier)
517 case u'C':
518 str.replace(i, 2, QString::number(torrent->filesCount()));
519 break;
520 case u'D':
521 str.replace(i, 2, torrent->savePath().toString());
522 break;
523 case u'F':
524 str.replace(i, 2, torrent->contentPath().toString());
525 break;
526 case u'G':
527 str.replace(i, 2, torrent->tags().join(u","_s));
528 break;
529 case u'I':
530 str.replace(i, 2, (torrent->infoHash().v1().isValid() ? torrent->infoHash().v1().toString() : u"-"_s));
531 break;
532 case u'J':
533 str.replace(i, 2, (torrent->infoHash().v2().isValid() ? torrent->infoHash().v2().toString() : u"-"_s));
534 break;
535 case u'K':
536 str.replace(i, 2, torrent->id().toString());
537 break;
538 case u'L':
539 str.replace(i, 2, torrent->category());
540 break;
541 case u'N':
542 str.replace(i, 2, torrent->name());
543 break;
544 case u'R':
545 str.replace(i, 2, torrent->rootPath().toString());
546 break;
547 case u'T':
548 str.replace(i, 2, torrent->currentTracker());
549 break;
550 case u'Z':
551 str.replace(i, 2, QString::number(torrent->totalSize()));
552 break;
553 default:
554 // do nothing
555 break;
558 // decrement `i` to avoid unwanted replacement, example pattern: "%%N"
559 --i;
562 return str;
565 const QString logMsg = tr("Running external program. Torrent: \"%1\". Command: `%2`");
566 const QString logMsgError = tr("Failed to run external program. Torrent: \"%1\". Command: `%2`");
568 // The processing sequenece is different for Windows and other OS, this is intentional
569 #if defined(Q_OS_WIN)
570 const QString program = replaceVariables(programTemplate);
571 const std::wstring programWStr = program.toStdWString();
573 // Need to split arguments manually because QProcess::startDetached(QString)
574 // will strip off empty parameters.
575 // E.g. `python.exe "1" "" "3"` will become `python.exe "1" "3"`
576 int argCount = 0;
577 std::unique_ptr<LPWSTR[], decltype(&::LocalFree)> args {::CommandLineToArgvW(programWStr.c_str(), &argCount), ::LocalFree};
579 if (argCount <= 0)
580 return;
582 QStringList argList;
583 for (int i = 1; i < argCount; ++i)
584 argList += QString::fromWCharArray(args[i]);
586 QProcess proc;
587 proc.setProgram(QString::fromWCharArray(args[0]));
588 proc.setArguments(argList);
589 proc.setCreateProcessArgumentsModifier([](QProcess::CreateProcessArguments *args)
591 if (Preferences::instance()->isAutoRunConsoleEnabled())
593 args->flags |= CREATE_NEW_CONSOLE;
594 args->flags &= ~(CREATE_NO_WINDOW | DETACHED_PROCESS);
596 else
598 args->flags |= CREATE_NO_WINDOW;
599 args->flags &= ~(CREATE_NEW_CONSOLE | DETACHED_PROCESS);
601 args->inheritHandles = false;
602 args->startupInfo->dwFlags &= ~STARTF_USESTDHANDLES;
603 ::CloseHandle(args->startupInfo->hStdInput);
604 ::CloseHandle(args->startupInfo->hStdOutput);
605 ::CloseHandle(args->startupInfo->hStdError);
606 args->startupInfo->hStdInput = nullptr;
607 args->startupInfo->hStdOutput = nullptr;
608 args->startupInfo->hStdError = nullptr;
611 if (proc.startDetached())
612 LogMsg(logMsg.arg(torrent->name(), program));
613 else
614 LogMsg(logMsgError.arg(torrent->name(), program));
615 #else // Q_OS_WIN
616 QStringList args = Utils::String::splitCommand(programTemplate);
618 if (args.isEmpty())
619 return;
621 for (QString &arg : args)
623 // strip redundant quotes
624 if (arg.startsWith(u'"') && arg.endsWith(u'"'))
625 arg = arg.mid(1, (arg.size() - 2));
627 arg = replaceVariables(arg);
630 const QString command = args.takeFirst();
631 QProcess proc;
632 proc.setProgram(command);
633 proc.setArguments(args);
635 if (proc.startDetached())
637 // show intended command in log
638 LogMsg(logMsg.arg(torrent->name(), replaceVariables(programTemplate)));
640 else
642 // show intended command in log
643 LogMsg(logMsgError.arg(torrent->name(), replaceVariables(programTemplate)));
645 #endif
648 void Application::sendNotificationEmail(const BitTorrent::Torrent *torrent)
650 // Prepare mail content
651 const QString content = tr("Torrent name: %1").arg(torrent->name()) + u'\n'
652 + tr("Torrent size: %1").arg(Utils::Misc::friendlyUnit(torrent->wantedSize())) + u'\n'
653 + tr("Save path: %1").arg(torrent->savePath().toString()) + u"\n\n"
654 + tr("The torrent was downloaded in %1.", "The torrent was downloaded in 1 hour and 20 seconds")
655 .arg(Utils::Misc::userFriendlyDuration(torrent->activeTime())) + u"\n\n\n"
656 + tr("Thank you for using qBittorrent.") + u'\n';
658 // Send the notification email
659 const Preferences *pref = Preferences::instance();
660 auto *smtp = new Net::Smtp(this);
661 smtp->sendMail(pref->getMailNotificationSender(),
662 pref->getMailNotificationEmail(),
663 tr("Torrent \"%1\" has finished downloading").arg(torrent->name()),
664 content);
667 void Application::torrentAdded(const BitTorrent::Torrent *torrent) const
669 const Preferences *pref = Preferences::instance();
671 // AutoRun program
672 if (pref->isAutoRunOnTorrentAddedEnabled())
673 runExternalProgram(pref->getAutoRunOnTorrentAddedProgram().trimmed(), torrent);
676 void Application::torrentFinished(const BitTorrent::Torrent *torrent)
678 const Preferences *pref = Preferences::instance();
680 // AutoRun program
681 if (pref->isAutoRunOnTorrentFinishedEnabled())
682 runExternalProgram(pref->getAutoRunOnTorrentFinishedProgram().trimmed(), torrent);
684 // Mail notification
685 if (pref->isMailNotificationEnabled())
687 LogMsg(tr("Torrent: %1, sending mail notification").arg(torrent->name()));
688 sendNotificationEmail(torrent);
691 #ifndef DISABLE_GUI
692 if (Preferences::instance()->isRecursiveDownloadEnabled())
694 // Check whether it contains .torrent files
695 for (const Path &torrentRelpath : asConst(torrent->filePaths()))
697 if (torrentRelpath.hasExtension(u".torrent"_s))
699 askRecursiveTorrentDownloadConfirmation(torrent);
700 break;
704 #endif
707 void Application::allTorrentsFinished()
709 Preferences *const pref = Preferences::instance();
710 bool isExit = pref->shutdownqBTWhenDownloadsComplete();
711 bool isShutdown = pref->shutdownWhenDownloadsComplete();
712 bool isSuspend = pref->suspendWhenDownloadsComplete();
713 bool isHibernate = pref->hibernateWhenDownloadsComplete();
715 bool haveAction = isExit || isShutdown || isSuspend || isHibernate;
716 if (!haveAction) return;
718 ShutdownDialogAction action = ShutdownDialogAction::Exit;
719 if (isSuspend)
720 action = ShutdownDialogAction::Suspend;
721 else if (isHibernate)
722 action = ShutdownDialogAction::Hibernate;
723 else if (isShutdown)
724 action = ShutdownDialogAction::Shutdown;
726 #ifndef DISABLE_GUI
727 // ask confirm
728 if ((action == ShutdownDialogAction::Exit) && (pref->dontConfirmAutoExit()))
730 // do nothing & skip confirm
732 else
734 if (!ShutdownConfirmDialog::askForConfirmation(m_window, action)) return;
736 #endif // DISABLE_GUI
738 // Actually shut down
739 if (action != ShutdownDialogAction::Exit)
741 qDebug("Preparing for auto-shutdown because all downloads are complete!");
742 // Disabling it for next time
743 pref->setShutdownWhenDownloadsComplete(false);
744 pref->setSuspendWhenDownloadsComplete(false);
745 pref->setHibernateWhenDownloadsComplete(false);
746 // Make sure preferences are synced before exiting
747 m_shutdownAct = action;
750 qDebug("Exiting the application");
751 exit();
754 bool Application::callMainInstance()
756 return m_instanceManager->sendMessage(serializeParams(commandLineArgs()));
759 void Application::processParams(const QBtCommandLineParameters &params)
761 #ifndef DISABLE_GUI
762 // There are two circumstances in which we want to show the torrent
763 // dialog. One is when the application settings specify that it should
764 // be shown and skipTorrentDialog is undefined. The other is when
765 // skipTorrentDialog is false, meaning that the application setting
766 // should be overridden.
767 AddTorrentOption addTorrentOption = AddTorrentOption::Default;
768 if (params.skipDialog.has_value())
769 addTorrentOption = params.skipDialog.value() ? AddTorrentOption::SkipDialog : AddTorrentOption::ShowDialog;
770 for (const QString &torrentSource : params.torrentSources)
771 m_addTorrentManager->addTorrent(torrentSource, params.addTorrentParams, addTorrentOption);
772 #else
773 for (const QString &torrentSource : params.torrentSources)
774 m_addTorrentManager->addTorrent(torrentSource, params.addTorrentParams);
775 #endif
778 int Application::exec()
780 #if !defined(DISABLE_WEBUI) && defined(DISABLE_GUI)
781 const QString loadingStr = tr("WebUI will be started shortly after internal preparations. Please wait...");
782 printf("%s\n", qUtf8Printable(loadingStr));
783 #endif
785 #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
786 applyMemoryWorkingSetLimit();
787 #endif
789 #ifdef Q_OS_WIN
790 applyMemoryPriority();
791 adjustThreadPriority();
792 #endif
794 Net::ProxyConfigurationManager::initInstance();
795 Net::DownloadManager::initInstance();
796 IconProvider::initInstance();
798 BitTorrent::Session::initInstance();
799 #ifndef DISABLE_GUI
800 UIThemeManager::initInstance();
802 m_desktopIntegration = new DesktopIntegration;
803 m_desktopIntegration->setToolTip(tr("Loading torrents..."));
804 #ifndef Q_OS_MACOS
805 auto *desktopIntegrationMenu = new QMenu;
806 auto *actionExit = new QAction(tr("E&xit"), desktopIntegrationMenu);
807 actionExit->setIcon(UIThemeManager::instance()->getIcon(u"application-exit"_s));
808 actionExit->setMenuRole(QAction::QuitRole);
809 actionExit->setShortcut(Qt::CTRL | Qt::Key_Q);
810 connect(actionExit, &QAction::triggered, this, []
812 QApplication::exit();
814 desktopIntegrationMenu->addAction(actionExit);
816 m_desktopIntegration->setMenu(desktopIntegrationMenu);
818 const bool isHidden = m_desktopIntegration->isActive() && (startUpWindowState() == WindowState::Hidden);
819 #else
820 const bool isHidden = false;
821 #endif
823 if (!isHidden)
825 createStartupProgressDialog();
826 // Add a small delay to avoid "flashing" the progress dialog in case there are not many torrents to restore.
827 m_startupProgressDialog->setMinimumDuration(1000);
828 if (startUpWindowState() != WindowState::Normal)
829 m_startupProgressDialog->setWindowState(Qt::WindowMinimized);
831 else
833 connect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
835 #endif
836 connect(BitTorrent::Session::instance(), &BitTorrent::Session::restored, this, [this]()
838 connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentAdded, this, &Application::torrentAdded);
839 connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentFinished, this, &Application::torrentFinished);
840 connect(BitTorrent::Session::instance(), &BitTorrent::Session::allTorrentsFinished, this, &Application::allTorrentsFinished, Qt::QueuedConnection);
842 m_addTorrentManager = new AddTorrentManagerImpl(this, BitTorrent::Session::instance(), this);
844 Net::GeoIPManager::initInstance();
845 TorrentFilesWatcher::initInstance();
847 new RSS::Session; // create RSS::Session singleton
848 new RSS::AutoDownloader(this); // create RSS::AutoDownloader singleton
850 #ifndef DISABLE_GUI
851 const auto *btSession = BitTorrent::Session::instance();
852 connect(btSession, &BitTorrent::Session::fullDiskError, this
853 , [this](const BitTorrent::Torrent *torrent, const QString &msg)
855 m_desktopIntegration->showNotification(tr("I/O Error", "i.e: Input/Output Error")
856 , tr("An I/O error occurred for torrent '%1'.\n Reason: %2"
857 , "e.g: An error occurred for torrent 'xxx.avi'.\n Reason: disk is full.").arg(torrent->name(), msg));
859 connect(btSession, &BitTorrent::Session::torrentFinished, this
860 , [this](const BitTorrent::Torrent *torrent)
862 m_desktopIntegration->showNotification(tr("Download completed"), tr("'%1' has finished downloading.", "e.g: xxx.avi has finished downloading.").arg(torrent->name()));
864 connect(m_addTorrentManager, &AddTorrentManager::torrentAdded, this
865 , [this]([[maybe_unused]] const QString &source, const BitTorrent::Torrent *torrent)
867 if (isTorrentAddedNotificationsEnabled())
868 m_desktopIntegration->showNotification(tr("Torrent added"), tr("'%1' was added.", "e.g: xxx.avi was added.").arg(torrent->name()));
870 connect(m_addTorrentManager, &AddTorrentManager::addTorrentFailed, this
871 , [this](const QString &source, const QString &reason)
873 m_desktopIntegration->showNotification(tr("Add torrent failed")
874 , tr("Couldn't add torrent '%1', reason: %2.").arg(source, reason));
877 disconnect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
878 #ifndef Q_OS_MACOS
879 const WindowState windowState = !m_startupProgressDialog ? WindowState::Hidden
880 : (m_startupProgressDialog->windowState() & Qt::WindowMinimized) ? WindowState::Minimized
881 : WindowState::Normal;
882 #else
883 const WindowState windowState = (m_startupProgressDialog->windowState() & Qt::WindowMinimized)
884 ? WindowState::Minimized : WindowState::Normal;
885 #endif
886 m_window = new MainWindow(this, windowState);
887 delete m_startupProgressDialog;
888 #endif // DISABLE_GUI
890 #ifndef DISABLE_WEBUI
891 m_webui = new WebUI(this);
892 #ifdef DISABLE_GUI
893 connect(m_webui, &WebUI::error, this, [](const QString &message) { fprintf(stderr, "%s\n", qUtf8Printable(message)); });
895 printf("%s", qUtf8Printable(u"\n******** %1 ********\n"_s.arg(tr("Information"))));
897 if (m_webui->isErrored())
899 const QString error = m_webui->errorMessage() + u'\n'
900 + tr("To fix the error, you may need to edit the config file manually.");
901 fprintf(stderr, "%s\n", qUtf8Printable(error));
903 else if (m_webui->isEnabled())
905 const QHostAddress address = m_webui->hostAddress();
906 const QString url = u"%1://%2:%3"_s.arg((m_webui->isHttps() ? u"https"_s : u"http"_s)
907 , (address.isEqual(QHostAddress::Any, QHostAddress::ConvertUnspecifiedAddress) ? u"localhost"_s : address.toString())
908 , QString::number(m_webui->port()));
909 printf("%s\n", qUtf8Printable(tr("To control qBittorrent, access the WebUI at: %1").arg(url)));
911 const Preferences *pref = Preferences::instance();
912 if (pref->getWebUIPassword() == QByteArrayLiteral("ARQ77eY1NUZaQsuDHbIMCA==:0WMRkYTUWVT9wVvdDtHAjU9b3b7uB8NR1Gur2hmQCvCDpm39Q+PsJRJPaCU51dEiz+dTzh8qbPsL8WkFljQYFQ=="))
914 const QString warning = tr("The Web UI administrator username is: %1").arg(pref->getWebUiUsername()) + u'\n'
915 + tr("The Web UI administrator password has not been changed from the default: %1").arg(u"adminadmin"_s) + u'\n'
916 + tr("This is a security risk, please change your password in program preferences.") + u'\n';
917 printf("%s", qUtf8Printable(warning));
920 else
922 printf("%s\n", qUtf8Printable(tr("The WebUI is disabled! To enable the WebUI, edit the config file manually.")));
924 #endif // DISABLE_GUI
925 #endif // DISABLE_WEBUI
927 m_isProcessingParamsAllowed = true;
928 for (const QBtCommandLineParameters &params : m_paramsQueue)
929 processParams(params);
930 m_paramsQueue.clear();
933 const QBtCommandLineParameters params = commandLineArgs();
934 if (!params.torrentSources.isEmpty())
935 m_paramsQueue.append(params);
937 return BaseApplication::exec();
940 bool Application::isRunning()
942 return !m_instanceManager->isFirstInstance();
945 #ifndef DISABLE_GUI
946 void Application::createStartupProgressDialog()
948 Q_ASSERT(!m_startupProgressDialog);
949 Q_ASSERT(m_desktopIntegration);
951 disconnect(m_desktopIntegration, &DesktopIntegration::activationRequested, this, &Application::createStartupProgressDialog);
953 m_startupProgressDialog = new QProgressDialog(tr("Loading torrents..."), tr("Exit"), 0, 100);
954 m_startupProgressDialog->setAttribute(Qt::WA_DeleteOnClose);
955 m_startupProgressDialog->setWindowFlag(Qt::WindowMinimizeButtonHint);
956 m_startupProgressDialog->setMinimumDuration(0); // Show dialog immediately by default
957 m_startupProgressDialog->setAutoReset(false);
958 m_startupProgressDialog->setAutoClose(false);
960 connect(m_startupProgressDialog, &QProgressDialog::canceled, this, []()
962 QApplication::exit();
965 connect(BitTorrent::Session::instance(), &BitTorrent::Session::startupProgressUpdated, m_startupProgressDialog, &QProgressDialog::setValue);
967 connect(m_desktopIntegration, &DesktopIntegration::activationRequested, m_startupProgressDialog, [this]()
969 #ifdef Q_OS_MACOS
970 if (!m_startupProgressDialog->isVisible())
972 m_startupProgressDialog->show();
973 m_startupProgressDialog->activateWindow();
974 m_startupProgressDialog->raise();
976 #else
977 if (m_startupProgressDialog->isHidden())
979 // Make sure the window is not minimized
980 m_startupProgressDialog->setWindowState((m_startupProgressDialog->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
982 // Then show it
983 m_startupProgressDialog->show();
984 m_startupProgressDialog->raise();
985 m_startupProgressDialog->activateWindow();
987 else
989 m_startupProgressDialog->hide();
991 #endif
995 void Application::askRecursiveTorrentDownloadConfirmation(const BitTorrent::Torrent *torrent)
997 const auto torrentID = torrent->id();
999 QMessageBox *confirmBox = new QMessageBox(QMessageBox::Question, tr("Recursive download confirmation")
1000 , tr("The torrent '%1' contains .torrent files, do you want to proceed with their downloads?").arg(torrent->name())
1001 , (QMessageBox::Yes | QMessageBox::No | QMessageBox::NoToAll), mainWindow());
1002 confirmBox->setAttribute(Qt::WA_DeleteOnClose);
1004 const QAbstractButton *yesButton = confirmBox->button(QMessageBox::Yes);
1005 QAbstractButton *neverButton = confirmBox->button(QMessageBox::NoToAll);
1006 neverButton->setText(tr("Never"));
1008 connect(confirmBox, &QMessageBox::buttonClicked, this
1009 , [this, torrentID, yesButton, neverButton](const QAbstractButton *button)
1011 if (button == yesButton)
1013 recursiveTorrentDownload(torrentID);
1015 else if (button == neverButton)
1017 Preferences::instance()->setRecursiveDownloadEnabled(false);
1020 confirmBox->open();
1023 void Application::recursiveTorrentDownload(const BitTorrent::TorrentID &torrentID)
1025 const BitTorrent::Torrent *torrent = BitTorrent::Session::instance()->getTorrent(torrentID);
1026 if (!torrent)
1027 return;
1029 for (const Path &torrentRelpath : asConst(torrent->filePaths()))
1031 if (torrentRelpath.hasExtension(u".torrent"_s))
1033 const Path torrentFullpath = torrent->savePath() / torrentRelpath;
1035 LogMsg(tr("Recursive download .torrent file within torrent. Source torrent: \"%1\". File: \"%2\"")
1036 .arg(torrent->name(), torrentFullpath.toString()));
1038 BitTorrent::AddTorrentParams params;
1039 // Passing the save path along to the sub torrent file
1040 params.savePath = torrent->savePath();
1041 addTorrentManager()->addTorrent(torrentFullpath.data(), params, AddTorrentOption::SkipDialog);
1046 #ifdef Q_OS_MACOS
1047 bool Application::event(QEvent *ev)
1049 if (ev->type() == QEvent::FileOpen)
1051 QString path = static_cast<QFileOpenEvent *>(ev)->file();
1052 if (path.isEmpty())
1053 // Get the url instead
1054 path = static_cast<QFileOpenEvent *>(ev)->url().toString();
1055 qDebug("Received a mac file open event: %s", qUtf8Printable(path));
1057 QBtCommandLineParameters params;
1058 params.torrentSources.append(path);
1059 // If Application is not allowed to process params immediately
1060 // (i.e., other components are not ready) store params
1061 if (m_isProcessingParamsAllowed)
1062 processParams(params);
1063 else
1064 m_paramsQueue.append(params);
1066 return true;
1069 return BaseApplication::event(ev);
1071 #endif // Q_OS_MACOS
1072 #endif // DISABLE_GUI
1074 void Application::initializeTranslation()
1076 Preferences *const pref = Preferences::instance();
1077 // Load translation
1078 const QString localeStr = pref->getLocale();
1080 if (m_qtTranslator.load((u"qtbase_" + localeStr), QLibraryInfo::path(QLibraryInfo::TranslationsPath))
1081 || m_qtTranslator.load((u"qt_" + localeStr), QLibraryInfo::path(QLibraryInfo::TranslationsPath)))
1083 qDebug("Qt %s locale recognized, using translation.", qUtf8Printable(localeStr));
1085 else
1087 qDebug("Qt %s locale unrecognized, using default (en).", qUtf8Printable(localeStr));
1090 installTranslator(&m_qtTranslator);
1092 if (m_translator.load(u":/lang/qbittorrent_" + localeStr))
1093 qDebug("%s locale recognized, using translation.", qUtf8Printable(localeStr));
1094 else
1095 qDebug("%s locale unrecognized, using default (en).", qUtf8Printable(localeStr));
1096 installTranslator(&m_translator);
1098 #ifndef DISABLE_GUI
1099 if (localeStr.startsWith(u"ar") || localeStr.startsWith(u"he"))
1101 qDebug("Right to Left mode");
1102 setLayoutDirection(Qt::RightToLeft);
1104 else
1106 setLayoutDirection(Qt::LeftToRight);
1108 #endif
1111 #if (!defined(DISABLE_GUI) && defined(Q_OS_WIN))
1112 void Application::shutdownCleanup([[maybe_unused]] QSessionManager &manager)
1114 // This is only needed for a special case on Windows XP.
1115 // (but is called for every Windows version)
1116 // If a process takes too much time to exit during OS
1117 // shutdown, the OS presents a dialog to the user.
1118 // That dialog tells the user that qbt is blocking the
1119 // shutdown, it shows a progress bar and it offers
1120 // a "Terminate Now" button for the user. However,
1121 // after the progress bar has reached 100% another button
1122 // is offered to the user reading "Cancel". With this the
1123 // user can cancel the **OS** shutdown. If we don't do
1124 // the cleanup by handling the commitDataRequest() signal
1125 // and the user clicks "Cancel", it will result in qbt being
1126 // killed and the shutdown proceeding instead. Apparently
1127 // aboutToQuit() is emitted too late in the shutdown process.
1128 cleanup();
1130 // According to the qt docs we shouldn't call quit() inside a slot.
1131 // aboutToQuit() is never emitted if the user hits "Cancel" in
1132 // the above dialog.
1133 QMetaObject::invokeMethod(qApp, &QCoreApplication::quit, Qt::QueuedConnection);
1135 #endif
1137 #if defined(QBT_USES_LIBTORRENT2) && !defined(Q_OS_MACOS)
1138 void Application::applyMemoryWorkingSetLimit() const
1140 const size_t MiB = 1024 * 1024;
1141 const QString logMessage = tr("Failed to set physical memory (RAM) usage limit. Error code: %1. Error message: \"%2\"");
1143 #ifdef Q_OS_WIN
1144 const SIZE_T maxSize = memoryWorkingSetLimit() * MiB;
1145 const auto minSize = std::min<SIZE_T>((64 * MiB), (maxSize / 2));
1146 if (!::SetProcessWorkingSetSizeEx(::GetCurrentProcess(), minSize, maxSize, QUOTA_LIMITS_HARDWS_MAX_ENABLE))
1148 const DWORD errorCode = ::GetLastError();
1149 QString message;
1150 LPVOID lpMsgBuf = nullptr;
1151 const DWORD msgLength = ::FormatMessageW((FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS)
1152 , nullptr, errorCode, LANG_USER_DEFAULT, reinterpret_cast<LPWSTR>(&lpMsgBuf), 0, nullptr);
1153 if (msgLength > 0)
1155 message = QString::fromWCharArray(reinterpret_cast<LPWSTR>(lpMsgBuf)).trimmed();
1156 ::LocalFree(lpMsgBuf);
1158 LogMsg(logMessage.arg(QString::number(errorCode), message), Log::WARNING);
1160 #elif defined(Q_OS_UNIX)
1161 // has no effect on linux but it might be meaningful for other OS
1162 rlimit limit {};
1164 if (::getrlimit(RLIMIT_RSS, &limit) != 0)
1165 return;
1167 const size_t newSize = memoryWorkingSetLimit() * MiB;
1168 if (newSize > limit.rlim_max)
1170 // try to raise the hard limit
1171 rlimit newLimit = limit;
1172 newLimit.rlim_max = newSize;
1173 if (::setrlimit(RLIMIT_RSS, &newLimit) != 0)
1175 const auto message = QString::fromLocal8Bit(strerror(errno));
1176 LogMsg(tr("Failed to set physical memory (RAM) usage hard limit. Requested size: %1. System hard limit: %2. Error code: %3. Error message: \"%4\"")
1177 .arg(QString::number(newSize), QString::number(limit.rlim_max), QString::number(errno), message), Log::WARNING);
1178 return;
1182 limit.rlim_cur = newSize;
1183 if (::setrlimit(RLIMIT_RSS, &limit) != 0)
1185 const auto message = QString::fromLocal8Bit(strerror(errno));
1186 LogMsg(logMessage.arg(QString::number(errno), message), Log::WARNING);
1188 #endif
1190 #endif
1192 #ifdef Q_OS_WIN
1193 MemoryPriority Application::processMemoryPriority() const
1195 return m_processMemoryPriority.get(MemoryPriority::BelowNormal);
1198 void Application::setProcessMemoryPriority(const MemoryPriority priority)
1200 if (processMemoryPriority() == priority)
1201 return;
1203 m_processMemoryPriority = priority;
1204 applyMemoryPriority();
1207 void Application::applyMemoryPriority() const
1209 using SETPROCESSINFORMATION = BOOL (WINAPI *)(HANDLE, PROCESS_INFORMATION_CLASS, LPVOID, DWORD);
1210 const auto setProcessInformation = Utils::Misc::loadWinAPI<SETPROCESSINFORMATION>(u"Kernel32.dll"_s, "SetProcessInformation");
1211 if (!setProcessInformation) // only available on Windows >= 8
1212 return;
1214 using SETTHREADINFORMATION = BOOL (WINAPI *)(HANDLE, THREAD_INFORMATION_CLASS, LPVOID, DWORD);
1215 const auto setThreadInformation = Utils::Misc::loadWinAPI<SETTHREADINFORMATION>(u"Kernel32.dll"_s, "SetThreadInformation");
1216 if (!setThreadInformation) // only available on Windows >= 8
1217 return;
1219 #if (_WIN32_WINNT < _WIN32_WINNT_WIN8)
1220 // this dummy struct is required to compile successfully when targeting older Windows version
1221 struct MEMORY_PRIORITY_INFORMATION
1223 ULONG MemoryPriority;
1226 #define MEMORY_PRIORITY_LOWEST 0
1227 #define MEMORY_PRIORITY_VERY_LOW 1
1228 #define MEMORY_PRIORITY_LOW 2
1229 #define MEMORY_PRIORITY_MEDIUM 3
1230 #define MEMORY_PRIORITY_BELOW_NORMAL 4
1231 #define MEMORY_PRIORITY_NORMAL 5
1232 #endif
1234 MEMORY_PRIORITY_INFORMATION prioInfo {};
1235 switch (processMemoryPriority())
1237 case MemoryPriority::Normal:
1238 default:
1239 prioInfo.MemoryPriority = MEMORY_PRIORITY_NORMAL;
1240 break;
1241 case MemoryPriority::BelowNormal:
1242 prioInfo.MemoryPriority = MEMORY_PRIORITY_BELOW_NORMAL;
1243 break;
1244 case MemoryPriority::Medium:
1245 prioInfo.MemoryPriority = MEMORY_PRIORITY_MEDIUM;
1246 break;
1247 case MemoryPriority::Low:
1248 prioInfo.MemoryPriority = MEMORY_PRIORITY_LOW;
1249 break;
1250 case MemoryPriority::VeryLow:
1251 prioInfo.MemoryPriority = MEMORY_PRIORITY_VERY_LOW;
1252 break;
1254 setProcessInformation(::GetCurrentProcess(), ProcessMemoryPriority, &prioInfo, sizeof(prioInfo));
1256 // To avoid thrashing/sluggishness of the app, set "main event loop" thread to normal memory priority
1257 // which is higher/equal than other threads
1258 prioInfo.MemoryPriority = MEMORY_PRIORITY_NORMAL;
1259 setThreadInformation(::GetCurrentThread(), ThreadMemoryPriority, &prioInfo, sizeof(prioInfo));
1262 void Application::adjustThreadPriority() const
1264 // Workaround for improving responsiveness of qbt when CPU resources are scarce.
1265 // Raise main event loop thread to be just one level higher than libtorrent threads.
1266 // Also note that on *nix platforms there is no easy way to achieve it,
1267 // so implementation is omitted.
1269 ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
1271 #endif
1273 void Application::cleanup()
1275 // cleanup() can be called multiple times during shutdown. We only need it once.
1276 if (m_isCleanupRun.exchange(true, std::memory_order_acquire))
1277 return;
1279 LogMsg(tr("qBittorrent termination initiated"));
1281 #ifndef DISABLE_GUI
1282 if (m_desktopIntegration)
1284 m_desktopIntegration->disconnect();
1285 m_desktopIntegration->setToolTip(tr("qBittorrent is shutting down..."));
1286 if (m_desktopIntegration->menu())
1287 m_desktopIntegration->menu()->setEnabled(false);
1290 if (m_window)
1292 // Hide the window and don't leave it on screen as
1293 // unresponsive. Also for Windows take the WinId
1294 // after it's hidden, because hide() may cause a
1295 // WinId change.
1296 m_window->hide();
1298 #ifdef Q_OS_WIN
1299 const std::wstring msg = tr("Saving torrent progress...").toStdWString();
1300 ::ShutdownBlockReasonCreate(reinterpret_cast<HWND>(m_window->effectiveWinId())
1301 , msg.c_str());
1302 #endif // Q_OS_WIN
1304 // Do manual cleanup in MainWindow to force widgets
1305 // to save their Preferences, stop all timers and
1306 // delete as many widgets as possible to leave only
1307 // a 'shell' MainWindow.
1308 // We need a valid window handle for Windows Vista+
1309 // otherwise the system shutdown will continue even
1310 // though we created a ShutdownBlockReason
1311 m_window->cleanup();
1313 #endif // DISABLE_GUI
1315 #ifndef DISABLE_WEBUI
1316 delete m_webui;
1317 #endif
1319 delete RSS::AutoDownloader::instance();
1320 delete RSS::Session::instance();
1322 TorrentFilesWatcher::freeInstance();
1323 delete m_addTorrentManager;
1324 BitTorrent::Session::freeInstance();
1325 Net::GeoIPManager::freeInstance();
1326 Net::DownloadManager::freeInstance();
1327 Net::ProxyConfigurationManager::freeInstance();
1328 Preferences::freeInstance();
1329 SettingsStorage::freeInstance();
1330 IconProvider::freeInstance();
1331 SearchPluginManager::freeInstance();
1332 Utils::Fs::removeDirRecursively(Utils::Fs::tempPath());
1334 LogMsg(tr("qBittorrent is now ready to exit"));
1335 Logger::freeInstance();
1336 delete m_fileLogger;
1338 #ifndef DISABLE_GUI
1339 if (m_window)
1341 #ifdef Q_OS_WIN
1342 ::ShutdownBlockReasonDestroy(reinterpret_cast<HWND>(m_window->effectiveWinId()));
1343 #endif // Q_OS_WIN
1344 delete m_window;
1345 delete m_desktopIntegration;
1346 UIThemeManager::freeInstance();
1348 #endif // DISABLE_GUI
1350 Profile::freeInstance();
1352 if (m_shutdownAct != ShutdownDialogAction::Exit)
1354 qDebug() << "Sending computer shutdown/suspend/hibernate signal...";
1355 Utils::Misc::shutdownComputer(m_shutdownAct);
1359 AddTorrentManagerImpl *Application::addTorrentManager() const
1361 return m_addTorrentManager;