Switch URLs to https
[qBittorrent.git] / src / gui / mainwindow.cpp
blobbefe5cd00e533f8ae86f1eb57252a44cd7d3c94a
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2022 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2006 Christophe Dumez <chris@qbittorrent.org>
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 "mainwindow.h"
32 #include <algorithm>
33 #include <chrono>
35 #include <QActionGroup>
36 #include <QClipboard>
37 #include <QCloseEvent>
38 #include <QComboBox>
39 #include <QDebug>
40 #include <QDesktopServices>
41 #include <QFileDialog>
42 #include <QFileSystemWatcher>
43 #include <QKeyEvent>
44 #include <QLabel>
45 #include <QMessageBox>
46 #include <QMetaObject>
47 #include <QMimeData>
48 #include <QProcess>
49 #include <QPushButton>
50 #include <QShortcut>
51 #include <QSplitter>
52 #include <QStatusBar>
53 #include <QtGlobal>
54 #include <QTimer>
56 #include "base/bittorrent/session.h"
57 #include "base/bittorrent/sessionstatus.h"
58 #include "base/global.h"
59 #include "base/net/downloadmanager.h"
60 #include "base/path.h"
61 #include "base/preferences.h"
62 #include "base/rss/rss_folder.h"
63 #include "base/rss/rss_session.h"
64 #include "base/utils/foreignapps.h"
65 #include "base/utils/fs.h"
66 #include "base/utils/misc.h"
67 #include "base/utils/password.h"
68 #include "base/version.h"
69 #include "aboutdialog.h"
70 #include "addnewtorrentdialog.h"
71 #include "autoexpandabledialog.h"
72 #include "cookiesdialog.h"
73 #include "desktopintegration.h"
74 #include "downloadfromurldialog.h"
75 #include "executionlogwidget.h"
76 #include "hidabletabwidget.h"
77 #include "lineedit.h"
78 #include "optionsdialog.h"
79 #include "powermanagement/powermanagement.h"
80 #include "properties/peerlistwidget.h"
81 #include "properties/propertieswidget.h"
82 #include "properties/trackerlistwidget.h"
83 #include "rss/rsswidget.h"
84 #include "search/searchwidget.h"
85 #include "speedlimitdialog.h"
86 #include "statsdialog.h"
87 #include "statusbar.h"
88 #include "torrentcreatordialog.h"
89 #include "transferlistfilterswidget.h"
90 #include "transferlistmodel.h"
91 #include "transferlistwidget.h"
92 #include "ui_mainwindow.h"
93 #include "uithememanager.h"
94 #include "utils.h"
96 #ifdef Q_OS_MACOS
97 #include "macutilities.h"
98 #endif
99 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
100 #include "programupdater.h"
101 #endif
103 using namespace std::chrono_literals;
105 namespace
107 #define SETTINGS_KEY(name) u"GUI/" name
108 #define EXECUTIONLOG_SETTINGS_KEY(name) (SETTINGS_KEY(u"Log/"_qs) name)
110 const std::chrono::seconds PREVENT_SUSPEND_INTERVAL {60};
112 bool isTorrentLink(const QString &str)
114 return str.startsWith(u"magnet:", Qt::CaseInsensitive)
115 || str.endsWith(TORRENT_FILE_EXTENSION, Qt::CaseInsensitive)
116 || (!str.startsWith(u"file:", Qt::CaseInsensitive)
117 && Net::DownloadManager::hasSupportedScheme(str));
121 MainWindow::MainWindow(IGUIApplication *app, WindowState initialState)
122 : GUIApplicationComponent(app)
123 , m_ui(new Ui::MainWindow)
124 , m_storeExecutionLogEnabled(EXECUTIONLOG_SETTINGS_KEY(u"Enabled"_qs))
125 , m_storeDownloadTrackerFavicon(SETTINGS_KEY(u"DownloadTrackerFavicon"_qs))
126 , m_storeExecutionLogTypes(EXECUTIONLOG_SETTINGS_KEY(u"Types"_qs), Log::MsgType::ALL)
128 m_ui->setupUi(this);
130 Preferences *const pref = Preferences::instance();
131 m_uiLocked = pref->isUILocked();
132 setWindowTitle(QStringLiteral("qBittorrent " QBT_VERSION));
133 m_displaySpeedInTitle = pref->speedInTitleBar();
134 // Setting icons
135 #ifndef Q_OS_MACOS
136 setWindowIcon(UIThemeManager::instance()->getIcon(u"qbittorrent"_qs));
137 #endif // Q_OS_MACOS
139 #if (defined(Q_OS_UNIX))
140 m_ui->actionOptions->setText(tr("Preferences"));
141 #endif
143 addToolbarContextMenu();
145 m_ui->actionOpen->setIcon(UIThemeManager::instance()->getIcon(u"list-add"_qs));
146 m_ui->actionDownloadFromURL->setIcon(UIThemeManager::instance()->getIcon(u"insert-link"_qs));
147 m_ui->actionSetGlobalSpeedLimits->setIcon(UIThemeManager::instance()->getIcon(u"speedometer"_qs));
148 m_ui->actionCreateTorrent->setIcon(UIThemeManager::instance()->getIcon(u"torrent-creator"_qs, u"document-edit"_qs));
149 m_ui->actionAbout->setIcon(UIThemeManager::instance()->getIcon(u"help-about"_qs));
150 m_ui->actionStatistics->setIcon(UIThemeManager::instance()->getIcon(u"view-statistics"_qs));
151 m_ui->actionTopQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-top"_qs));
152 m_ui->actionIncreaseQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-up"_qs));
153 m_ui->actionDecreaseQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-down"_qs));
154 m_ui->actionBottomQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-bottom"_qs));
155 m_ui->actionDelete->setIcon(UIThemeManager::instance()->getIcon(u"list-remove"_qs));
156 m_ui->actionDocumentation->setIcon(UIThemeManager::instance()->getIcon(u"help-contents"_qs));
157 m_ui->actionDonateMoney->setIcon(UIThemeManager::instance()->getIcon(u"wallet-open"_qs));
158 m_ui->actionExit->setIcon(UIThemeManager::instance()->getIcon(u"application-exit"_qs));
159 m_ui->actionLock->setIcon(UIThemeManager::instance()->getIcon(u"object-locked"_qs));
160 m_ui->actionOptions->setIcon(UIThemeManager::instance()->getIcon(u"configure"_qs, u"preferences-system"_qs));
161 m_ui->actionPause->setIcon(UIThemeManager::instance()->getIcon(u"torrent-stop"_qs, u"media-playback-pause"_qs));
162 m_ui->actionPauseAll->setIcon(UIThemeManager::instance()->getIcon(u"torrent-stop"_qs, u"media-playback-pause"_qs));
163 m_ui->actionStart->setIcon(UIThemeManager::instance()->getIcon(u"torrent-start"_qs, u"media-playback-start"_qs));
164 m_ui->actionStartAll->setIcon(UIThemeManager::instance()->getIcon(u"torrent-start"_qs, u"media-playback-start"_qs));
165 m_ui->menuAutoShutdownOnDownloadsCompletion->setIcon(UIThemeManager::instance()->getIcon(u"task-complete"_qs, u"application-exit"_qs));
166 m_ui->actionManageCookies->setIcon(UIThemeManager::instance()->getIcon(u"browser-cookies"_qs, u"preferences-web-browser-cookies"_qs));
167 m_ui->menuLog->setIcon(UIThemeManager::instance()->getIcon(u"help-contents"_qs));
168 m_ui->actionCheckForUpdates->setIcon(UIThemeManager::instance()->getIcon(u"view-refresh"_qs));
170 auto *lockMenu = new QMenu(this);
171 lockMenu->addAction(tr("&Set Password"), this, &MainWindow::defineUILockPassword);
172 lockMenu->addAction(tr("&Clear Password"), this, &MainWindow::clearUILockPassword);
173 m_ui->actionLock->setMenu(lockMenu);
175 // Creating Bittorrent session
176 updateAltSpeedsBtn(BitTorrent::Session::instance()->isAltGlobalSpeedLimitEnabled());
178 connect(BitTorrent::Session::instance(), &BitTorrent::Session::speedLimitModeChanged, this, &MainWindow::updateAltSpeedsBtn);
179 connect(BitTorrent::Session::instance(), &BitTorrent::Session::recursiveTorrentDownloadPossible, this, &MainWindow::askRecursiveTorrentDownloadConfirmation);
181 qDebug("create tabWidget");
182 m_tabs = new HidableTabWidget(this);
183 connect(m_tabs.data(), &QTabWidget::currentChanged, this, &MainWindow::tabChanged);
185 m_splitter = new QSplitter(Qt::Horizontal, this);
186 // vSplitter->setChildrenCollapsible(false);
188 auto *hSplitter = new QSplitter(Qt::Vertical, this);
189 hSplitter->setChildrenCollapsible(false);
190 hSplitter->setFrameShape(QFrame::NoFrame);
192 // Torrent filter
193 m_columnFilterEdit = new LineEdit;
194 m_columnFilterEdit->setPlaceholderText(tr("Filter torrents..."));
195 m_columnFilterEdit->setFixedWidth(200);
196 m_columnFilterEdit->setContextMenuPolicy(Qt::CustomContextMenu);
197 connect(m_columnFilterEdit, &QWidget::customContextMenuRequested, this, &MainWindow::showFilterContextMenu);
198 auto *columnFilterLabel = new QLabel(tr("Filter by:"));
199 m_columnFilterComboBox = new QComboBox;
200 QHBoxLayout *columnFilterLayout = new QHBoxLayout(m_columnFilterWidget);
201 columnFilterLayout->setContentsMargins(0, 0, 0, 0);
202 auto *columnFilterSpacer = new QWidget(this);
203 columnFilterSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
204 columnFilterLayout->addWidget(columnFilterSpacer);
205 columnFilterLayout->addWidget(m_columnFilterEdit);
206 columnFilterLayout->addWidget(columnFilterLabel, 0);
207 columnFilterLayout->addWidget(m_columnFilterComboBox, 0);
208 m_columnFilterWidget = new QWidget(this);
209 m_columnFilterWidget->setLayout(columnFilterLayout);
210 m_columnFilterAction = m_ui->toolBar->insertWidget(m_ui->actionLock, m_columnFilterWidget);
212 auto *spacer = new QWidget(this);
213 spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
214 m_ui->toolBar->insertWidget(m_columnFilterAction, spacer);
216 // Transfer List tab
217 m_transferListWidget = new TransferListWidget(hSplitter, this);
218 // m_transferListWidget->setStyleSheet("QTreeView {border: none;}"); // borderless
219 m_propertiesWidget = new PropertiesWidget(hSplitter);
220 connect(m_transferListWidget, &TransferListWidget::currentTorrentChanged, m_propertiesWidget, &PropertiesWidget::loadTorrentInfos);
221 hSplitter->addWidget(m_transferListWidget);
222 hSplitter->addWidget(m_propertiesWidget);
223 m_splitter->addWidget(hSplitter);
224 m_splitter->setCollapsible(0, false);
225 m_tabs->addTab(m_splitter,
226 #ifndef Q_OS_MACOS
227 UIThemeManager::instance()->getIcon(u"folder-remote"_qs),
228 #endif
229 tr("Transfers"));
230 // Filter types
231 const QVector<TransferListModel::Column> filterTypes = {TransferListModel::Column::TR_NAME, TransferListModel::Column::TR_SAVE_PATH};
232 for (const TransferListModel::Column type : filterTypes)
234 const QString typeName = m_transferListWidget->getSourceModel()->headerData(type, Qt::Horizontal, Qt::DisplayRole).value<QString>();
235 m_columnFilterComboBox->addItem(typeName, type);
237 connect(m_columnFilterComboBox, &QComboBox::currentIndexChanged, this, &MainWindow::applyTransferListFilter);
238 connect(m_columnFilterEdit, &LineEdit::textChanged, this, &MainWindow::applyTransferListFilter);
239 connect(hSplitter, &QSplitter::splitterMoved, this, &MainWindow::saveSettings);
240 connect(m_splitter, &QSplitter::splitterMoved, this, &MainWindow::saveSplitterSettings);
241 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersChanged, m_propertiesWidget, &PropertiesWidget::loadTrackers);
243 #ifdef Q_OS_MACOS
244 // Increase top spacing to avoid tab overlapping
245 m_ui->centralWidgetLayout->addSpacing(8);
246 #endif
248 m_ui->centralWidgetLayout->addWidget(m_tabs);
250 m_queueSeparator = m_ui->toolBar->insertSeparator(m_ui->actionTopQueuePos);
251 m_queueSeparatorMenu = m_ui->menuEdit->insertSeparator(m_ui->actionTopQueuePos);
253 #ifdef Q_OS_MACOS
254 for (QAction *action : asConst(m_ui->toolBar->actions()))
256 if (action->isSeparator())
258 QWidget *spacer = new QWidget(this);
259 spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
260 spacer->setMinimumWidth(16);
261 m_ui->toolBar->insertWidget(action, spacer);
262 m_ui->toolBar->removeAction(action);
266 QWidget *spacer = new QWidget(this);
267 spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
268 spacer->setMinimumWidth(8);
269 m_ui->toolBar->insertWidget(m_ui->actionDownloadFromURL, spacer);
272 QWidget *spacer = new QWidget(this);
273 spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
274 spacer->setMinimumWidth(8);
275 m_ui->toolBar->addWidget(spacer);
277 #endif // Q_OS_MACOS
279 // Transfer list slots
280 connect(m_ui->actionStart, &QAction::triggered, m_transferListWidget, &TransferListWidget::startSelectedTorrents);
281 connect(m_ui->actionStartAll, &QAction::triggered, m_transferListWidget, &TransferListWidget::resumeAllTorrents);
282 connect(m_ui->actionPause, &QAction::triggered, m_transferListWidget, &TransferListWidget::pauseSelectedTorrents);
283 connect(m_ui->actionPauseAll, &QAction::triggered, m_transferListWidget, &TransferListWidget::pauseAllTorrents);
284 connect(m_ui->actionDelete, &QAction::triggered, m_transferListWidget, &TransferListWidget::softDeleteSelectedTorrents);
285 connect(m_ui->actionTopQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::topQueuePosSelectedTorrents);
286 connect(m_ui->actionIncreaseQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::increaseQueuePosSelectedTorrents);
287 connect(m_ui->actionDecreaseQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::decreaseQueuePosSelectedTorrents);
288 connect(m_ui->actionBottomQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::bottomQueuePosSelectedTorrents);
289 #ifndef Q_OS_MACOS
290 connect(m_ui->actionToggleVisibility, &QAction::triggered, this, &MainWindow::toggleVisibility);
291 #endif
292 connect(m_ui->actionMinimize, &QAction::triggered, this, &MainWindow::minimizeWindow);
293 connect(m_ui->actionUseAlternativeSpeedLimits, &QAction::triggered, this, &MainWindow::toggleAlternativeSpeeds);
295 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
296 connect(m_ui->actionCheckForUpdates, &QAction::triggered, this, [this]() { checkProgramUpdate(true); });
298 // trigger an early check on startup
299 if (pref->isUpdateCheckEnabled())
300 checkProgramUpdate(false);
301 #else
302 m_ui->actionCheckForUpdates->setVisible(false);
303 #endif
305 // Certain menu items should reside at specific places on macOS.
306 // Qt partially does it on its own, but updates and different languages require tuning.
307 m_ui->actionExit->setMenuRole(QAction::QuitRole);
308 m_ui->actionAbout->setMenuRole(QAction::AboutRole);
309 m_ui->actionCheckForUpdates->setMenuRole(QAction::ApplicationSpecificRole);
310 m_ui->actionOptions->setMenuRole(QAction::PreferencesRole);
312 connect(m_ui->actionManageCookies, &QAction::triggered, this, &MainWindow::manageCookies);
314 // Initialise system sleep inhibition timer
315 m_pwr = new PowerManagement(this);
316 m_preventTimer = new QTimer(this);
317 connect(m_preventTimer, &QTimer::timeout, this, &MainWindow::updatePowerManagementState);
318 m_preventTimer->start(PREVENT_SUSPEND_INTERVAL);
320 // Configure BT session according to options
321 loadPreferences();
323 connect(BitTorrent::Session::instance(), &BitTorrent::Session::statsUpdated, this, &MainWindow::reloadSessionStats);
324 connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentsUpdated, this, &MainWindow::reloadTorrentStats);
326 // Accept drag 'n drops
327 setAcceptDrops(true);
328 createKeyboardShortcuts();
330 #ifdef Q_OS_MACOS
331 setUnifiedTitleAndToolBarOnMac(true);
332 #endif
334 // View settings
335 m_ui->actionTopToolBar->setChecked(pref->isToolbarDisplayed());
336 m_ui->actionShowStatusbar->setChecked(pref->isStatusbarDisplayed());
337 m_ui->actionSpeedInTitleBar->setChecked(pref->speedInTitleBar());
338 m_ui->actionRSSReader->setChecked(pref->isRSSWidgetEnabled());
339 m_ui->actionSearchWidget->setChecked(pref->isSearchEnabled());
340 m_ui->actionExecutionLogs->setChecked(isExecutionLogEnabled());
342 const Log::MsgTypes flags = executionLogMsgTypes();
343 m_ui->actionNormalMessages->setChecked(flags.testFlag(Log::NORMAL));
344 m_ui->actionInformationMessages->setChecked(flags.testFlag(Log::INFO));
345 m_ui->actionWarningMessages->setChecked(flags.testFlag(Log::WARNING));
346 m_ui->actionCriticalMessages->setChecked(flags.testFlag(Log::CRITICAL));
348 displayRSSTab(m_ui->actionRSSReader->isChecked());
349 on_actionExecutionLogs_triggered(m_ui->actionExecutionLogs->isChecked());
350 on_actionNormalMessages_triggered(m_ui->actionNormalMessages->isChecked());
351 on_actionInformationMessages_triggered(m_ui->actionInformationMessages->isChecked());
352 on_actionWarningMessages_triggered(m_ui->actionWarningMessages->isChecked());
353 on_actionCriticalMessages_triggered(m_ui->actionCriticalMessages->isChecked());
354 if (m_ui->actionSearchWidget->isChecked())
355 QMetaObject::invokeMethod(this, &MainWindow::on_actionSearchWidget_triggered, Qt::QueuedConnection);
356 // Auto shutdown actions
357 auto *autoShutdownGroup = new QActionGroup(this);
358 autoShutdownGroup->setExclusive(true);
359 autoShutdownGroup->addAction(m_ui->actionAutoShutdownDisabled);
360 autoShutdownGroup->addAction(m_ui->actionAutoExit);
361 autoShutdownGroup->addAction(m_ui->actionAutoShutdown);
362 autoShutdownGroup->addAction(m_ui->actionAutoSuspend);
363 autoShutdownGroup->addAction(m_ui->actionAutoHibernate);
364 #if (!defined(Q_OS_UNIX) || defined(Q_OS_MACOS)) || defined(QBT_USES_DBUS)
365 m_ui->actionAutoShutdown->setChecked(pref->shutdownWhenDownloadsComplete());
366 m_ui->actionAutoSuspend->setChecked(pref->suspendWhenDownloadsComplete());
367 m_ui->actionAutoHibernate->setChecked(pref->hibernateWhenDownloadsComplete());
368 #else
369 m_ui->actionAutoShutdown->setDisabled(true);
370 m_ui->actionAutoSuspend->setDisabled(true);
371 m_ui->actionAutoHibernate->setDisabled(true);
372 #endif
373 m_ui->actionAutoExit->setChecked(pref->shutdownqBTWhenDownloadsComplete());
375 if (!autoShutdownGroup->checkedAction())
376 m_ui->actionAutoShutdownDisabled->setChecked(true);
378 // Load Window state and sizes
379 loadSettings();
381 app->desktopIntegration()->setMenu(createDesktopIntegrationMenu());
382 #ifndef Q_OS_MACOS
383 m_ui->actionLock->setVisible(app->desktopIntegration()->isActive());
384 connect(app->desktopIntegration(), &DesktopIntegration::stateChanged, this, [this, app]()
386 m_ui->actionLock->setVisible(app->desktopIntegration()->isActive());
388 #endif
389 connect(app->desktopIntegration(), &DesktopIntegration::notificationClicked, this, &MainWindow::desktopNotificationClicked);
390 connect(app->desktopIntegration(), &DesktopIntegration::activationRequested, this, [this]()
392 #ifdef Q_OS_MACOS
393 if (!isVisible())
394 activate();
395 #else
396 toggleVisibility();
397 #endif
400 #ifdef Q_OS_MACOS
401 if (initialState == WindowState::Normal)
403 show();
404 activateWindow();
405 raise();
407 else
409 // Make sure the Window is visible if we don't have a tray icon
410 showMinimized();
412 #else
413 if (app->desktopIntegration()->isActive())
415 if ((initialState == WindowState::Normal) && !m_uiLocked)
417 show();
418 activateWindow();
419 raise();
421 else if (initialState == WindowState::Minimized)
423 showMinimized();
424 if (pref->minimizeToTray())
426 hide();
427 if (!pref->minimizeToTrayNotified())
429 app->desktopIntegration()->showNotification(tr("qBittorrent is minimized to tray"), tr("This behavior can be changed in the settings. You won't be reminded again."));
430 pref->setMinimizeToTrayNotified(true);
435 else
437 // Make sure the Window is visible if we don't have a tray icon
438 if (initialState != WindowState::Normal)
440 showMinimized();
442 else
444 show();
445 activateWindow();
446 raise();
449 #endif
451 m_propertiesWidget->readSettings();
453 const bool isFiltersSidebarVisible = pref->isFiltersSidebarVisible();
454 m_ui->actionShowFiltersSidebar->setChecked(isFiltersSidebarVisible);
455 if (isFiltersSidebarVisible)
457 showFiltersSidebar(true);
459 else
461 m_transferListWidget->applyStatusFilter(pref->getTransSelFilter());
462 m_transferListWidget->applyCategoryFilter(QString());
463 m_transferListWidget->applyTagFilter(QString());
464 m_transferListWidget->applyTrackerFilterAll();
467 // Start watching the executable for updates
468 m_executableWatcher = new QFileSystemWatcher(this);
469 connect(m_executableWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::notifyOfUpdate);
470 m_executableWatcher->addPath(qApp->applicationFilePath());
472 m_transferListWidget->setFocus();
474 // Update the number of torrents (tab)
475 updateNbTorrents();
476 connect(m_transferListWidget->getSourceModel(), &QAbstractItemModel::rowsInserted, this, &MainWindow::updateNbTorrents);
477 connect(m_transferListWidget->getSourceModel(), &QAbstractItemModel::rowsRemoved, this, &MainWindow::updateNbTorrents);
479 connect(pref, &Preferences::changed, this, &MainWindow::optionsSaved);
481 qDebug("GUI Built");
484 MainWindow::~MainWindow()
486 delete m_ui;
489 bool MainWindow::isExecutionLogEnabled() const
491 return m_storeExecutionLogEnabled;
494 void MainWindow::setExecutionLogEnabled(const bool value)
496 m_storeExecutionLogEnabled = value;
499 Log::MsgTypes MainWindow::executionLogMsgTypes() const
501 return m_storeExecutionLogTypes;
504 void MainWindow::setExecutionLogMsgTypes(const Log::MsgTypes value)
506 m_executionLog->setMessageTypes(value);
507 m_storeExecutionLogTypes = value;
510 bool MainWindow::isDownloadTrackerFavicon() const
512 return m_storeDownloadTrackerFavicon;
515 void MainWindow::setDownloadTrackerFavicon(const bool value)
517 if (m_transferListFiltersWidget)
518 m_transferListFiltersWidget->setDownloadTrackerFavicon(value);
519 m_storeDownloadTrackerFavicon = value;
522 void MainWindow::addToolbarContextMenu()
524 const Preferences *const pref = Preferences::instance();
525 m_toolbarMenu = new QMenu(this);
527 m_ui->toolBar->setContextMenuPolicy(Qt::CustomContextMenu);
528 connect(m_ui->toolBar, &QWidget::customContextMenuRequested, this, &MainWindow::toolbarMenuRequested);
530 QAction *iconsOnly = m_toolbarMenu->addAction(tr("Icons Only"), this, &MainWindow::toolbarIconsOnly);
531 QAction *textOnly = m_toolbarMenu->addAction(tr("Text Only"), this, &MainWindow::toolbarTextOnly);
532 QAction *textBesideIcons = m_toolbarMenu->addAction(tr("Text Alongside Icons"), this, &MainWindow::toolbarTextBeside);
533 QAction *textUnderIcons = m_toolbarMenu->addAction(tr("Text Under Icons"), this, &MainWindow::toolbarTextUnder);
534 QAction *followSystemStyle = m_toolbarMenu->addAction(tr("Follow System Style"), this, &MainWindow::toolbarFollowSystem);
536 auto *textPositionGroup = new QActionGroup(m_toolbarMenu);
537 textPositionGroup->addAction(iconsOnly);
538 iconsOnly->setCheckable(true);
539 textPositionGroup->addAction(textOnly);
540 textOnly->setCheckable(true);
541 textPositionGroup->addAction(textBesideIcons);
542 textBesideIcons->setCheckable(true);
543 textPositionGroup->addAction(textUnderIcons);
544 textUnderIcons->setCheckable(true);
545 textPositionGroup->addAction(followSystemStyle);
546 followSystemStyle->setCheckable(true);
548 const auto buttonStyle = static_cast<Qt::ToolButtonStyle>(pref->getToolbarTextPosition());
549 if ((buttonStyle >= Qt::ToolButtonIconOnly) && (buttonStyle <= Qt::ToolButtonFollowStyle))
550 m_ui->toolBar->setToolButtonStyle(buttonStyle);
551 switch (buttonStyle)
553 case Qt::ToolButtonIconOnly:
554 iconsOnly->setChecked(true);
555 break;
556 case Qt::ToolButtonTextOnly:
557 textOnly->setChecked(true);
558 break;
559 case Qt::ToolButtonTextBesideIcon:
560 textBesideIcons->setChecked(true);
561 break;
562 case Qt::ToolButtonTextUnderIcon:
563 textUnderIcons->setChecked(true);
564 break;
565 default:
566 followSystemStyle->setChecked(true);
570 void MainWindow::manageCookies()
572 auto *cookieDialog = new CookiesDialog(this);
573 cookieDialog->setAttribute(Qt::WA_DeleteOnClose);
574 cookieDialog->open();
577 void MainWindow::toolbarMenuRequested()
579 m_toolbarMenu->popup(QCursor::pos());
582 void MainWindow::toolbarIconsOnly()
584 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
585 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonIconOnly);
588 void MainWindow::toolbarTextOnly()
590 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextOnly);
591 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonTextOnly);
594 void MainWindow::toolbarTextBeside()
596 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
597 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonTextBesideIcon);
600 void MainWindow::toolbarTextUnder()
602 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
603 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonTextUnderIcon);
606 void MainWindow::toolbarFollowSystem()
608 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonFollowStyle);
609 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonFollowStyle);
612 bool MainWindow::defineUILockPassword()
614 bool ok = false;
615 const QString newPassword = AutoExpandableDialog::getText(this, tr("UI lock password")
616 , tr("Please type the UI lock password:"), QLineEdit::Password, {}, &ok);
617 if (!ok)
618 return false;
620 if (newPassword.size() < 3)
622 QMessageBox::warning(this, tr("Invalid password"), tr("The password must be at least 3 characters long"));
623 return false;
626 Preferences::instance()->setUILockPassword(Utils::Password::PBKDF2::generate(newPassword));
627 return true;
630 void MainWindow::clearUILockPassword()
632 const QMessageBox::StandardButton answer = QMessageBox::question(this, tr("Clear the password")
633 , tr("Are you sure you want to clear the password?"), (QMessageBox::Yes | QMessageBox::No), QMessageBox::No);
634 if (answer == QMessageBox::Yes)
635 Preferences::instance()->setUILockPassword({});
638 void MainWindow::on_actionLock_triggered()
640 Preferences *const pref = Preferences::instance();
642 // Check if there is a password
643 if (pref->getUILockPassword().isEmpty())
645 if (!defineUILockPassword())
646 return;
649 // Lock the interface
650 m_uiLocked = true;
651 pref->setUILocked(true);
652 app()->desktopIntegration()->menu()->setEnabled(false);
653 hide();
656 void MainWindow::handleRSSUnreadCountUpdated(int count)
658 m_tabs->setTabText(m_tabs->indexOf(m_rssWidget), tr("RSS (%1)").arg(count));
661 void MainWindow::displayRSSTab(bool enable)
663 if (enable)
665 // RSS tab
666 if (!m_rssWidget)
668 m_rssWidget = new RSSWidget(m_tabs);
669 connect(m_rssWidget.data(), &RSSWidget::unreadCountUpdated, this, &MainWindow::handleRSSUnreadCountUpdated);
670 #ifdef Q_OS_MACOS
671 m_tabs->addTab(m_rssWidget, tr("RSS (%1)").arg(RSS::Session::instance()->rootFolder()->unreadCount()));
672 #else
673 const int indexTab = m_tabs->addTab(m_rssWidget, tr("RSS (%1)").arg(RSS::Session::instance()->rootFolder()->unreadCount()));
674 m_tabs->setTabIcon(indexTab, UIThemeManager::instance()->getIcon(u"application-rss"_qs));
675 #endif
678 else
680 delete m_rssWidget;
684 void MainWindow::showFilterContextMenu()
686 const Preferences *pref = Preferences::instance();
688 QMenu *menu = m_columnFilterEdit->createStandardContextMenu();
689 menu->setAttribute(Qt::WA_DeleteOnClose);
690 menu->addSeparator();
692 QAction *useRegexAct = menu->addAction(tr("Use regular expressions"));
693 useRegexAct->setCheckable(true);
694 useRegexAct->setChecked(pref->getRegexAsFilteringPatternForTransferList());
695 connect(useRegexAct, &QAction::toggled, pref, &Preferences::setRegexAsFilteringPatternForTransferList);
696 connect(useRegexAct, &QAction::toggled, this, &MainWindow::applyTransferListFilter);
698 menu->popup(QCursor::pos());
701 void MainWindow::displaySearchTab(bool enable)
703 Preferences::instance()->setSearchEnabled(enable);
704 if (enable)
706 // RSS tab
707 if (!m_searchWidget)
709 m_searchWidget = new SearchWidget(app(), this);
710 m_tabs->insertTab(1, m_searchWidget,
711 #ifndef Q_OS_MACOS
712 UIThemeManager::instance()->getIcon(u"edit-find"_qs),
713 #endif
714 tr("Search"));
717 else
719 delete m_searchWidget;
723 void MainWindow::focusSearchFilter()
725 m_columnFilterEdit->setFocus();
726 m_columnFilterEdit->selectAll();
729 void MainWindow::updateNbTorrents()
731 m_tabs->setTabText(0, tr("Transfers (%1)").arg(m_transferListWidget->getSourceModel()->rowCount()));
734 void MainWindow::on_actionDocumentation_triggered() const
736 QDesktopServices::openUrl(QUrl(u"https://doc.qbittorrent.org"_qs));
739 void MainWindow::tabChanged(int newTab)
741 Q_UNUSED(newTab);
742 // We cannot rely on the index newTab
743 // because the tab order is undetermined now
744 if (m_tabs->currentWidget() == m_splitter)
746 qDebug("Changed tab to transfer list, refreshing the list");
747 m_propertiesWidget->loadDynamicData();
748 m_columnFilterAction->setVisible(true);
749 return;
751 m_columnFilterAction->setVisible(false);
753 if (m_tabs->currentWidget() == m_searchWidget)
755 qDebug("Changed tab to search engine, giving focus to search input");
756 m_searchWidget->giveFocusToSearchInput();
760 void MainWindow::saveSettings() const
762 auto *pref = Preferences::instance();
763 pref->setMainGeometry(saveGeometry());
764 m_propertiesWidget->saveSettings();
767 void MainWindow::saveSplitterSettings() const
769 if (!m_transferListFiltersWidget)
770 return;
772 auto *pref = Preferences::instance();
773 pref->setFiltersSidebarWidth(m_splitter->sizes()[0]);
776 void MainWindow::cleanup()
778 saveSettings();
779 saveSplitterSettings();
781 // delete RSSWidget explicitly to avoid crash in
782 // handleRSSUnreadCountUpdated() at application shutdown
783 delete m_rssWidget;
785 delete m_executableWatcher;
787 m_preventTimer->stop();
789 #if (defined(Q_OS_WIN) || defined(Q_OS_MACOS))
790 if (m_programUpdateTimer)
791 m_programUpdateTimer->stop();
792 #endif
794 // remove all child widgets
795 while (auto *w = findChild<QWidget *>())
796 delete w;
799 void MainWindow::loadSettings()
801 const auto *pref = Preferences::instance();
803 if (const QByteArray mainGeo = pref->getMainGeometry();
804 !mainGeo.isEmpty() && restoreGeometry(mainGeo))
806 m_posInitialized = true;
810 void MainWindow::desktopNotificationClicked()
812 if (isHidden())
814 if (m_uiLocked)
816 // Ask for UI lock password
817 if (!unlockUI())
818 return;
820 show();
821 if (isMinimized())
822 showNormal();
825 raise();
826 activateWindow();
829 void MainWindow::createKeyboardShortcuts()
831 m_ui->actionCreateTorrent->setShortcut(QKeySequence::New);
832 m_ui->actionOpen->setShortcut(QKeySequence::Open);
833 m_ui->actionDelete->setShortcut(QKeySequence::Delete);
834 m_ui->actionDelete->setShortcutContext(Qt::WidgetShortcut); // nullify its effect: delete key event is handled by respective widgets, not here
835 m_ui->actionDownloadFromURL->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_O);
836 m_ui->actionExit->setShortcut(Qt::CTRL | Qt::Key_Q);
837 #ifdef Q_OS_MACOS
838 m_ui->actionCloseWindow->setShortcut(QKeySequence::Close);
839 #else
840 m_ui->actionCloseWindow->setVisible(false);
841 #endif
843 const auto *switchTransferShortcut = new QShortcut((Qt::ALT | Qt::Key_1), this);
844 connect(switchTransferShortcut, &QShortcut::activated, this, &MainWindow::displayTransferTab);
845 const auto *switchSearchShortcut = new QShortcut((Qt::ALT | Qt::Key_2), this);
846 connect(switchSearchShortcut, &QShortcut::activated, this, qOverload<>(&MainWindow::displaySearchTab));
847 const auto *switchRSSShortcut = new QShortcut((Qt::ALT | Qt::Key_3), this);
848 connect(switchRSSShortcut, &QShortcut::activated, this, qOverload<>(&MainWindow::displayRSSTab));
849 const auto *switchExecutionLogShortcut = new QShortcut((Qt::ALT | Qt::Key_4), this);
850 connect(switchExecutionLogShortcut, &QShortcut::activated, this, &MainWindow::displayExecutionLogTab);
851 const auto *switchSearchFilterShortcut = new QShortcut(QKeySequence::Find, m_transferListWidget);
852 connect(switchSearchFilterShortcut, &QShortcut::activated, this, &MainWindow::focusSearchFilter);
854 m_ui->actionDocumentation->setShortcut(QKeySequence::HelpContents);
855 m_ui->actionOptions->setShortcut(Qt::ALT | Qt::Key_O);
856 m_ui->actionStatistics->setShortcut(Qt::CTRL | Qt::Key_I);
857 m_ui->actionStart->setShortcut(Qt::CTRL | Qt::Key_S);
858 m_ui->actionStartAll->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_S);
859 m_ui->actionPause->setShortcut(Qt::CTRL | Qt::Key_P);
860 m_ui->actionPauseAll->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_P);
861 m_ui->actionBottomQueuePos->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_Minus);
862 m_ui->actionDecreaseQueuePos->setShortcut(Qt::CTRL | Qt::Key_Minus);
863 m_ui->actionIncreaseQueuePos->setShortcut(Qt::CTRL | Qt::Key_Plus);
864 m_ui->actionTopQueuePos->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_Plus);
865 #ifdef Q_OS_MACOS
866 m_ui->actionMinimize->setShortcut(Qt::CTRL + Qt::Key_M);
867 addAction(m_ui->actionMinimize);
868 #endif
871 // Keyboard shortcuts slots
872 void MainWindow::displayTransferTab() const
874 m_tabs->setCurrentWidget(m_transferListWidget);
877 void MainWindow::displaySearchTab()
879 if (!m_searchWidget)
881 m_ui->actionSearchWidget->setChecked(true);
882 displaySearchTab(true);
885 m_tabs->setCurrentWidget(m_searchWidget);
888 void MainWindow::displayRSSTab()
890 if (!m_rssWidget)
892 m_ui->actionRSSReader->setChecked(true);
893 displayRSSTab(true);
896 m_tabs->setCurrentWidget(m_rssWidget);
899 void MainWindow::displayExecutionLogTab()
901 if (!m_executionLog)
903 m_ui->actionExecutionLogs->setChecked(true);
904 on_actionExecutionLogs_triggered(true);
907 m_tabs->setCurrentWidget(m_executionLog);
910 // End of keyboard shortcuts slots
912 void MainWindow::askRecursiveTorrentDownloadConfirmation(const BitTorrent::Torrent *torrent)
914 if (!Preferences::instance()->isRecursiveDownloadEnabled())
915 return;
917 const auto torrentID = torrent->id();
919 QMessageBox *confirmBox = new QMessageBox(QMessageBox::Question, tr("Recursive download confirmation")
920 , tr("The torrent '%1' contains .torrent files, do you want to proceed with their downloads?").arg(torrent->name())
921 , (QMessageBox::Yes | QMessageBox::No | QMessageBox::NoToAll), this);
922 confirmBox->setAttribute(Qt::WA_DeleteOnClose);
924 const QAbstractButton *yesButton = confirmBox->button(QMessageBox::Yes);
925 QAbstractButton *neverButton = confirmBox->button(QMessageBox::NoToAll);
926 neverButton->setText(tr("Never"));
928 connect(confirmBox, &QMessageBox::buttonClicked, this
929 , [torrentID, yesButton, neverButton](const QAbstractButton *button)
931 if (button == yesButton)
933 BitTorrent::Session::instance()->recursiveTorrentDownload(torrentID);
935 else if (button == neverButton)
937 Preferences::instance()->setRecursiveDownloadEnabled(false);
940 confirmBox->open();
943 void MainWindow::on_actionSetGlobalSpeedLimits_triggered()
945 auto dialog = new SpeedLimitDialog {this};
946 dialog->setAttribute(Qt::WA_DeleteOnClose);
947 dialog->open();
950 // Necessary if we want to close the window
951 // in one time if "close to systray" is enabled
952 void MainWindow::on_actionExit_triggered()
954 // UI locking enforcement.
955 if (isHidden() && m_uiLocked)
956 // Ask for UI lock password
957 if (!unlockUI()) return;
959 m_forceExit = true;
960 close();
963 #ifdef Q_OS_MACOS
964 void MainWindow::on_actionCloseWindow_triggered()
966 // On macOS window close is basically equivalent to window hide.
967 // If you decide to implement this functionality for other OS,
968 // then you will also need ui lock checks like in actionExit.
969 close();
971 #endif
973 QWidget *MainWindow::currentTabWidget() const
975 if (isMinimized() || !isVisible())
976 return nullptr;
977 if (m_tabs->currentIndex() == 0)
978 return m_transferListWidget;
979 return m_tabs->currentWidget();
982 TransferListWidget *MainWindow::transferListWidget() const
984 return m_transferListWidget;
987 bool MainWindow::unlockUI()
989 if (m_unlockDlgShowing)
990 return false;
992 bool ok = false;
993 const QString password = AutoExpandableDialog::getText(this, tr("UI lock password")
994 , tr("Please type the UI lock password:"), QLineEdit::Password, {}, &ok);
995 if (!ok) return false;
997 Preferences *const pref = Preferences::instance();
999 const QByteArray secret = pref->getUILockPassword();
1000 if (!Utils::Password::PBKDF2::verify(secret, password))
1002 QMessageBox::warning(this, tr("Invalid password"), tr("The password is invalid"));
1003 return false;
1006 m_uiLocked = false;
1007 pref->setUILocked(false);
1008 app()->desktopIntegration()->menu()->setEnabled(true);
1009 return true;
1012 void MainWindow::notifyOfUpdate(const QString &)
1014 // Show restart message
1015 m_statusBar->showRestartRequired();
1016 LogMsg(tr("qBittorrent was just updated and needs to be restarted for the changes to be effective.")
1017 , Log::CRITICAL);
1018 // Delete the executable watcher
1019 delete m_executableWatcher;
1020 m_executableWatcher = nullptr;
1023 #ifndef Q_OS_MACOS
1024 // Toggle Main window visibility
1025 void MainWindow::toggleVisibility()
1027 if (isHidden())
1029 if (m_uiLocked && !unlockUI()) // Ask for UI lock password
1030 return;
1032 // Make sure the window is not minimized
1033 setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
1035 // Then show it
1036 show();
1037 raise();
1038 activateWindow();
1040 else
1042 hide();
1045 #endif // Q_OS_MACOS
1047 // Display About Dialog
1048 void MainWindow::on_actionAbout_triggered()
1050 // About dialog
1051 if (m_aboutDlg)
1053 m_aboutDlg->activateWindow();
1055 else
1057 m_aboutDlg = new AboutDialog(this);
1058 m_aboutDlg->setAttribute(Qt::WA_DeleteOnClose);
1059 m_aboutDlg->show();
1063 void MainWindow::on_actionStatistics_triggered()
1065 if (m_statsDlg)
1067 m_statsDlg->activateWindow();
1069 else
1071 m_statsDlg = new StatsDialog(this);
1072 m_statsDlg->setAttribute(Qt::WA_DeleteOnClose);
1073 m_statsDlg->show();
1077 void MainWindow::showEvent(QShowEvent *e)
1079 qDebug("** Show Event **");
1080 e->accept();
1082 if (isVisible())
1084 // preparations before showing the window
1086 if (currentTabWidget() == m_transferListWidget)
1087 m_propertiesWidget->loadDynamicData();
1089 // Make sure the window is initially centered
1090 if (!m_posInitialized)
1092 move(Utils::Gui::screenCenter(this));
1093 m_posInitialized = true;
1096 else
1098 // to avoid blank screen when restoring from tray icon
1099 show();
1103 void MainWindow::keyPressEvent(QKeyEvent *event)
1105 if (event->matches(QKeySequence::Paste))
1107 const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData();
1109 if (mimeData->hasText())
1111 const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled();
1112 const QStringList lines = mimeData->text().split(u'\n', Qt::SkipEmptyParts);
1114 for (QString line : lines)
1116 line = line.trimmed();
1118 if (!isTorrentLink(line))
1119 continue;
1121 if (useTorrentAdditionDialog)
1122 AddNewTorrentDialog::show(line, this);
1123 else
1124 BitTorrent::Session::instance()->addTorrent(line);
1127 return;
1131 QMainWindow::keyPressEvent(event);
1134 // Called when we close the program
1135 void MainWindow::closeEvent(QCloseEvent *e)
1137 Preferences *const pref = Preferences::instance();
1138 #ifdef Q_OS_MACOS
1139 if (!m_forceExit)
1141 hide();
1142 e->accept();
1143 return;
1145 #else
1146 const bool goToSystrayOnExit = pref->closeToTray();
1147 if (!m_forceExit && app()->desktopIntegration()->isActive() && goToSystrayOnExit && !this->isHidden())
1149 e->ignore();
1150 QMetaObject::invokeMethod(this, &QWidget::hide, Qt::QueuedConnection);
1151 if (!pref->closeToTrayNotified())
1153 app()->desktopIntegration()->showNotification(tr("qBittorrent is closed to tray"), tr("This behavior can be changed in the settings. You won't be reminded again."));
1154 pref->setCloseToTrayNotified(true);
1156 return;
1158 #endif // Q_OS_MACOS
1160 const QVector<BitTorrent::Torrent *> allTorrents = BitTorrent::Session::instance()->torrents();
1161 const bool hasActiveTorrents = std::any_of(allTorrents.cbegin(), allTorrents.cend(), [](BitTorrent::Torrent *torrent)
1163 return torrent->isActive();
1165 if (pref->confirmOnExit() && hasActiveTorrents)
1167 if (e->spontaneous() || m_forceExit)
1169 if (!isVisible())
1170 show();
1171 QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"),
1172 // Split it because the last sentence is used in the Web UI
1173 tr("Some files are currently transferring.") + u'\n' + tr("Are you sure you want to quit qBittorrent?"),
1174 QMessageBox::NoButton, this);
1175 QPushButton *noBtn = confirmBox.addButton(tr("&No"), QMessageBox::NoRole);
1176 confirmBox.addButton(tr("&Yes"), QMessageBox::YesRole);
1177 QPushButton *alwaysBtn = confirmBox.addButton(tr("&Always Yes"), QMessageBox::YesRole);
1178 confirmBox.setDefaultButton(noBtn);
1179 confirmBox.exec();
1180 if (!confirmBox.clickedButton() || (confirmBox.clickedButton() == noBtn))
1182 // Cancel exit
1183 e->ignore();
1184 m_forceExit = false;
1185 return;
1187 if (confirmBox.clickedButton() == alwaysBtn)
1188 // Remember choice
1189 Preferences::instance()->setConfirmOnExit(false);
1193 // Accept exit
1194 e->accept();
1195 qApp->exit();
1198 // Display window to create a torrent
1199 void MainWindow::on_actionCreateTorrent_triggered()
1201 createTorrentTriggered({});
1204 void MainWindow::createTorrentTriggered(const Path &path)
1206 if (m_createTorrentDlg)
1208 m_createTorrentDlg->updateInputPath(path);
1209 m_createTorrentDlg->activateWindow();
1211 else
1213 m_createTorrentDlg = new TorrentCreatorDialog(this, path);
1214 m_createTorrentDlg->setAttribute(Qt::WA_DeleteOnClose);
1215 m_createTorrentDlg->show();
1219 bool MainWindow::event(QEvent *e)
1221 #ifndef Q_OS_MACOS
1222 switch (e->type())
1224 case QEvent::WindowStateChange:
1225 qDebug("Window change event");
1226 // Now check to see if the window is minimised
1227 if (isMinimized())
1229 qDebug("minimisation");
1230 Preferences *const pref = Preferences::instance();
1231 if (app()->desktopIntegration()->isActive() && pref->minimizeToTray())
1233 qDebug() << "Has active window:" << (qApp->activeWindow() != nullptr);
1234 // Check if there is a modal window
1235 const QWidgetList allWidgets = QApplication::allWidgets();
1236 const bool hasModalWindow = std::any_of(allWidgets.cbegin(), allWidgets.cend()
1237 , [](const QWidget *widget) { return widget->isModal(); });
1238 // Iconify if there is no modal window
1239 if (!hasModalWindow)
1241 qDebug("Minimize to Tray enabled, hiding!");
1242 e->ignore();
1243 QMetaObject::invokeMethod(this, &QWidget::hide, Qt::QueuedConnection);
1244 if (!pref->minimizeToTrayNotified())
1246 app()->desktopIntegration()->showNotification(tr("qBittorrent is minimized to tray"), tr("This behavior can be changed in the settings. You won't be reminded again."));
1247 pref->setMinimizeToTrayNotified(true);
1249 return true;
1253 break;
1254 case QEvent::ToolBarChange:
1256 qDebug("MAC: Received a toolbar change event!");
1257 const bool ret = QMainWindow::event(e);
1259 qDebug("MAC: new toolbar visibility is %d", !m_ui->actionTopToolBar->isChecked());
1260 m_ui->actionTopToolBar->toggle();
1261 Preferences::instance()->setToolbarDisplayed(m_ui->actionTopToolBar->isChecked());
1262 return ret;
1264 default:
1265 break;
1267 #endif // Q_OS_MACOS
1269 return QMainWindow::event(e);
1272 // action executed when a file is dropped
1273 void MainWindow::dropEvent(QDropEvent *event)
1275 event->acceptProposedAction();
1277 // remove scheme
1278 QStringList files;
1279 if (event->mimeData()->hasUrls())
1281 for (const QUrl &url : asConst(event->mimeData()->urls()))
1283 if (url.isEmpty())
1284 continue;
1286 files << ((url.scheme().compare(u"file", Qt::CaseInsensitive) == 0)
1287 ? url.toLocalFile()
1288 : url.toString());
1291 else
1293 files = event->mimeData()->text().split(u'\n');
1296 // differentiate ".torrent" files/links & magnet links from others
1297 QStringList torrentFiles, otherFiles;
1298 for (const QString &file : asConst(files))
1300 if (isTorrentLink(file))
1301 torrentFiles << file;
1302 else
1303 otherFiles << file;
1306 // Download torrents
1307 const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled();
1308 for (const QString &file : asConst(torrentFiles))
1310 if (useTorrentAdditionDialog)
1311 AddNewTorrentDialog::show(file, this);
1312 else
1313 BitTorrent::Session::instance()->addTorrent(file);
1315 if (!torrentFiles.isEmpty()) return;
1317 // Create torrent
1318 for (const QString &file : asConst(otherFiles))
1320 createTorrentTriggered(Path(file));
1322 // currently only handle the first entry
1323 // this is a stub that can be expanded later to create many torrents at once
1324 break;
1328 // Decode if we accept drag 'n drop or not
1329 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1331 for (const QString &mime : asConst(event->mimeData()->formats()))
1332 qDebug("mimeData: %s", mime.toLocal8Bit().data());
1334 if (event->mimeData()->hasFormat(u"text/plain"_qs) || event->mimeData()->hasFormat(u"text/uri-list"_qs))
1335 event->acceptProposedAction();
1338 /*****************************************************
1340 * Torrent *
1342 *****************************************************/
1344 // Display a dialog to allow user to add
1345 // torrents to download list
1346 void MainWindow::on_actionOpen_triggered()
1348 Preferences *const pref = Preferences::instance();
1349 // Open File Open Dialog
1350 // Note: it is possible to select more than one file
1351 const QStringList pathsList =
1352 QFileDialog::getOpenFileNames(this, tr("Open Torrent Files"), pref->getMainLastDir().data(),
1353 tr("Torrent Files") + u" (*" + TORRENT_FILE_EXTENSION + u')');
1355 if (pathsList.isEmpty())
1356 return;
1358 const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled();
1360 for (const QString &file : pathsList)
1362 if (useTorrentAdditionDialog)
1363 AddNewTorrentDialog::show(file, this);
1364 else
1365 BitTorrent::Session::instance()->addTorrent(file);
1368 // Save last dir to remember it
1369 const Path topDir {pathsList.at(0)};
1370 const Path parentDir = topDir.parentPath();
1371 pref->setMainLastDir(parentDir.isEmpty() ? topDir : parentDir);
1374 void MainWindow::activate()
1376 if (!m_uiLocked || unlockUI())
1378 show();
1379 activateWindow();
1380 raise();
1384 void MainWindow::optionsSaved()
1386 LogMsg(tr("Options saved."));
1387 loadPreferences();
1390 void MainWindow::showStatusBar(bool show)
1392 if (!show)
1394 // Remove status bar
1395 setStatusBar(nullptr);
1397 else if (!m_statusBar)
1399 // Create status bar
1400 m_statusBar = new StatusBar;
1401 connect(m_statusBar.data(), &StatusBar::connectionButtonClicked, this, &MainWindow::showConnectionSettings);
1402 connect(m_statusBar.data(), &StatusBar::alternativeSpeedsButtonClicked, this, &MainWindow::toggleAlternativeSpeeds);
1403 setStatusBar(m_statusBar);
1407 void MainWindow::showFiltersSidebar(const bool show)
1409 if (show && !m_transferListFiltersWidget)
1411 m_transferListFiltersWidget = new TransferListFiltersWidget(m_splitter, m_transferListWidget, isDownloadTrackerFavicon());
1412 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersAdded, m_transferListFiltersWidget, &TransferListFiltersWidget::addTrackers);
1413 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersRemoved, m_transferListFiltersWidget, &TransferListFiltersWidget::removeTrackers);
1414 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersChanged, m_transferListFiltersWidget, &TransferListFiltersWidget::refreshTrackers);
1415 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackerlessStateChanged, m_transferListFiltersWidget, &TransferListFiltersWidget::changeTrackerless);
1416 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackerEntriesUpdated, m_transferListFiltersWidget, &TransferListFiltersWidget::trackerEntriesUpdated);
1418 m_splitter->insertWidget(0, m_transferListFiltersWidget);
1419 m_splitter->setCollapsible(0, true);
1420 // From https://doc.qt.io/qt-5/qsplitter.html#setSizes:
1421 // Instead, any additional/missing space is distributed amongst the widgets
1422 // according to the relative weight of the sizes.
1423 m_splitter->setStretchFactor(0, 0);
1424 m_splitter->setStretchFactor(1, 1);
1425 m_splitter->setSizes({Preferences::instance()->getFiltersSidebarWidth()});
1427 else if (!show && m_transferListFiltersWidget)
1429 saveSplitterSettings();
1430 delete m_transferListFiltersWidget;
1431 m_transferListFiltersWidget = nullptr;
1435 void MainWindow::loadPreferences()
1437 const Preferences *pref = Preferences::instance();
1439 // General
1440 if (pref->isToolbarDisplayed())
1442 m_ui->toolBar->setVisible(true);
1444 else
1446 // Clear search filter before hiding the top toolbar
1447 m_columnFilterEdit->clear();
1448 m_ui->toolBar->setVisible(false);
1451 showStatusBar(pref->isStatusbarDisplayed());
1453 updatePowerManagementState();
1455 m_transferListWidget->setAlternatingRowColors(pref->useAlternatingRowColors());
1456 m_propertiesWidget->getFilesList()->setAlternatingRowColors(pref->useAlternatingRowColors());
1457 m_propertiesWidget->getTrackerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
1458 m_propertiesWidget->getPeerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
1460 // Queueing System
1461 if (BitTorrent::Session::instance()->isQueueingSystemEnabled())
1463 if (!m_ui->actionDecreaseQueuePos->isVisible())
1465 m_transferListWidget->hideQueuePosColumn(false);
1466 m_ui->actionDecreaseQueuePos->setVisible(true);
1467 m_ui->actionIncreaseQueuePos->setVisible(true);
1468 m_ui->actionTopQueuePos->setVisible(true);
1469 m_ui->actionBottomQueuePos->setVisible(true);
1470 #ifndef Q_OS_MACOS
1471 m_queueSeparator->setVisible(true);
1472 #endif
1473 m_queueSeparatorMenu->setVisible(true);
1476 else
1478 if (m_ui->actionDecreaseQueuePos->isVisible())
1480 m_transferListWidget->hideQueuePosColumn(true);
1481 m_ui->actionDecreaseQueuePos->setVisible(false);
1482 m_ui->actionIncreaseQueuePos->setVisible(false);
1483 m_ui->actionTopQueuePos->setVisible(false);
1484 m_ui->actionBottomQueuePos->setVisible(false);
1485 #ifndef Q_OS_MACOS
1486 m_queueSeparator->setVisible(false);
1487 #endif
1488 m_queueSeparatorMenu->setVisible(false);
1492 // Torrent properties
1493 m_propertiesWidget->reloadPreferences();
1495 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
1496 if (pref->isUpdateCheckEnabled())
1498 if (!m_programUpdateTimer)
1500 m_programUpdateTimer = new QTimer(this);
1501 m_programUpdateTimer->setInterval(24h);
1502 m_programUpdateTimer->setSingleShot(true);
1503 connect(m_programUpdateTimer, &QTimer::timeout, this, [this]() { checkProgramUpdate(false); });
1504 m_programUpdateTimer->start();
1507 else
1509 delete m_programUpdateTimer;
1510 m_programUpdateTimer = nullptr;
1512 #endif
1514 qDebug("GUI settings loaded");
1517 void MainWindow::reloadSessionStats()
1519 const BitTorrent::SessionStatus &status = BitTorrent::Session::instance()->status();
1521 // update global information
1522 #ifdef Q_OS_MACOS
1523 if (status.payloadDownloadRate > 0)
1525 MacUtils::setBadgeLabelText(tr("%1/s", "s is a shorthand for seconds")
1526 .arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate)));
1528 else if (!MacUtils::badgeLabelText().isEmpty())
1530 MacUtils::setBadgeLabelText({});
1532 #else
1533 const auto toolTip = u"%1\n%2"_qs.arg(
1534 tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate, true))
1535 , tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(Utils::Misc::friendlyUnit(status.payloadUploadRate, true)));
1536 app()->desktopIntegration()->setToolTip(toolTip); // tray icon
1537 #endif // Q_OS_MACOS
1539 if (m_displaySpeedInTitle)
1541 setWindowTitle(tr("[D: %1, U: %2] qBittorrent %3", "D = Download; U = Upload; %3 is qBittorrent version")
1542 .arg(Utils::Misc::friendlyUnit(status.payloadDownloadRate, true)
1543 , Utils::Misc::friendlyUnit(status.payloadUploadRate, true)
1544 , QStringLiteral(QBT_VERSION)));
1548 void MainWindow::reloadTorrentStats(const QVector<BitTorrent::Torrent *> &torrents)
1550 if (currentTabWidget() == m_transferListWidget)
1552 if (torrents.contains(m_propertiesWidget->getCurrentTorrent()))
1553 m_propertiesWidget->loadDynamicData();
1557 /*****************************************************
1559 * Utils *
1561 *****************************************************/
1563 void MainWindow::downloadFromURLList(const QStringList &urlList)
1565 const bool useTorrentAdditionDialog = AddNewTorrentDialog::isEnabled();
1566 for (const QString &url : urlList)
1568 if (useTorrentAdditionDialog)
1569 AddNewTorrentDialog::show(url, this);
1570 else
1571 BitTorrent::Session::instance()->addTorrent(url);
1575 /*****************************************************
1577 * Options *
1579 *****************************************************/
1581 QMenu *MainWindow::createDesktopIntegrationMenu()
1583 auto *menu = new QMenu;
1585 #ifndef Q_OS_MACOS
1586 connect(menu, &QMenu::aboutToShow, this, [this]()
1588 m_ui->actionToggleVisibility->setText(isVisible() ? tr("Hide") : tr("Show"));
1591 menu->addAction(m_ui->actionToggleVisibility);
1592 menu->addSeparator();
1593 #endif
1595 menu->addAction(m_ui->actionOpen);
1596 menu->addAction(m_ui->actionDownloadFromURL);
1597 menu->addSeparator();
1599 menu->addAction(m_ui->actionUseAlternativeSpeedLimits);
1600 menu->addAction(m_ui->actionSetGlobalSpeedLimits);
1601 menu->addSeparator();
1603 menu->addAction(m_ui->actionStartAll);
1604 menu->addAction(m_ui->actionPauseAll);
1606 #ifndef Q_OS_MACOS
1607 menu->addSeparator();
1608 menu->addAction(m_ui->actionExit);
1609 #endif
1611 if (m_uiLocked)
1612 menu->setEnabled(false);
1614 return menu;
1617 void MainWindow::updateAltSpeedsBtn(const bool alternative)
1619 m_ui->actionUseAlternativeSpeedLimits->setChecked(alternative);
1622 PropertiesWidget *MainWindow::propertiesWidget() const
1624 return m_propertiesWidget;
1627 // Display Program Options
1628 void MainWindow::on_actionOptions_triggered()
1630 if (m_options)
1632 m_options->activateWindow();
1634 else
1636 m_options = new OptionsDialog(app(), this);
1637 m_options->setAttribute(Qt::WA_DeleteOnClose);
1638 m_options->open();
1642 void MainWindow::on_actionTopToolBar_triggered()
1644 const bool isVisible = static_cast<QAction *>(sender())->isChecked();
1645 m_ui->toolBar->setVisible(isVisible);
1646 Preferences::instance()->setToolbarDisplayed(isVisible);
1649 void MainWindow::on_actionShowStatusbar_triggered()
1651 const bool isVisible = static_cast<QAction *>(sender())->isChecked();
1652 Preferences::instance()->setStatusbarDisplayed(isVisible);
1653 showStatusBar(isVisible);
1656 void MainWindow::on_actionShowFiltersSidebar_triggered(const bool checked)
1658 Preferences *const pref = Preferences::instance();
1659 pref->setFiltersSidebarVisible(checked);
1660 showFiltersSidebar(checked);
1663 void MainWindow::on_actionSpeedInTitleBar_triggered()
1665 m_displaySpeedInTitle = static_cast<QAction *>(sender())->isChecked();
1666 Preferences::instance()->showSpeedInTitleBar(m_displaySpeedInTitle);
1667 if (m_displaySpeedInTitle)
1668 reloadSessionStats();
1669 else
1670 setWindowTitle(QStringLiteral("qBittorrent " QBT_VERSION));
1673 void MainWindow::on_actionRSSReader_triggered()
1675 Preferences::instance()->setRSSWidgetVisible(m_ui->actionRSSReader->isChecked());
1676 displayRSSTab(m_ui->actionRSSReader->isChecked());
1679 void MainWindow::on_actionSearchWidget_triggered()
1681 if (!m_hasPython && m_ui->actionSearchWidget->isChecked())
1683 const Utils::ForeignApps::PythonInfo pyInfo = Utils::ForeignApps::pythonInfo();
1685 // Not installed
1686 if (!pyInfo.isValid())
1688 m_ui->actionSearchWidget->setChecked(false);
1689 Preferences::instance()->setSearchEnabled(false);
1691 #ifdef Q_OS_WIN
1692 const QMessageBox::StandardButton buttonPressed = QMessageBox::question(this, tr("Missing Python Runtime")
1693 , tr("Python is required to use the search engine but it does not seem to be installed.\nDo you want to install it now?")
1694 , (QMessageBox::Yes | QMessageBox::No), QMessageBox::Yes);
1695 if (buttonPressed == QMessageBox::Yes)
1696 installPython();
1697 #else
1698 QMessageBox::information(this, tr("Missing Python Runtime")
1699 , tr("Python is required to use the search engine but it does not seem to be installed."));
1700 #endif
1701 return;
1704 // Check version requirement
1705 if (!pyInfo.isSupportedVersion())
1707 m_ui->actionSearchWidget->setChecked(false);
1708 Preferences::instance()->setSearchEnabled(false);
1710 #ifdef Q_OS_WIN
1711 const QMessageBox::StandardButton buttonPressed = QMessageBox::question(this, tr("Old Python Runtime")
1712 , tr("Your Python version (%1) is outdated. Minimum requirement: %2.\nDo you want to install a newer version now?")
1713 .arg(pyInfo.version.toString(), u"3.5.0")
1714 , (QMessageBox::Yes | QMessageBox::No), QMessageBox::Yes);
1715 if (buttonPressed == QMessageBox::Yes)
1716 installPython();
1717 #else
1718 QMessageBox::information(this, tr("Old Python Runtime")
1719 , tr("Your Python version (%1) is outdated. Please upgrade to latest version for search engines to work.\nMinimum requirement: %2.")
1720 .arg(pyInfo.version.toString(), u"3.5.0"));
1721 #endif
1722 return;
1725 m_hasPython = true;
1726 m_ui->actionSearchWidget->setChecked(true);
1727 Preferences::instance()->setSearchEnabled(true);
1730 displaySearchTab(m_ui->actionSearchWidget->isChecked());
1733 /*****************************************************
1735 * HTTP Downloader *
1737 *****************************************************/
1739 // Display an input dialog to prompt user for
1740 // an url
1741 void MainWindow::on_actionDownloadFromURL_triggered()
1743 if (!m_downloadFromURLDialog)
1745 m_downloadFromURLDialog = new DownloadFromURLDialog(this);
1746 m_downloadFromURLDialog->setAttribute(Qt::WA_DeleteOnClose);
1747 connect(m_downloadFromURLDialog.data(), &DownloadFromURLDialog::urlsReadyToBeDownloaded, this, &MainWindow::downloadFromURLList);
1748 m_downloadFromURLDialog->open();
1752 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
1753 void MainWindow::handleUpdateCheckFinished(ProgramUpdater *updater, const bool invokedByUser)
1755 m_ui->actionCheckForUpdates->setEnabled(true);
1756 m_ui->actionCheckForUpdates->setText(tr("&Check for Updates"));
1757 m_ui->actionCheckForUpdates->setToolTip(tr("Check for program updates"));
1759 const auto cleanup = [this, updater]()
1761 if (m_programUpdateTimer)
1762 m_programUpdateTimer->start();
1763 updater->deleteLater();
1766 const QString newVersion = updater->getNewVersion();
1767 if (!newVersion.isEmpty())
1769 const QString msg {tr("A new version is available.") + u"<br/>"
1770 + tr("Do you want to download %1?").arg(newVersion) + u"<br/><br/>"
1771 + u"<a href=\"https://www.qbittorrent.org/news.php\">%1</a>"_qs.arg(tr("Open changelog..."))};
1772 auto *msgBox = new QMessageBox {QMessageBox::Question, tr("qBittorrent Update Available"), msg
1773 , (QMessageBox::Yes | QMessageBox::No), this};
1774 msgBox->setAttribute(Qt::WA_DeleteOnClose);
1775 msgBox->setAttribute(Qt::WA_ShowWithoutActivating);
1776 msgBox->setDefaultButton(QMessageBox::Yes);
1777 msgBox->setWindowModality(Qt::NonModal);
1778 connect(msgBox, &QMessageBox::buttonClicked, this, [msgBox, updater](QAbstractButton *button)
1780 if (msgBox->buttonRole(button) == QMessageBox::YesRole)
1782 updater->updateProgram();
1785 connect(msgBox, &QDialog::finished, this, cleanup);
1786 msgBox->show();
1788 else
1790 if (invokedByUser)
1792 auto *msgBox = new QMessageBox {QMessageBox::Information, u"qBittorrent"_qs
1793 , tr("No updates available.\nYou are already using the latest version.")
1794 , QMessageBox::Ok, this};
1795 msgBox->setAttribute(Qt::WA_DeleteOnClose);
1796 msgBox->setWindowModality(Qt::NonModal);
1797 connect(msgBox, &QDialog::finished, this, cleanup);
1798 msgBox->show();
1800 else
1802 cleanup();
1806 #endif
1808 void MainWindow::toggleAlternativeSpeeds()
1810 BitTorrent::Session *const session = BitTorrent::Session::instance();
1811 session->setAltGlobalSpeedLimitEnabled(!session->isAltGlobalSpeedLimitEnabled());
1814 void MainWindow::on_actionDonateMoney_triggered()
1816 QDesktopServices::openUrl(QUrl(u"https://www.qbittorrent.org/donate"_qs));
1819 void MainWindow::showConnectionSettings()
1821 on_actionOptions_triggered();
1822 m_options->showConnectionTab();
1825 void MainWindow::minimizeWindow()
1827 setWindowState(windowState() | Qt::WindowMinimized);
1830 void MainWindow::on_actionExecutionLogs_triggered(bool checked)
1832 if (checked)
1834 Q_ASSERT(!m_executionLog);
1835 m_executionLog = new ExecutionLogWidget(executionLogMsgTypes(), m_tabs);
1836 #ifdef Q_OS_MACOS
1837 m_tabs->addTab(m_executionLog, tr("Execution Log"));
1838 #else
1839 const int indexTab = m_tabs->addTab(m_executionLog, tr("Execution Log"));
1840 m_tabs->setTabIcon(indexTab, UIThemeManager::instance()->getIcon(u"help-contents"_qs));
1841 #endif
1843 else
1845 delete m_executionLog;
1848 m_ui->actionNormalMessages->setEnabled(checked);
1849 m_ui->actionInformationMessages->setEnabled(checked);
1850 m_ui->actionWarningMessages->setEnabled(checked);
1851 m_ui->actionCriticalMessages->setEnabled(checked);
1852 setExecutionLogEnabled(checked);
1855 void MainWindow::on_actionNormalMessages_triggered(const bool checked)
1857 if (!m_executionLog)
1858 return;
1860 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::NORMAL, checked);
1861 setExecutionLogMsgTypes(flags);
1864 void MainWindow::on_actionInformationMessages_triggered(const bool checked)
1866 if (!m_executionLog)
1867 return;
1869 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::INFO, checked);
1870 setExecutionLogMsgTypes(flags);
1873 void MainWindow::on_actionWarningMessages_triggered(const bool checked)
1875 if (!m_executionLog)
1876 return;
1878 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::WARNING, checked);
1879 setExecutionLogMsgTypes(flags);
1882 void MainWindow::on_actionCriticalMessages_triggered(const bool checked)
1884 if (!m_executionLog)
1885 return;
1887 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::CRITICAL, checked);
1888 setExecutionLogMsgTypes(flags);
1891 void MainWindow::on_actionAutoExit_toggled(bool enabled)
1893 qDebug() << Q_FUNC_INFO << enabled;
1894 Preferences::instance()->setShutdownqBTWhenDownloadsComplete(enabled);
1897 void MainWindow::on_actionAutoSuspend_toggled(bool enabled)
1899 qDebug() << Q_FUNC_INFO << enabled;
1900 Preferences::instance()->setSuspendWhenDownloadsComplete(enabled);
1903 void MainWindow::on_actionAutoHibernate_toggled(bool enabled)
1905 qDebug() << Q_FUNC_INFO << enabled;
1906 Preferences::instance()->setHibernateWhenDownloadsComplete(enabled);
1909 void MainWindow::on_actionAutoShutdown_toggled(bool enabled)
1911 qDebug() << Q_FUNC_INFO << enabled;
1912 Preferences::instance()->setShutdownWhenDownloadsComplete(enabled);
1915 void MainWindow::updatePowerManagementState()
1917 const bool preventFromSuspendWhenDownloading = Preferences::instance()->preventFromSuspendWhenDownloading();
1918 const bool preventFromSuspendWhenSeeding = Preferences::instance()->preventFromSuspendWhenSeeding();
1920 const QVector<BitTorrent::Torrent *> allTorrents = BitTorrent::Session::instance()->torrents();
1921 const bool inhibitSuspend = std::any_of(allTorrents.cbegin(), allTorrents.cend(), [&](const BitTorrent::Torrent *torrent)
1923 if (preventFromSuspendWhenDownloading && (!torrent->isFinished() && !torrent->isPaused() && !torrent->isErrored() && torrent->hasMetadata()))
1924 return true;
1926 if (preventFromSuspendWhenSeeding && (torrent->isFinished() && !torrent->isPaused()))
1927 return true;
1929 return torrent->isMoving();
1931 m_pwr->setActivityState(inhibitSuspend);
1934 void MainWindow::applyTransferListFilter()
1936 m_transferListWidget->applyFilter(m_columnFilterEdit->text(), m_columnFilterComboBox->currentData().value<TransferListModel::Column>());
1939 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
1940 void MainWindow::checkProgramUpdate(const bool invokedByUser)
1942 if (m_programUpdateTimer)
1943 m_programUpdateTimer->stop();
1945 m_ui->actionCheckForUpdates->setEnabled(false);
1946 m_ui->actionCheckForUpdates->setText(tr("Checking for Updates..."));
1947 m_ui->actionCheckForUpdates->setToolTip(tr("Already checking for program updates in the background"));
1949 auto *updater = new ProgramUpdater(this);
1950 connect(updater, &ProgramUpdater::updateCheckFinished
1951 , this, [this, invokedByUser, updater]()
1953 handleUpdateCheckFinished(updater, invokedByUser);
1955 updater->checkForUpdates();
1957 #endif
1959 #ifdef Q_OS_WIN
1960 void MainWindow::installPython()
1962 setCursor(QCursor(Qt::WaitCursor));
1963 // Download python
1964 #ifdef QBT_APP_64BIT
1965 const auto installerURL = u"https://www.python.org/ftp/python/3.8.10/python-3.8.10-amd64.exe"_qs;
1966 #else
1967 const auto installerURL = u"https://www.python.org/ftp/python/3.8.10/python-3.8.10.exe"_qs;
1968 #endif
1969 Net::DownloadManager::instance()->download(
1970 Net::DownloadRequest(installerURL).saveToFile(true)
1971 , Preferences::instance()->useProxyForGeneralPurposes()
1972 , this, &MainWindow::pythonDownloadFinished);
1975 void MainWindow::pythonDownloadFinished(const Net::DownloadResult &result)
1977 if (result.status != Net::DownloadStatus::Success)
1979 setCursor(QCursor(Qt::ArrowCursor));
1980 QMessageBox::warning(
1981 this, tr("Download error")
1982 , tr("Python setup could not be downloaded, reason: %1.\nPlease install it manually.")
1983 .arg(result.errorString));
1984 return;
1987 setCursor(QCursor(Qt::ArrowCursor));
1988 QProcess installer;
1989 qDebug("Launching Python installer in passive mode...");
1991 const Path exePath = result.filePath + u".exe";
1992 Utils::Fs::renameFile(result.filePath, exePath);
1993 installer.start(exePath.toString(), {u"/passive"_qs});
1995 // Wait for setup to complete
1996 installer.waitForFinished(10 * 60 * 1000);
1998 qDebug("Installer stdout: %s", installer.readAllStandardOutput().data());
1999 qDebug("Installer stderr: %s", installer.readAllStandardError().data());
2000 qDebug("Setup should be complete!");
2002 // Delete temp file
2003 Utils::Fs::removeFile(exePath);
2005 // Reload search engine
2006 if (Utils::ForeignApps::pythonInfo().isSupportedVersion())
2008 m_ui->actionSearchWidget->setChecked(true);
2009 displaySearchTab(true);
2012 #endif // Q_OS_WIN