Don't overwrite stored layout of main window with incorrect one
[qBittorrent.git] / src / gui / mainwindow.cpp
blob14a43ec9981fee1b119bdab3f1bfc7fc72179271
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2022-2024 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 <QtSystemDetection>
34 #include <algorithm>
35 #include <chrono>
37 #include <QAction>
38 #include <QActionGroup>
39 #include <QClipboard>
40 #include <QCloseEvent>
41 #include <QComboBox>
42 #include <QDebug>
43 #include <QDesktopServices>
44 #include <QFileDialog>
45 #include <QFileSystemWatcher>
46 #include <QKeyEvent>
47 #include <QLabel>
48 #include <QMenu>
49 #include <QMessageBox>
50 #include <QMetaObject>
51 #include <QMimeData>
52 #include <QProcess>
53 #include <QPushButton>
54 #include <QShortcut>
55 #include <QSplitter>
56 #include <QStatusBar>
57 #include <QString>
58 #include <QTimer>
60 #include "base/bittorrent/session.h"
61 #include "base/bittorrent/sessionstatus.h"
62 #include "base/global.h"
63 #include "base/net/downloadmanager.h"
64 #include "base/path.h"
65 #include "base/preferences.h"
66 #include "base/rss/rss_folder.h"
67 #include "base/rss/rss_session.h"
68 #include "base/utils/foreignapps.h"
69 #include "base/utils/fs.h"
70 #include "base/utils/misc.h"
71 #include "base/utils/password.h"
72 #include "base/version.h"
73 #include "aboutdialog.h"
74 #include "autoexpandabledialog.h"
75 #include "cookiesdialog.h"
76 #include "desktopintegration.h"
77 #include "downloadfromurldialog.h"
78 #include "executionlogwidget.h"
79 #include "hidabletabwidget.h"
80 #include "interfaces/iguiapplication.h"
81 #include "lineedit.h"
82 #include "optionsdialog.h"
83 #include "powermanagement/powermanagement.h"
84 #include "properties/peerlistwidget.h"
85 #include "properties/propertieswidget.h"
86 #include "properties/proptabbar.h"
87 #include "rss/rsswidget.h"
88 #include "search/searchwidget.h"
89 #include "speedlimitdialog.h"
90 #include "statsdialog.h"
91 #include "statusbar.h"
92 #include "torrentcreatordialog.h"
93 #include "trackerlist/trackerlistwidget.h"
94 #include "transferlistfilterswidget.h"
95 #include "transferlistmodel.h"
96 #include "transferlistwidget.h"
97 #include "ui_mainwindow.h"
98 #include "uithememanager.h"
99 #include "utils.h"
101 #ifdef Q_OS_MACOS
102 #include "macosdockbadge/badger.h"
103 #endif
104 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
105 #include "programupdater.h"
106 #endif
108 using namespace std::chrono_literals;
110 namespace
112 #define SETTINGS_KEY(name) u"GUI/" name
113 #define EXECUTIONLOG_SETTINGS_KEY(name) (SETTINGS_KEY(u"Log/"_s) name)
115 const std::chrono::seconds PREVENT_SUSPEND_INTERVAL {60};
117 bool isTorrentLink(const QString &str)
119 return str.startsWith(u"magnet:", Qt::CaseInsensitive)
120 || str.endsWith(TORRENT_FILE_EXTENSION, Qt::CaseInsensitive)
121 || (!str.startsWith(u"file:", Qt::CaseInsensitive)
122 && Net::DownloadManager::hasSupportedScheme(str));
126 MainWindow::MainWindow(IGUIApplication *app, const WindowState initialState, const QString &titleSuffix)
127 : GUIApplicationComponent(app)
128 , m_ui(new Ui::MainWindow)
129 , m_storeExecutionLogEnabled(EXECUTIONLOG_SETTINGS_KEY(u"Enabled"_s))
130 , m_storeDownloadTrackerFavicon(SETTINGS_KEY(u"DownloadTrackerFavicon"_s))
131 , m_storeExecutionLogTypes(EXECUTIONLOG_SETTINGS_KEY(u"Types"_s), Log::MsgType::ALL)
132 #ifdef Q_OS_MACOS
133 , m_badger(std::make_unique<MacUtils::Badger>())
134 #endif // Q_OS_MACOS
136 m_ui->setupUi(this);
138 setTitleSuffix(titleSuffix);
140 Preferences *const pref = Preferences::instance();
141 m_uiLocked = pref->isUILocked();
142 m_displaySpeedInTitle = pref->speedInTitleBar();
143 // Setting icons
144 #ifndef Q_OS_MACOS
145 setWindowIcon(UIThemeManager::instance()->getIcon(u"qbittorrent"_s));
146 #endif // Q_OS_MACOS
148 #if (defined(Q_OS_UNIX))
149 m_ui->actionOptions->setText(tr("Preferences"));
150 #endif
152 addToolbarContextMenu();
154 m_ui->actionOpen->setIcon(UIThemeManager::instance()->getIcon(u"list-add"_s));
155 m_ui->actionDownloadFromURL->setIcon(UIThemeManager::instance()->getIcon(u"insert-link"_s));
156 m_ui->actionSetGlobalSpeedLimits->setIcon(UIThemeManager::instance()->getIcon(u"speedometer"_s));
157 m_ui->actionCreateTorrent->setIcon(UIThemeManager::instance()->getIcon(u"torrent-creator"_s, u"document-edit"_s));
158 m_ui->actionAbout->setIcon(UIThemeManager::instance()->getIcon(u"help-about"_s));
159 m_ui->actionStatistics->setIcon(UIThemeManager::instance()->getIcon(u"view-statistics"_s));
160 m_ui->actionTopQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-top"_s));
161 m_ui->actionIncreaseQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-up"_s));
162 m_ui->actionDecreaseQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-down"_s));
163 m_ui->actionBottomQueuePos->setIcon(UIThemeManager::instance()->getIcon(u"go-bottom"_s));
164 m_ui->actionDelete->setIcon(UIThemeManager::instance()->getIcon(u"list-remove"_s));
165 m_ui->actionDocumentation->setIcon(UIThemeManager::instance()->getIcon(u"help-contents"_s));
166 m_ui->actionDonateMoney->setIcon(UIThemeManager::instance()->getIcon(u"wallet-open"_s));
167 m_ui->actionExit->setIcon(UIThemeManager::instance()->getIcon(u"application-exit"_s));
168 m_ui->actionLock->setIcon(UIThemeManager::instance()->getIcon(u"object-locked"_s));
169 m_ui->actionOptions->setIcon(UIThemeManager::instance()->getIcon(u"configure"_s, u"preferences-system"_s));
170 m_ui->actionStop->setIcon(UIThemeManager::instance()->getIcon(u"torrent-stop"_s, u"media-playback-pause"_s));
171 m_ui->actionStopAll->setIcon(UIThemeManager::instance()->getIcon(u"torrent-stop"_s, u"media-playback-pause"_s));
172 m_ui->actionStart->setIcon(UIThemeManager::instance()->getIcon(u"torrent-start"_s, u"media-playback-start"_s));
173 m_ui->actionStartAll->setIcon(UIThemeManager::instance()->getIcon(u"torrent-start"_s, u"media-playback-start"_s));
174 m_ui->menuAutoShutdownOnDownloadsCompletion->setIcon(UIThemeManager::instance()->getIcon(u"task-complete"_s, u"application-exit"_s));
175 m_ui->actionManageCookies->setIcon(UIThemeManager::instance()->getIcon(u"browser-cookies"_s, u"preferences-web-browser-cookies"_s));
176 m_ui->menuLog->setIcon(UIThemeManager::instance()->getIcon(u"help-contents"_s));
177 m_ui->actionCheckForUpdates->setIcon(UIThemeManager::instance()->getIcon(u"view-refresh"_s));
179 auto *lockMenu = new QMenu(m_ui->menuView);
180 lockMenu->addAction(tr("&Set Password"), this, &MainWindow::defineUILockPassword);
181 lockMenu->addAction(tr("&Clear Password"), this, &MainWindow::clearUILockPassword);
182 m_ui->actionLock->setMenu(lockMenu);
184 // Creating Bittorrent session
185 updateAltSpeedsBtn(BitTorrent::Session::instance()->isAltGlobalSpeedLimitEnabled());
187 connect(BitTorrent::Session::instance(), &BitTorrent::Session::speedLimitModeChanged, this, &MainWindow::updateAltSpeedsBtn);
189 qDebug("create tabWidget");
190 m_tabs = new HidableTabWidget(this);
191 connect(m_tabs.data(), &QTabWidget::currentChanged, this, &MainWindow::tabChanged);
193 m_splitter = new QSplitter(Qt::Horizontal, this);
194 // vSplitter->setChildrenCollapsible(false);
196 auto *hSplitter = new QSplitter(Qt::Vertical, this);
197 hSplitter->setChildrenCollapsible(false);
198 hSplitter->setFrameShape(QFrame::NoFrame);
200 // Torrent filter
201 m_columnFilterEdit = new LineEdit;
202 m_columnFilterEdit->setPlaceholderText(tr("Filter torrents..."));
203 m_columnFilterEdit->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
204 m_columnFilterEdit->setFixedWidth(200);
205 m_columnFilterEdit->setContextMenuPolicy(Qt::CustomContextMenu);
206 connect(m_columnFilterEdit, &QWidget::customContextMenuRequested, this, &MainWindow::showFilterContextMenu);
207 auto *columnFilterLabel = new QLabel(tr("Filter by:"));
208 m_columnFilterComboBox = new QComboBox;
209 QHBoxLayout *columnFilterLayout = new QHBoxLayout(m_columnFilterWidget);
210 columnFilterLayout->setContentsMargins(0, 0, 0, 0);
211 auto *columnFilterSpacer = new QWidget(this);
212 columnFilterSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
213 columnFilterLayout->addWidget(columnFilterSpacer);
214 columnFilterLayout->addWidget(m_columnFilterEdit);
215 columnFilterLayout->addWidget(columnFilterLabel, 0);
216 columnFilterLayout->addWidget(m_columnFilterComboBox, 0);
217 m_columnFilterWidget = new QWidget(this);
218 m_columnFilterWidget->setLayout(columnFilterLayout);
219 m_columnFilterAction = m_ui->toolBar->insertWidget(m_ui->actionLock, m_columnFilterWidget);
221 auto *spacer = new QWidget(this);
222 spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
223 m_ui->toolBar->insertWidget(m_columnFilterAction, spacer);
225 // Transfer List tab
226 m_transferListWidget = new TransferListWidget(hSplitter, this);
227 m_propertiesWidget = new PropertiesWidget(hSplitter);
228 connect(m_transferListWidget, &TransferListWidget::currentTorrentChanged, m_propertiesWidget, &PropertiesWidget::loadTorrentInfos);
229 hSplitter->addWidget(m_transferListWidget);
230 hSplitter->addWidget(m_propertiesWidget);
231 m_splitter->addWidget(hSplitter);
232 m_splitter->setCollapsible(0, false);
233 m_tabs->addTab(m_splitter,
234 #ifndef Q_OS_MACOS
235 UIThemeManager::instance()->getIcon(u"folder-remote"_s),
236 #endif
237 tr("Transfers"));
238 // Filter types
239 const QVector<TransferListModel::Column> filterTypes = {TransferListModel::Column::TR_NAME, TransferListModel::Column::TR_SAVE_PATH};
240 for (const TransferListModel::Column type : filterTypes)
242 const QString typeName = m_transferListWidget->getSourceModel()->headerData(type, Qt::Horizontal, Qt::DisplayRole).value<QString>();
243 m_columnFilterComboBox->addItem(typeName, type);
245 connect(m_columnFilterComboBox, &QComboBox::currentIndexChanged, this, &MainWindow::applyTransferListFilter);
246 connect(m_columnFilterEdit, &LineEdit::textChanged, this, &MainWindow::applyTransferListFilter);
247 connect(hSplitter, &QSplitter::splitterMoved, this, &MainWindow::saveSettings);
248 connect(m_splitter, &QSplitter::splitterMoved, this, &MainWindow::saveSplitterSettings);
250 #ifdef Q_OS_MACOS
251 // Increase top spacing to avoid tab overlapping
252 m_ui->centralWidgetLayout->addSpacing(8);
253 #endif
255 m_ui->centralWidgetLayout->addWidget(m_tabs);
257 m_queueSeparator = m_ui->toolBar->insertSeparator(m_ui->actionTopQueuePos);
258 m_queueSeparatorMenu = m_ui->menuEdit->insertSeparator(m_ui->actionTopQueuePos);
260 #ifdef Q_OS_MACOS
261 for (QAction *action : asConst(m_ui->toolBar->actions()))
263 if (action->isSeparator())
265 QWidget *spacer = new QWidget(this);
266 spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
267 spacer->setMinimumWidth(16);
268 m_ui->toolBar->insertWidget(action, spacer);
269 m_ui->toolBar->removeAction(action);
273 QWidget *spacer = new QWidget(this);
274 spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
275 spacer->setMinimumWidth(8);
276 m_ui->toolBar->insertWidget(m_ui->actionDownloadFromURL, spacer);
279 QWidget *spacer = new QWidget(this);
280 spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
281 spacer->setMinimumWidth(8);
282 m_ui->toolBar->addWidget(spacer);
284 #endif // Q_OS_MACOS
286 // Transfer list slots
287 connect(m_ui->actionStart, &QAction::triggered, m_transferListWidget, &TransferListWidget::startSelectedTorrents);
288 connect(m_ui->actionStartAll, &QAction::triggered, m_transferListWidget, &TransferListWidget::startAllTorrents);
289 connect(m_ui->actionStop, &QAction::triggered, m_transferListWidget, &TransferListWidget::stopSelectedTorrents);
290 connect(m_ui->actionStopAll, &QAction::triggered, m_transferListWidget, &TransferListWidget::stopAllTorrents);
291 connect(m_ui->actionDelete, &QAction::triggered, m_transferListWidget, &TransferListWidget::softDeleteSelectedTorrents);
292 connect(m_ui->actionTopQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::topQueuePosSelectedTorrents);
293 connect(m_ui->actionIncreaseQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::increaseQueuePosSelectedTorrents);
294 connect(m_ui->actionDecreaseQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::decreaseQueuePosSelectedTorrents);
295 connect(m_ui->actionBottomQueuePos, &QAction::triggered, m_transferListWidget, &TransferListWidget::bottomQueuePosSelectedTorrents);
296 connect(m_ui->actionMinimize, &QAction::triggered, this, &MainWindow::minimizeWindow);
297 connect(m_ui->actionUseAlternativeSpeedLimits, &QAction::triggered, this, &MainWindow::toggleAlternativeSpeeds);
299 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
300 connect(m_ui->actionCheckForUpdates, &QAction::triggered, this, [this]() { checkProgramUpdate(true); });
302 // trigger an early check on startup
303 if (pref->isUpdateCheckEnabled())
304 checkProgramUpdate(false);
305 #else
306 m_ui->actionCheckForUpdates->setVisible(false);
307 #endif
309 // Certain menu items should reside at specific places on macOS.
310 // Qt partially does it on its own, but updates and different languages require tuning.
311 m_ui->actionExit->setMenuRole(QAction::QuitRole);
312 m_ui->actionAbout->setMenuRole(QAction::AboutRole);
313 m_ui->actionCheckForUpdates->setMenuRole(QAction::ApplicationSpecificRole);
314 m_ui->actionOptions->setMenuRole(QAction::PreferencesRole);
316 connect(m_ui->actionManageCookies, &QAction::triggered, this, &MainWindow::manageCookies);
318 // Initialise system sleep inhibition timer
319 m_pwr = new PowerManagement(this);
320 m_preventTimer = new QTimer(this);
321 m_preventTimer->setSingleShot(true);
322 connect(m_preventTimer, &QTimer::timeout, this, &MainWindow::updatePowerManagementState);
323 connect(pref, &Preferences::changed, this, &MainWindow::updatePowerManagementState);
324 updatePowerManagementState();
326 // Configure BT session according to options
327 loadPreferences();
329 connect(BitTorrent::Session::instance(), &BitTorrent::Session::statsUpdated, this, &MainWindow::reloadSessionStats);
330 connect(BitTorrent::Session::instance(), &BitTorrent::Session::torrentsUpdated, this, &MainWindow::reloadTorrentStats);
332 // Accept drag 'n drops
333 setAcceptDrops(true);
334 createKeyboardShortcuts();
336 #ifdef Q_OS_MACOS
337 setUnifiedTitleAndToolBarOnMac(true);
338 #endif
340 // View settings
341 m_ui->actionTopToolBar->setChecked(pref->isToolbarDisplayed());
342 m_ui->actionShowStatusbar->setChecked(pref->isStatusbarDisplayed());
343 m_ui->actionSpeedInTitleBar->setChecked(pref->speedInTitleBar());
344 m_ui->actionRSSReader->setChecked(pref->isRSSWidgetEnabled());
345 m_ui->actionSearchWidget->setChecked(pref->isSearchEnabled());
346 m_ui->actionExecutionLogs->setChecked(isExecutionLogEnabled());
348 const Log::MsgTypes flags = executionLogMsgTypes();
349 m_ui->actionNormalMessages->setChecked(flags.testFlag(Log::NORMAL));
350 m_ui->actionInformationMessages->setChecked(flags.testFlag(Log::INFO));
351 m_ui->actionWarningMessages->setChecked(flags.testFlag(Log::WARNING));
352 m_ui->actionCriticalMessages->setChecked(flags.testFlag(Log::CRITICAL));
354 displayRSSTab(m_ui->actionRSSReader->isChecked());
355 on_actionExecutionLogs_triggered(m_ui->actionExecutionLogs->isChecked());
356 on_actionNormalMessages_triggered(m_ui->actionNormalMessages->isChecked());
357 on_actionInformationMessages_triggered(m_ui->actionInformationMessages->isChecked());
358 on_actionWarningMessages_triggered(m_ui->actionWarningMessages->isChecked());
359 on_actionCriticalMessages_triggered(m_ui->actionCriticalMessages->isChecked());
360 if (m_ui->actionSearchWidget->isChecked())
361 QMetaObject::invokeMethod(this, &MainWindow::on_actionSearchWidget_triggered, Qt::QueuedConnection);
362 // Auto shutdown actions
363 auto *autoShutdownGroup = new QActionGroup(this);
364 autoShutdownGroup->setExclusive(true);
365 autoShutdownGroup->addAction(m_ui->actionAutoShutdownDisabled);
366 autoShutdownGroup->addAction(m_ui->actionAutoExit);
367 autoShutdownGroup->addAction(m_ui->actionAutoShutdown);
368 autoShutdownGroup->addAction(m_ui->actionAutoSuspend);
369 autoShutdownGroup->addAction(m_ui->actionAutoHibernate);
370 #if (!defined(Q_OS_UNIX) || defined(Q_OS_MACOS)) || defined(QBT_USES_DBUS)
371 m_ui->actionAutoShutdown->setChecked(pref->shutdownWhenDownloadsComplete());
372 m_ui->actionAutoSuspend->setChecked(pref->suspendWhenDownloadsComplete());
373 m_ui->actionAutoHibernate->setChecked(pref->hibernateWhenDownloadsComplete());
374 #else
375 m_ui->actionAutoShutdown->setDisabled(true);
376 m_ui->actionAutoSuspend->setDisabled(true);
377 m_ui->actionAutoHibernate->setDisabled(true);
378 #endif
379 m_ui->actionAutoExit->setChecked(pref->shutdownqBTWhenDownloadsComplete());
381 if (!autoShutdownGroup->checkedAction())
382 m_ui->actionAutoShutdownDisabled->setChecked(true);
384 // Load Window state and sizes
385 loadSettings();
387 populateDesktopIntegrationMenu();
388 #ifndef Q_OS_MACOS
389 m_ui->actionLock->setVisible(app->desktopIntegration()->isActive());
390 connect(app->desktopIntegration(), &DesktopIntegration::stateChanged, this, [this, app]()
392 m_ui->actionLock->setVisible(app->desktopIntegration()->isActive());
394 #endif
395 connect(app->desktopIntegration(), &DesktopIntegration::notificationClicked, this, &MainWindow::desktopNotificationClicked);
396 connect(app->desktopIntegration(), &DesktopIntegration::activationRequested, this, [this]()
398 #ifdef Q_OS_MACOS
399 if (!isVisible())
400 activate();
401 #else
402 toggleVisibility();
403 #endif
406 #ifdef Q_OS_MACOS
407 if (initialState == WindowState::Normal)
409 show();
410 activateWindow();
411 raise();
413 else
415 // Make sure the Window is visible if we don't have a tray icon
416 showMinimized();
418 #else
419 if (app->desktopIntegration()->isActive())
421 if ((initialState == WindowState::Normal) && !m_uiLocked)
423 show();
424 activateWindow();
425 raise();
427 else if (initialState == WindowState::Minimized)
429 showMinimized();
430 if (pref->minimizeToTray())
432 hide();
433 if (!pref->minimizeToTrayNotified())
435 app->desktopIntegration()->showNotification(tr("qBittorrent is minimized to tray"), tr("This behavior can be changed in the settings. You won't be reminded again."));
436 pref->setMinimizeToTrayNotified(true);
441 else
443 // Make sure the Window is visible if we don't have a tray icon
444 if (initialState != WindowState::Normal)
446 showMinimized();
448 else
450 show();
451 activateWindow();
452 raise();
455 #endif
457 const bool isFiltersSidebarVisible = pref->isFiltersSidebarVisible();
458 m_ui->actionShowFiltersSidebar->setChecked(isFiltersSidebarVisible);
459 if (isFiltersSidebarVisible)
461 showFiltersSidebar(true);
463 else
465 m_transferListWidget->applyStatusFilter(pref->getTransSelFilter());
466 m_transferListWidget->applyCategoryFilter(QString());
467 m_transferListWidget->applyTagFilter(std::nullopt);
468 m_transferListWidget->applyTrackerFilterAll();
471 // Start watching the executable for updates
472 m_executableWatcher = new QFileSystemWatcher(this);
473 connect(m_executableWatcher, &QFileSystemWatcher::fileChanged, this, &MainWindow::notifyOfUpdate);
474 m_executableWatcher->addPath(qApp->applicationFilePath());
476 m_transferListWidget->setFocus();
478 // Update the number of torrents (tab)
479 updateNbTorrents();
480 connect(m_transferListWidget->getSourceModel(), &QAbstractItemModel::rowsInserted, this, &MainWindow::updateNbTorrents);
481 connect(m_transferListWidget->getSourceModel(), &QAbstractItemModel::rowsRemoved, this, &MainWindow::updateNbTorrents);
483 connect(pref, &Preferences::changed, this, &MainWindow::optionsSaved);
485 qDebug("GUI Built");
488 MainWindow::~MainWindow()
490 delete m_ui;
493 bool MainWindow::isExecutionLogEnabled() const
495 return m_storeExecutionLogEnabled;
498 void MainWindow::setExecutionLogEnabled(const bool value)
500 m_storeExecutionLogEnabled = value;
503 Log::MsgTypes MainWindow::executionLogMsgTypes() const
505 return m_storeExecutionLogTypes;
508 void MainWindow::setExecutionLogMsgTypes(const Log::MsgTypes value)
510 m_executionLog->setMessageTypes(value);
511 m_storeExecutionLogTypes = value;
514 bool MainWindow::isDownloadTrackerFavicon() const
516 return m_storeDownloadTrackerFavicon;
519 void MainWindow::setDownloadTrackerFavicon(const bool value)
521 if (m_transferListFiltersWidget)
522 m_transferListFiltersWidget->setDownloadTrackerFavicon(value);
523 m_storeDownloadTrackerFavicon = value;
526 void MainWindow::setTitleSuffix(const QString &suffix)
528 const auto emDash = QChar(0x2014);
529 const QString separator = u' ' + emDash + u' ';
530 m_windowTitle = QStringLiteral("qBittorrent " QBT_VERSION)
531 + (!suffix.isEmpty() ? (separator + suffix) : QString());
533 setWindowTitle(m_windowTitle);
536 void MainWindow::addToolbarContextMenu()
538 const Preferences *const pref = Preferences::instance();
539 m_toolbarMenu = new QMenu(this);
541 m_ui->toolBar->setContextMenuPolicy(Qt::CustomContextMenu);
542 connect(m_ui->toolBar, &QWidget::customContextMenuRequested, this, &MainWindow::toolbarMenuRequested);
544 QAction *iconsOnly = m_toolbarMenu->addAction(tr("Icons Only"), this, &MainWindow::toolbarIconsOnly);
545 QAction *textOnly = m_toolbarMenu->addAction(tr("Text Only"), this, &MainWindow::toolbarTextOnly);
546 QAction *textBesideIcons = m_toolbarMenu->addAction(tr("Text Alongside Icons"), this, &MainWindow::toolbarTextBeside);
547 QAction *textUnderIcons = m_toolbarMenu->addAction(tr("Text Under Icons"), this, &MainWindow::toolbarTextUnder);
548 QAction *followSystemStyle = m_toolbarMenu->addAction(tr("Follow System Style"), this, &MainWindow::toolbarFollowSystem);
550 auto *textPositionGroup = new QActionGroup(m_toolbarMenu);
551 textPositionGroup->addAction(iconsOnly);
552 iconsOnly->setCheckable(true);
553 textPositionGroup->addAction(textOnly);
554 textOnly->setCheckable(true);
555 textPositionGroup->addAction(textBesideIcons);
556 textBesideIcons->setCheckable(true);
557 textPositionGroup->addAction(textUnderIcons);
558 textUnderIcons->setCheckable(true);
559 textPositionGroup->addAction(followSystemStyle);
560 followSystemStyle->setCheckable(true);
562 const auto buttonStyle = static_cast<Qt::ToolButtonStyle>(pref->getToolbarTextPosition());
563 if ((buttonStyle >= Qt::ToolButtonIconOnly) && (buttonStyle <= Qt::ToolButtonFollowStyle))
564 m_ui->toolBar->setToolButtonStyle(buttonStyle);
565 switch (buttonStyle)
567 case Qt::ToolButtonIconOnly:
568 iconsOnly->setChecked(true);
569 break;
570 case Qt::ToolButtonTextOnly:
571 textOnly->setChecked(true);
572 break;
573 case Qt::ToolButtonTextBesideIcon:
574 textBesideIcons->setChecked(true);
575 break;
576 case Qt::ToolButtonTextUnderIcon:
577 textUnderIcons->setChecked(true);
578 break;
579 default:
580 followSystemStyle->setChecked(true);
584 void MainWindow::manageCookies()
586 auto *cookieDialog = new CookiesDialog(this);
587 cookieDialog->setAttribute(Qt::WA_DeleteOnClose);
588 cookieDialog->open();
591 void MainWindow::toolbarMenuRequested()
593 m_toolbarMenu->popup(QCursor::pos());
596 void MainWindow::toolbarIconsOnly()
598 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonIconOnly);
599 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonIconOnly);
602 void MainWindow::toolbarTextOnly()
604 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextOnly);
605 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonTextOnly);
608 void MainWindow::toolbarTextBeside()
610 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
611 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonTextBesideIcon);
614 void MainWindow::toolbarTextUnder()
616 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
617 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonTextUnderIcon);
620 void MainWindow::toolbarFollowSystem()
622 m_ui->toolBar->setToolButtonStyle(Qt::ToolButtonFollowStyle);
623 Preferences::instance()->setToolbarTextPosition(Qt::ToolButtonFollowStyle);
626 bool MainWindow::defineUILockPassword()
628 bool ok = false;
629 const QString newPassword = AutoExpandableDialog::getText(this, tr("UI lock password")
630 , tr("Please type the UI lock password:"), QLineEdit::Password, {}, &ok);
631 if (!ok)
632 return false;
634 if (newPassword.size() < 3)
636 QMessageBox::warning(this, tr("Invalid password"), tr("The password must be at least 3 characters long"));
637 return false;
640 Preferences::instance()->setUILockPassword(Utils::Password::PBKDF2::generate(newPassword));
641 return true;
644 void MainWindow::clearUILockPassword()
646 const QMessageBox::StandardButton answer = QMessageBox::question(this, tr("Clear the password")
647 , tr("Are you sure you want to clear the password?"), (QMessageBox::Yes | QMessageBox::No), QMessageBox::No);
648 if (answer == QMessageBox::Yes)
649 Preferences::instance()->setUILockPassword({});
652 void MainWindow::on_actionLock_triggered()
654 Preferences *const pref = Preferences::instance();
656 // Check if there is a password
657 if (pref->getUILockPassword().isEmpty())
659 if (!defineUILockPassword())
660 return;
663 // Lock the interface
664 m_uiLocked = true;
665 pref->setUILocked(true);
666 app()->desktopIntegration()->menu()->setEnabled(false);
667 hide();
670 void MainWindow::handleRSSUnreadCountUpdated(int count)
672 m_tabs->setTabText(m_tabs->indexOf(m_rssWidget), tr("RSS (%1)").arg(count));
675 void MainWindow::displayRSSTab(bool enable)
677 if (enable)
679 // RSS tab
680 if (!m_rssWidget)
682 m_rssWidget = new RSSWidget(app(), m_tabs);
683 connect(m_rssWidget.data(), &RSSWidget::unreadCountUpdated, this, &MainWindow::handleRSSUnreadCountUpdated);
684 #ifdef Q_OS_MACOS
685 m_tabs->addTab(m_rssWidget, tr("RSS (%1)").arg(RSS::Session::instance()->rootFolder()->unreadCount()));
686 #else
687 const int indexTab = m_tabs->addTab(m_rssWidget, tr("RSS (%1)").arg(RSS::Session::instance()->rootFolder()->unreadCount()));
688 m_tabs->setTabIcon(indexTab, UIThemeManager::instance()->getIcon(u"application-rss"_s));
689 #endif
692 else
694 delete m_rssWidget;
698 void MainWindow::showFilterContextMenu()
700 const Preferences *pref = Preferences::instance();
702 QMenu *menu = m_columnFilterEdit->createStandardContextMenu();
703 menu->setAttribute(Qt::WA_DeleteOnClose);
704 menu->addSeparator();
706 QAction *useRegexAct = menu->addAction(tr("Use regular expressions"));
707 useRegexAct->setCheckable(true);
708 useRegexAct->setChecked(pref->getRegexAsFilteringPatternForTransferList());
709 connect(useRegexAct, &QAction::toggled, pref, &Preferences::setRegexAsFilteringPatternForTransferList);
710 connect(useRegexAct, &QAction::toggled, this, &MainWindow::applyTransferListFilter);
712 menu->popup(QCursor::pos());
715 void MainWindow::displaySearchTab(bool enable)
717 Preferences::instance()->setSearchEnabled(enable);
718 if (enable)
720 // RSS tab
721 if (!m_searchWidget)
723 m_searchWidget = new SearchWidget(app(), this);
724 m_tabs->insertTab(1, m_searchWidget,
725 #ifndef Q_OS_MACOS
726 UIThemeManager::instance()->getIcon(u"edit-find"_s),
727 #endif
728 tr("Search"));
731 else
733 delete m_searchWidget;
737 void MainWindow::toggleFocusBetweenLineEdits()
739 if (m_columnFilterEdit->hasFocus() && (m_propertiesWidget->tabBar()->currentIndex() == PropTabBar::FilesTab))
741 m_propertiesWidget->contentFilterLine()->setFocus();
742 m_propertiesWidget->contentFilterLine()->selectAll();
744 else
746 m_columnFilterEdit->setFocus();
747 m_columnFilterEdit->selectAll();
751 void MainWindow::updateNbTorrents()
753 m_tabs->setTabText(0, tr("Transfers (%1)").arg(m_transferListWidget->getSourceModel()->rowCount()));
756 void MainWindow::on_actionDocumentation_triggered() const
758 QDesktopServices::openUrl(QUrl(u"https://doc.qbittorrent.org"_s));
761 void MainWindow::tabChanged([[maybe_unused]] const int newTab)
763 // We cannot rely on the index newTab
764 // because the tab order is undetermined now
765 if (m_tabs->currentWidget() == m_splitter)
767 qDebug("Changed tab to transfer list, refreshing the list");
768 m_propertiesWidget->loadDynamicData();
769 m_columnFilterAction->setVisible(true);
770 return;
772 m_columnFilterAction->setVisible(false);
774 if (m_tabs->currentWidget() == m_searchWidget)
776 qDebug("Changed tab to search engine, giving focus to search input");
777 m_searchWidget->giveFocusToSearchInput();
781 void MainWindow::saveSettings() const
783 auto *pref = Preferences::instance();
784 pref->setMainGeometry(saveGeometry());
785 m_propertiesWidget->saveSettings();
788 void MainWindow::saveSplitterSettings() const
790 if (!m_transferListFiltersWidget)
791 return;
793 auto *pref = Preferences::instance();
794 pref->setFiltersSidebarWidth(m_splitter->sizes()[0]);
797 void MainWindow::cleanup()
799 if (!m_neverShown)
801 saveSettings();
802 saveSplitterSettings();
805 // delete RSSWidget explicitly to avoid crash in
806 // handleRSSUnreadCountUpdated() at application shutdown
807 delete m_rssWidget;
809 delete m_executableWatcher;
811 m_preventTimer->stop();
813 #if (defined(Q_OS_WIN) || defined(Q_OS_MACOS))
814 if (m_programUpdateTimer)
815 m_programUpdateTimer->stop();
816 #endif
818 // remove all child widgets
819 while (auto *w = findChild<QWidget *>())
820 delete w;
823 void MainWindow::loadSettings()
825 const auto *pref = Preferences::instance();
827 if (const QByteArray mainGeo = pref->getMainGeometry();
828 !mainGeo.isEmpty() && restoreGeometry(mainGeo))
830 m_posInitialized = true;
834 void MainWindow::desktopNotificationClicked()
836 if (isHidden())
838 if (m_uiLocked)
840 // Ask for UI lock password
841 if (!unlockUI())
842 return;
844 show();
845 if (isMinimized())
846 showNormal();
849 raise();
850 activateWindow();
853 void MainWindow::createKeyboardShortcuts()
855 m_ui->actionCreateTorrent->setShortcut(QKeySequence::New);
856 m_ui->actionOpen->setShortcut(QKeySequence::Open);
857 m_ui->actionDelete->setShortcut(QKeySequence::Delete);
858 m_ui->actionDelete->setShortcutContext(Qt::WidgetShortcut); // nullify its effect: delete key event is handled by respective widgets, not here
859 m_ui->actionDownloadFromURL->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_O);
860 m_ui->actionExit->setShortcut(Qt::CTRL | Qt::Key_Q);
861 #ifdef Q_OS_MACOS
862 m_ui->actionCloseWindow->setShortcut(QKeySequence::Close);
863 #else
864 m_ui->actionCloseWindow->setVisible(false);
865 #endif
867 const auto *switchTransferShortcut = new QShortcut((Qt::ALT | Qt::Key_1), this);
868 connect(switchTransferShortcut, &QShortcut::activated, this, &MainWindow::displayTransferTab);
869 const auto *switchSearchShortcut = new QShortcut((Qt::ALT | Qt::Key_2), this);
870 connect(switchSearchShortcut, &QShortcut::activated, this, qOverload<>(&MainWindow::displaySearchTab));
871 const auto *switchRSSShortcut = new QShortcut((Qt::ALT | Qt::Key_3), this);
872 connect(switchRSSShortcut, &QShortcut::activated, this, qOverload<>(&MainWindow::displayRSSTab));
873 const auto *switchExecutionLogShortcut = new QShortcut((Qt::ALT | Qt::Key_4), this);
874 connect(switchExecutionLogShortcut, &QShortcut::activated, this, &MainWindow::displayExecutionLogTab);
875 const auto *switchSearchFilterShortcut = new QShortcut(QKeySequence::Find, m_transferListWidget);
876 connect(switchSearchFilterShortcut, &QShortcut::activated, this, &MainWindow::toggleFocusBetweenLineEdits);
877 const auto *switchSearchFilterShortcutAlternative = new QShortcut((Qt::CTRL | Qt::Key_E), m_transferListWidget);
878 connect(switchSearchFilterShortcutAlternative, &QShortcut::activated, this, &MainWindow::toggleFocusBetweenLineEdits);
880 m_ui->actionDocumentation->setShortcut(QKeySequence::HelpContents);
881 m_ui->actionOptions->setShortcut(Qt::ALT | Qt::Key_O);
882 m_ui->actionStatistics->setShortcut(Qt::CTRL | Qt::Key_I);
883 m_ui->actionStart->setShortcut(Qt::CTRL | Qt::Key_S);
884 m_ui->actionStartAll->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_S);
885 m_ui->actionStop->setShortcut(Qt::CTRL | Qt::Key_P);
886 m_ui->actionStopAll->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_P);
887 m_ui->actionBottomQueuePos->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_Minus);
888 m_ui->actionDecreaseQueuePos->setShortcut(Qt::CTRL | Qt::Key_Minus);
889 m_ui->actionIncreaseQueuePos->setShortcut(Qt::CTRL | Qt::Key_Plus);
890 m_ui->actionTopQueuePos->setShortcut(Qt::CTRL | Qt::SHIFT | Qt::Key_Plus);
891 #ifdef Q_OS_MACOS
892 m_ui->actionMinimize->setShortcut(Qt::CTRL | Qt::Key_M);
893 addAction(m_ui->actionMinimize);
894 #endif
897 // Keyboard shortcuts slots
898 void MainWindow::displayTransferTab() const
900 m_tabs->setCurrentWidget(m_splitter);
903 void MainWindow::displaySearchTab()
905 if (!m_searchWidget)
907 m_ui->actionSearchWidget->setChecked(true);
908 displaySearchTab(true);
911 m_tabs->setCurrentWidget(m_searchWidget);
914 void MainWindow::displayRSSTab()
916 if (!m_rssWidget)
918 m_ui->actionRSSReader->setChecked(true);
919 displayRSSTab(true);
922 m_tabs->setCurrentWidget(m_rssWidget);
925 void MainWindow::displayExecutionLogTab()
927 if (!m_executionLog)
929 m_ui->actionExecutionLogs->setChecked(true);
930 on_actionExecutionLogs_triggered(true);
933 m_tabs->setCurrentWidget(m_executionLog);
936 // End of keyboard shortcuts slots
938 void MainWindow::on_actionSetGlobalSpeedLimits_triggered()
940 auto *dialog = new SpeedLimitDialog {this};
941 dialog->setAttribute(Qt::WA_DeleteOnClose);
942 dialog->open();
945 // Necessary if we want to close the window
946 // in one time if "close to systray" is enabled
947 void MainWindow::on_actionExit_triggered()
949 // UI locking enforcement.
950 if (isHidden() && m_uiLocked)
951 // Ask for UI lock password
952 if (!unlockUI()) return;
954 m_forceExit = true;
955 close();
958 #ifdef Q_OS_MACOS
959 void MainWindow::on_actionCloseWindow_triggered()
961 // On macOS window close is basically equivalent to window hide.
962 // If you decide to implement this functionality for other OS,
963 // then you will also need ui lock checks like in actionExit.
964 close();
966 #endif
968 QWidget *MainWindow::currentTabWidget() const
970 if (isMinimized() || !isVisible())
971 return nullptr;
972 if (m_tabs->currentIndex() == 0)
973 return m_transferListWidget;
974 return m_tabs->currentWidget();
977 TransferListWidget *MainWindow::transferListWidget() const
979 return m_transferListWidget;
982 bool MainWindow::unlockUI()
984 if (m_unlockDlgShowing)
985 return false;
987 bool ok = false;
988 const QString password = AutoExpandableDialog::getText(this, tr("UI lock password")
989 , tr("Please type the UI lock password:"), QLineEdit::Password, {}, &ok);
990 if (!ok) return false;
992 Preferences *const pref = Preferences::instance();
994 const QByteArray secret = pref->getUILockPassword();
995 if (!Utils::Password::PBKDF2::verify(secret, password))
997 QMessageBox::warning(this, tr("Invalid password"), tr("The password is invalid"));
998 return false;
1001 m_uiLocked = false;
1002 pref->setUILocked(false);
1003 app()->desktopIntegration()->menu()->setEnabled(true);
1004 return true;
1007 void MainWindow::notifyOfUpdate(const QString &)
1009 // Show restart message
1010 m_statusBar->showRestartRequired();
1011 LogMsg(tr("qBittorrent was just updated and needs to be restarted for the changes to be effective.")
1012 , Log::CRITICAL);
1013 // Delete the executable watcher
1014 delete m_executableWatcher;
1015 m_executableWatcher = nullptr;
1018 #ifndef Q_OS_MACOS
1019 // Toggle Main window visibility
1020 void MainWindow::toggleVisibility()
1022 if (isHidden())
1024 if (m_uiLocked && !unlockUI()) // Ask for UI lock password
1025 return;
1027 // Make sure the window is not minimized
1028 setWindowState((windowState() & ~Qt::WindowMinimized) | Qt::WindowActive);
1030 // Then show it
1031 show();
1032 raise();
1033 activateWindow();
1035 else
1037 hide();
1040 #endif // Q_OS_MACOS
1042 // Display About Dialog
1043 void MainWindow::on_actionAbout_triggered()
1045 // About dialog
1046 if (m_aboutDlg)
1048 m_aboutDlg->activateWindow();
1050 else
1052 m_aboutDlg = new AboutDialog(this);
1053 m_aboutDlg->setAttribute(Qt::WA_DeleteOnClose);
1054 m_aboutDlg->show();
1058 void MainWindow::on_actionStatistics_triggered()
1060 if (m_statsDlg)
1062 m_statsDlg->activateWindow();
1064 else
1066 m_statsDlg = new StatsDialog(this);
1067 m_statsDlg->setAttribute(Qt::WA_DeleteOnClose);
1068 m_statsDlg->show();
1072 void MainWindow::showEvent(QShowEvent *e)
1074 qDebug("** Show Event **");
1075 e->accept();
1077 if (isVisible())
1079 // preparations before showing the window
1081 if (m_neverShown)
1083 m_propertiesWidget->readSettings();
1084 m_neverShown = false;
1087 if (currentTabWidget() == m_transferListWidget)
1088 m_propertiesWidget->loadDynamicData();
1090 // Make sure the window is initially centered
1091 if (!m_posInitialized)
1093 move(Utils::Gui::screenCenter(this));
1094 m_posInitialized = true;
1097 else
1099 // to avoid blank screen when restoring from tray icon
1100 show();
1104 void MainWindow::keyPressEvent(QKeyEvent *event)
1106 if (event->matches(QKeySequence::Paste))
1108 const QMimeData *mimeData = QGuiApplication::clipboard()->mimeData();
1110 if (mimeData->hasText())
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 app()->addTorrentManager()->addTorrent(line);
1124 return;
1128 QMainWindow::keyPressEvent(event);
1131 // Called when we close the program
1132 void MainWindow::closeEvent(QCloseEvent *e)
1134 Preferences *const pref = Preferences::instance();
1135 #ifdef Q_OS_MACOS
1136 if (!m_forceExit)
1138 hide();
1139 e->accept();
1140 return;
1142 #else
1143 const bool goToSystrayOnExit = pref->closeToTray();
1144 if (!m_forceExit && app()->desktopIntegration()->isActive() && goToSystrayOnExit && !this->isHidden())
1146 e->ignore();
1147 QMetaObject::invokeMethod(this, &QWidget::hide, Qt::QueuedConnection);
1148 if (!pref->closeToTrayNotified())
1150 app()->desktopIntegration()->showNotification(tr("qBittorrent is closed to tray"), tr("This behavior can be changed in the settings. You won't be reminded again."));
1151 pref->setCloseToTrayNotified(true);
1153 return;
1155 #endif // Q_OS_MACOS
1157 const QVector<BitTorrent::Torrent *> allTorrents = BitTorrent::Session::instance()->torrents();
1158 const bool hasActiveTorrents = std::any_of(allTorrents.cbegin(), allTorrents.cend(), [](BitTorrent::Torrent *torrent)
1160 return torrent->isActive();
1162 if (pref->confirmOnExit() && hasActiveTorrents)
1164 if (e->spontaneous() || m_forceExit)
1166 if (!isVisible())
1167 show();
1168 QMessageBox confirmBox(QMessageBox::Question, tr("Exiting qBittorrent"),
1169 // Split it because the last sentence is used in the WebUI
1170 tr("Some files are currently transferring.") + u'\n' + tr("Are you sure you want to quit qBittorrent?"),
1171 QMessageBox::NoButton, this);
1172 QPushButton *noBtn = confirmBox.addButton(tr("&No"), QMessageBox::NoRole);
1173 confirmBox.addButton(tr("&Yes"), QMessageBox::YesRole);
1174 QPushButton *alwaysBtn = confirmBox.addButton(tr("&Always Yes"), QMessageBox::YesRole);
1175 confirmBox.setDefaultButton(noBtn);
1176 confirmBox.exec();
1177 if (!confirmBox.clickedButton() || (confirmBox.clickedButton() == noBtn))
1179 // Cancel exit
1180 e->ignore();
1181 m_forceExit = false;
1182 return;
1184 if (confirmBox.clickedButton() == alwaysBtn)
1185 // Remember choice
1186 Preferences::instance()->setConfirmOnExit(false);
1190 // Accept exit
1191 e->accept();
1192 qApp->exit();
1195 // Display window to create a torrent
1196 void MainWindow::on_actionCreateTorrent_triggered()
1198 createTorrentTriggered({});
1201 void MainWindow::createTorrentTriggered(const Path &path)
1203 if (m_createTorrentDlg)
1205 m_createTorrentDlg->updateInputPath(path);
1206 m_createTorrentDlg->activateWindow();
1208 else
1210 m_createTorrentDlg = new TorrentCreatorDialog(this, path);
1211 m_createTorrentDlg->setAttribute(Qt::WA_DeleteOnClose);
1212 m_createTorrentDlg->show();
1216 bool MainWindow::event(QEvent *e)
1218 #ifndef Q_OS_MACOS
1219 switch (e->type())
1221 case QEvent::WindowStateChange:
1222 qDebug("Window change event");
1223 // Now check to see if the window is minimised
1224 if (isMinimized())
1226 qDebug("minimisation");
1227 Preferences *const pref = Preferences::instance();
1228 if (app()->desktopIntegration()->isActive() && pref->minimizeToTray())
1230 qDebug() << "Has active window:" << (qApp->activeWindow() != nullptr);
1231 // Check if there is a modal window
1232 const QWidgetList allWidgets = QApplication::allWidgets();
1233 const bool hasModalWindow = std::any_of(allWidgets.cbegin(), allWidgets.cend()
1234 , [](const QWidget *widget) { return widget->isModal(); });
1235 // Iconify if there is no modal window
1236 if (!hasModalWindow)
1238 qDebug("Minimize to Tray enabled, hiding!");
1239 e->ignore();
1240 QMetaObject::invokeMethod(this, &QWidget::hide, Qt::QueuedConnection);
1241 if (!pref->minimizeToTrayNotified())
1243 app()->desktopIntegration()->showNotification(tr("qBittorrent is minimized to tray"), tr("This behavior can be changed in the settings. You won't be reminded again."));
1244 pref->setMinimizeToTrayNotified(true);
1246 return true;
1250 break;
1251 case QEvent::ToolBarChange:
1253 qDebug("MAC: Received a toolbar change event!");
1254 const bool ret = QMainWindow::event(e);
1256 qDebug("MAC: new toolbar visibility is %d", !m_ui->actionTopToolBar->isChecked());
1257 m_ui->actionTopToolBar->toggle();
1258 Preferences::instance()->setToolbarDisplayed(m_ui->actionTopToolBar->isChecked());
1259 return ret;
1261 default:
1262 break;
1264 #endif // Q_OS_MACOS
1266 return QMainWindow::event(e);
1269 // action executed when a file is dropped
1270 void MainWindow::dropEvent(QDropEvent *event)
1272 event->acceptProposedAction();
1274 // remove scheme
1275 QStringList files;
1276 if (event->mimeData()->hasUrls())
1278 for (const QUrl &url : asConst(event->mimeData()->urls()))
1280 if (url.isEmpty())
1281 continue;
1283 files << ((url.scheme().compare(u"file", Qt::CaseInsensitive) == 0)
1284 ? url.toLocalFile()
1285 : url.toString());
1288 else
1290 files = event->mimeData()->text().split(u'\n');
1293 // differentiate ".torrent" files/links & magnet links from others
1294 QStringList torrentFiles, otherFiles;
1295 for (const QString &file : asConst(files))
1297 if (isTorrentLink(file))
1298 torrentFiles << file;
1299 else
1300 otherFiles << file;
1303 // Download torrents
1304 for (const QString &file : asConst(torrentFiles))
1305 app()->addTorrentManager()->addTorrent(file);
1306 if (!torrentFiles.isEmpty()) return;
1308 // Create torrent
1309 for (const QString &file : asConst(otherFiles))
1311 createTorrentTriggered(Path(file));
1313 // currently only handle the first entry
1314 // this is a stub that can be expanded later to create many torrents at once
1315 break;
1319 // Decode if we accept drag 'n drop or not
1320 void MainWindow::dragEnterEvent(QDragEnterEvent *event)
1322 for (const QString &mime : asConst(event->mimeData()->formats()))
1323 qDebug("mimeData: %s", mime.toLocal8Bit().data());
1325 if (event->mimeData()->hasFormat(u"text/plain"_s) || event->mimeData()->hasFormat(u"text/uri-list"_s))
1326 event->acceptProposedAction();
1329 // Display a dialog to allow user to add
1330 // torrents to download list
1331 void MainWindow::on_actionOpen_triggered()
1333 Preferences *const pref = Preferences::instance();
1334 // Open File Open Dialog
1335 // Note: it is possible to select more than one file
1336 const QStringList pathsList = QFileDialog::getOpenFileNames(this, tr("Open Torrent Files")
1337 , pref->getMainLastDir().data(), tr("Torrent Files") + u" (*" + TORRENT_FILE_EXTENSION + u')');
1339 if (pathsList.isEmpty())
1340 return;
1342 for (const QString &file : pathsList)
1343 app()->addTorrentManager()->addTorrent(file);
1345 // Save last dir to remember it
1346 const Path topDir {pathsList.at(0)};
1347 const Path parentDir = topDir.parentPath();
1348 pref->setMainLastDir(parentDir.isEmpty() ? topDir : parentDir);
1351 void MainWindow::activate()
1353 if (!m_uiLocked || unlockUI())
1355 show();
1356 activateWindow();
1357 raise();
1361 void MainWindow::optionsSaved()
1363 LogMsg(tr("Options saved."));
1364 loadPreferences();
1367 void MainWindow::showStatusBar(bool show)
1369 if (!show)
1371 // Remove status bar
1372 setStatusBar(nullptr);
1374 else if (!m_statusBar)
1376 // Create status bar
1377 m_statusBar = new StatusBar;
1378 connect(m_statusBar.data(), &StatusBar::connectionButtonClicked, this, &MainWindow::showConnectionSettings);
1379 connect(m_statusBar.data(), &StatusBar::alternativeSpeedsButtonClicked, this, &MainWindow::toggleAlternativeSpeeds);
1380 setStatusBar(m_statusBar);
1384 void MainWindow::showFiltersSidebar(const bool show)
1386 if (show && !m_transferListFiltersWidget)
1388 m_transferListFiltersWidget = new TransferListFiltersWidget(m_splitter, m_transferListWidget, isDownloadTrackerFavicon());
1389 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersAdded, m_transferListFiltersWidget, &TransferListFiltersWidget::addTrackers);
1390 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersRemoved, m_transferListFiltersWidget, &TransferListFiltersWidget::removeTrackers);
1391 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackersChanged, m_transferListFiltersWidget, &TransferListFiltersWidget::refreshTrackers);
1392 connect(BitTorrent::Session::instance(), &BitTorrent::Session::trackerEntryStatusesUpdated, m_transferListFiltersWidget, &TransferListFiltersWidget::trackerEntryStatusesUpdated);
1394 m_splitter->insertWidget(0, m_transferListFiltersWidget);
1395 m_splitter->setCollapsible(0, true);
1396 // From https://doc.qt.io/qt-5/qsplitter.html#setSizes:
1397 // Instead, any additional/missing space is distributed amongst the widgets
1398 // according to the relative weight of the sizes.
1399 m_splitter->setStretchFactor(0, 0);
1400 m_splitter->setStretchFactor(1, 1);
1401 m_splitter->setSizes({Preferences::instance()->getFiltersSidebarWidth()});
1403 else if (!show && m_transferListFiltersWidget)
1405 saveSplitterSettings();
1406 delete m_transferListFiltersWidget;
1407 m_transferListFiltersWidget = nullptr;
1411 void MainWindow::loadPreferences()
1413 const Preferences *pref = Preferences::instance();
1415 // General
1416 if (pref->isToolbarDisplayed())
1418 m_ui->toolBar->setVisible(true);
1420 else
1422 // Clear search filter before hiding the top toolbar
1423 m_columnFilterEdit->clear();
1424 m_ui->toolBar->setVisible(false);
1427 showStatusBar(pref->isStatusbarDisplayed());
1429 m_transferListWidget->setAlternatingRowColors(pref->useAlternatingRowColors());
1430 m_propertiesWidget->getFilesList()->setAlternatingRowColors(pref->useAlternatingRowColors());
1431 m_propertiesWidget->getTrackerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
1432 m_propertiesWidget->getPeerList()->setAlternatingRowColors(pref->useAlternatingRowColors());
1434 // Queueing System
1435 if (BitTorrent::Session::instance()->isQueueingSystemEnabled())
1437 if (!m_ui->actionDecreaseQueuePos->isVisible())
1439 m_transferListWidget->hideQueuePosColumn(false);
1440 m_ui->actionDecreaseQueuePos->setVisible(true);
1441 m_ui->actionIncreaseQueuePos->setVisible(true);
1442 m_ui->actionTopQueuePos->setVisible(true);
1443 m_ui->actionBottomQueuePos->setVisible(true);
1444 #ifndef Q_OS_MACOS
1445 m_queueSeparator->setVisible(true);
1446 #endif
1447 m_queueSeparatorMenu->setVisible(true);
1450 else
1452 if (m_ui->actionDecreaseQueuePos->isVisible())
1454 m_transferListWidget->hideQueuePosColumn(true);
1455 m_ui->actionDecreaseQueuePos->setVisible(false);
1456 m_ui->actionIncreaseQueuePos->setVisible(false);
1457 m_ui->actionTopQueuePos->setVisible(false);
1458 m_ui->actionBottomQueuePos->setVisible(false);
1459 #ifndef Q_OS_MACOS
1460 m_queueSeparator->setVisible(false);
1461 #endif
1462 m_queueSeparatorMenu->setVisible(false);
1466 // Torrent properties
1467 m_propertiesWidget->reloadPreferences();
1469 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
1470 if (pref->isUpdateCheckEnabled())
1472 if (!m_programUpdateTimer)
1474 m_programUpdateTimer = new QTimer(this);
1475 m_programUpdateTimer->setInterval(24h);
1476 m_programUpdateTimer->setSingleShot(true);
1477 connect(m_programUpdateTimer, &QTimer::timeout, this, [this]() { checkProgramUpdate(false); });
1478 m_programUpdateTimer->start();
1481 else
1483 delete m_programUpdateTimer;
1484 m_programUpdateTimer = nullptr;
1486 #endif
1488 qDebug("GUI settings loaded");
1491 void MainWindow::reloadSessionStats()
1493 const BitTorrent::SessionStatus &status = BitTorrent::Session::instance()->status();
1494 const QString downloadRate = Utils::Misc::friendlyUnit(status.payloadDownloadRate, true);
1495 const QString uploadRate = Utils::Misc::friendlyUnit(status.payloadUploadRate, true);
1497 // update global information
1498 #ifdef Q_OS_MACOS
1499 m_badger->updateSpeed(status.payloadDownloadRate, status.payloadUploadRate);
1500 #else
1501 const auto toolTip = u"%1\n%2"_s.arg(
1502 tr("DL speed: %1", "e.g: Download speed: 10 KiB/s").arg(downloadRate)
1503 , tr("UP speed: %1", "e.g: Upload speed: 10 KiB/s").arg(uploadRate));
1504 app()->desktopIntegration()->setToolTip(toolTip); // tray icon
1505 #endif // Q_OS_MACOS
1507 if (m_displaySpeedInTitle)
1509 const QString title = tr("[D: %1, U: %2] %3", "D = Download; U = Upload; %3 is the rest of the window title")
1510 .arg(downloadRate, uploadRate, m_windowTitle);
1511 setWindowTitle(title);
1515 void MainWindow::reloadTorrentStats(const QVector<BitTorrent::Torrent *> &torrents)
1517 if (currentTabWidget() == m_transferListWidget)
1519 if (torrents.contains(m_propertiesWidget->getCurrentTorrent()))
1520 m_propertiesWidget->loadDynamicData();
1524 void MainWindow::downloadFromURLList(const QStringList &urlList)
1526 for (const QString &url : urlList)
1527 app()->addTorrentManager()->addTorrent(url);
1530 void MainWindow::populateDesktopIntegrationMenu()
1532 auto *menu = app()->desktopIntegration()->menu();
1533 menu->clear();
1535 #ifndef Q_OS_MACOS
1536 connect(menu, &QMenu::aboutToShow, this, [this]()
1538 m_ui->actionToggleVisibility->setText(isVisible() ? tr("Hide") : tr("Show"));
1540 connect(m_ui->actionToggleVisibility, &QAction::triggered, this, &MainWindow::toggleVisibility);
1542 menu->addAction(m_ui->actionToggleVisibility);
1543 menu->addSeparator();
1544 #endif
1546 menu->addAction(m_ui->actionOpen);
1547 menu->addAction(m_ui->actionDownloadFromURL);
1548 menu->addSeparator();
1550 menu->addAction(m_ui->actionUseAlternativeSpeedLimits);
1551 menu->addAction(m_ui->actionSetGlobalSpeedLimits);
1552 menu->addSeparator();
1554 menu->addAction(m_ui->actionStartAll);
1555 menu->addAction(m_ui->actionStopAll);
1557 #ifndef Q_OS_MACOS
1558 menu->addSeparator();
1559 menu->addAction(m_ui->actionExit);
1560 #endif
1562 if (m_uiLocked)
1563 menu->setEnabled(false);
1566 void MainWindow::updateAltSpeedsBtn(const bool alternative)
1568 m_ui->actionUseAlternativeSpeedLimits->setChecked(alternative);
1571 PropertiesWidget *MainWindow::propertiesWidget() const
1573 return m_propertiesWidget;
1576 // Display Program Options
1577 void MainWindow::on_actionOptions_triggered()
1579 if (m_options)
1581 m_options->activateWindow();
1583 else
1585 m_options = new OptionsDialog(app(), this);
1586 m_options->setAttribute(Qt::WA_DeleteOnClose);
1587 m_options->open();
1591 void MainWindow::on_actionTopToolBar_triggered()
1593 const bool isVisible = static_cast<QAction *>(sender())->isChecked();
1594 m_ui->toolBar->setVisible(isVisible);
1595 Preferences::instance()->setToolbarDisplayed(isVisible);
1598 void MainWindow::on_actionShowStatusbar_triggered()
1600 const bool isVisible = static_cast<QAction *>(sender())->isChecked();
1601 Preferences::instance()->setStatusbarDisplayed(isVisible);
1602 showStatusBar(isVisible);
1605 void MainWindow::on_actionShowFiltersSidebar_triggered(const bool checked)
1607 Preferences *const pref = Preferences::instance();
1608 pref->setFiltersSidebarVisible(checked);
1609 showFiltersSidebar(checked);
1612 void MainWindow::on_actionSpeedInTitleBar_triggered()
1614 m_displaySpeedInTitle = static_cast<QAction *>(sender())->isChecked();
1615 Preferences::instance()->showSpeedInTitleBar(m_displaySpeedInTitle);
1616 if (m_displaySpeedInTitle)
1617 reloadSessionStats();
1618 else
1619 setWindowTitle(m_windowTitle);
1622 void MainWindow::on_actionRSSReader_triggered()
1624 Preferences::instance()->setRSSWidgetVisible(m_ui->actionRSSReader->isChecked());
1625 displayRSSTab(m_ui->actionRSSReader->isChecked());
1628 void MainWindow::on_actionSearchWidget_triggered()
1630 if (m_ui->actionSearchWidget->isChecked())
1632 const Utils::ForeignApps::PythonInfo pyInfo = Utils::ForeignApps::pythonInfo();
1634 // Not found
1635 if (!pyInfo.isValid())
1637 m_ui->actionSearchWidget->setChecked(false);
1638 Preferences::instance()->setSearchEnabled(false);
1640 #ifdef Q_OS_WIN
1641 const QMessageBox::StandardButton buttonPressed = QMessageBox::question(this, tr("Missing Python Runtime")
1642 , tr("Python is required to use the search engine but it does not seem to be installed.\nDo you want to install it now?")
1643 , (QMessageBox::Yes | QMessageBox::No), QMessageBox::Yes);
1644 if (buttonPressed == QMessageBox::Yes)
1645 installPython();
1646 #else
1647 QMessageBox::information(this, tr("Missing Python Runtime")
1648 , tr("Python is required to use the search engine but it does not seem to be installed."));
1649 #endif
1650 return;
1653 // Check version requirement
1654 if (!pyInfo.isSupportedVersion())
1656 m_ui->actionSearchWidget->setChecked(false);
1657 Preferences::instance()->setSearchEnabled(false);
1659 #ifdef Q_OS_WIN
1660 const QMessageBox::StandardButton buttonPressed = QMessageBox::question(this, tr("Old Python Runtime")
1661 , tr("Your Python version (%1) is outdated. Minimum requirement: %2.\nDo you want to install a newer version now?")
1662 .arg(pyInfo.version.toString(), u"3.7.0")
1663 , (QMessageBox::Yes | QMessageBox::No), QMessageBox::Yes);
1664 if (buttonPressed == QMessageBox::Yes)
1665 installPython();
1666 #else
1667 QMessageBox::information(this, tr("Old Python Runtime")
1668 , tr("Your Python version (%1) is outdated. Please upgrade to latest version for search engines to work.\nMinimum requirement: %2.")
1669 .arg(pyInfo.version.toString(), u"3.7.0"));
1670 #endif
1671 return;
1674 m_ui->actionSearchWidget->setChecked(true);
1675 Preferences::instance()->setSearchEnabled(true);
1678 displaySearchTab(m_ui->actionSearchWidget->isChecked());
1681 // Display an input dialog to prompt user for
1682 // an url
1683 void MainWindow::on_actionDownloadFromURL_triggered()
1685 if (!m_downloadFromURLDialog)
1687 m_downloadFromURLDialog = new DownloadFromURLDialog(this);
1688 m_downloadFromURLDialog->setAttribute(Qt::WA_DeleteOnClose);
1689 connect(m_downloadFromURLDialog.data(), &DownloadFromURLDialog::urlsReadyToBeDownloaded, this, &MainWindow::downloadFromURLList);
1690 m_downloadFromURLDialog->open();
1694 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
1695 void MainWindow::handleUpdateCheckFinished(ProgramUpdater *updater, const bool invokedByUser)
1697 m_ui->actionCheckForUpdates->setEnabled(true);
1698 m_ui->actionCheckForUpdates->setText(tr("&Check for Updates"));
1699 m_ui->actionCheckForUpdates->setToolTip(tr("Check for program updates"));
1701 const auto cleanup = [this, updater]()
1703 if (m_programUpdateTimer)
1704 m_programUpdateTimer->start();
1705 updater->deleteLater();
1708 const QString newVersion = updater->getNewVersion();
1709 if (!newVersion.isEmpty())
1711 const QString msg {tr("A new version is available.") + u"<br/>"
1712 + tr("Do you want to download %1?").arg(newVersion) + u"<br/><br/>"
1713 + u"<a href=\"https://www.qbittorrent.org/news.php\">%1</a>"_s.arg(tr("Open changelog..."))};
1714 auto *msgBox = new QMessageBox {QMessageBox::Question, tr("qBittorrent Update Available"), msg
1715 , (QMessageBox::Yes | QMessageBox::No), this};
1716 msgBox->setAttribute(Qt::WA_DeleteOnClose);
1717 msgBox->setAttribute(Qt::WA_ShowWithoutActivating);
1718 msgBox->setDefaultButton(QMessageBox::Yes);
1719 msgBox->setWindowModality(Qt::NonModal);
1720 connect(msgBox, &QMessageBox::buttonClicked, this, [msgBox, updater](QAbstractButton *button)
1722 if (msgBox->buttonRole(button) == QMessageBox::YesRole)
1724 updater->updateProgram();
1727 connect(msgBox, &QDialog::finished, this, cleanup);
1728 msgBox->show();
1730 else
1732 if (invokedByUser)
1734 auto *msgBox = new QMessageBox {QMessageBox::Information, u"qBittorrent"_s
1735 , tr("No updates available.\nYou are already using the latest version.")
1736 , QMessageBox::Ok, this};
1737 msgBox->setAttribute(Qt::WA_DeleteOnClose);
1738 msgBox->setWindowModality(Qt::NonModal);
1739 connect(msgBox, &QDialog::finished, this, cleanup);
1740 msgBox->show();
1742 else
1744 cleanup();
1748 #endif
1750 void MainWindow::toggleAlternativeSpeeds()
1752 BitTorrent::Session *const session = BitTorrent::Session::instance();
1753 session->setAltGlobalSpeedLimitEnabled(!session->isAltGlobalSpeedLimitEnabled());
1756 void MainWindow::on_actionDonateMoney_triggered()
1758 QDesktopServices::openUrl(QUrl(u"https://www.qbittorrent.org/donate"_s));
1761 void MainWindow::showConnectionSettings()
1763 on_actionOptions_triggered();
1764 m_options->showConnectionTab();
1767 void MainWindow::minimizeWindow()
1769 setWindowState(windowState() | Qt::WindowMinimized);
1772 void MainWindow::on_actionExecutionLogs_triggered(bool checked)
1774 if (checked)
1776 Q_ASSERT(!m_executionLog);
1777 m_executionLog = new ExecutionLogWidget(executionLogMsgTypes(), m_tabs);
1778 #ifdef Q_OS_MACOS
1779 m_tabs->addTab(m_executionLog, tr("Execution Log"));
1780 #else
1781 const int indexTab = m_tabs->addTab(m_executionLog, tr("Execution Log"));
1782 m_tabs->setTabIcon(indexTab, UIThemeManager::instance()->getIcon(u"help-contents"_s));
1783 #endif
1785 else
1787 delete m_executionLog;
1790 m_ui->actionNormalMessages->setEnabled(checked);
1791 m_ui->actionInformationMessages->setEnabled(checked);
1792 m_ui->actionWarningMessages->setEnabled(checked);
1793 m_ui->actionCriticalMessages->setEnabled(checked);
1794 setExecutionLogEnabled(checked);
1797 void MainWindow::on_actionNormalMessages_triggered(const bool checked)
1799 if (!m_executionLog)
1800 return;
1802 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::NORMAL, checked);
1803 setExecutionLogMsgTypes(flags);
1806 void MainWindow::on_actionInformationMessages_triggered(const bool checked)
1808 if (!m_executionLog)
1809 return;
1811 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::INFO, checked);
1812 setExecutionLogMsgTypes(flags);
1815 void MainWindow::on_actionWarningMessages_triggered(const bool checked)
1817 if (!m_executionLog)
1818 return;
1820 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::WARNING, checked);
1821 setExecutionLogMsgTypes(flags);
1824 void MainWindow::on_actionCriticalMessages_triggered(const bool checked)
1826 if (!m_executionLog)
1827 return;
1829 const Log::MsgTypes flags = executionLogMsgTypes().setFlag(Log::CRITICAL, checked);
1830 setExecutionLogMsgTypes(flags);
1833 void MainWindow::on_actionAutoExit_toggled(bool enabled)
1835 qDebug() << Q_FUNC_INFO << enabled;
1836 Preferences::instance()->setShutdownqBTWhenDownloadsComplete(enabled);
1839 void MainWindow::on_actionAutoSuspend_toggled(bool enabled)
1841 qDebug() << Q_FUNC_INFO << enabled;
1842 Preferences::instance()->setSuspendWhenDownloadsComplete(enabled);
1845 void MainWindow::on_actionAutoHibernate_toggled(bool enabled)
1847 qDebug() << Q_FUNC_INFO << enabled;
1848 Preferences::instance()->setHibernateWhenDownloadsComplete(enabled);
1851 void MainWindow::on_actionAutoShutdown_toggled(bool enabled)
1853 qDebug() << Q_FUNC_INFO << enabled;
1854 Preferences::instance()->setShutdownWhenDownloadsComplete(enabled);
1857 void MainWindow::updatePowerManagementState() const
1859 const auto *pref = Preferences::instance();
1860 const bool preventFromSuspendWhenDownloading = pref->preventFromSuspendWhenDownloading();
1861 const bool preventFromSuspendWhenSeeding = pref->preventFromSuspendWhenSeeding();
1863 const QVector<BitTorrent::Torrent *> allTorrents = BitTorrent::Session::instance()->torrents();
1864 const bool inhibitSuspend = std::any_of(allTorrents.cbegin(), allTorrents.cend(), [&](const BitTorrent::Torrent *torrent)
1866 if (preventFromSuspendWhenDownloading && (!torrent->isFinished() && !torrent->isStopped() && !torrent->isErrored() && torrent->hasMetadata()))
1867 return true;
1869 if (preventFromSuspendWhenSeeding && (torrent->isFinished() && !torrent->isStopped()))
1870 return true;
1872 return torrent->isMoving();
1874 m_pwr->setActivityState(inhibitSuspend);
1876 m_preventTimer->start(PREVENT_SUSPEND_INTERVAL);
1879 void MainWindow::applyTransferListFilter()
1881 m_transferListWidget->applyFilter(m_columnFilterEdit->text(), m_columnFilterComboBox->currentData().value<TransferListModel::Column>());
1884 #if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
1885 void MainWindow::checkProgramUpdate(const bool invokedByUser)
1887 if (m_programUpdateTimer)
1888 m_programUpdateTimer->stop();
1890 m_ui->actionCheckForUpdates->setEnabled(false);
1891 m_ui->actionCheckForUpdates->setText(tr("Checking for Updates..."));
1892 m_ui->actionCheckForUpdates->setToolTip(tr("Already checking for program updates in the background"));
1894 auto *updater = new ProgramUpdater(this);
1895 connect(updater, &ProgramUpdater::updateCheckFinished
1896 , this, [this, invokedByUser, updater]()
1898 handleUpdateCheckFinished(updater, invokedByUser);
1900 updater->checkForUpdates();
1902 #endif
1904 #ifdef Q_OS_WIN
1905 void MainWindow::installPython()
1907 setCursor(QCursor(Qt::WaitCursor));
1908 // Download python
1909 const auto installerURL = u"https://www.python.org/ftp/python/3.10.11/python-3.10.11-amd64.exe"_s;
1910 Net::DownloadManager::instance()->download(
1911 Net::DownloadRequest(installerURL).saveToFile(true)
1912 , Preferences::instance()->useProxyForGeneralPurposes()
1913 , this, &MainWindow::pythonDownloadFinished);
1916 void MainWindow::pythonDownloadFinished(const Net::DownloadResult &result)
1918 if (result.status != Net::DownloadStatus::Success)
1920 setCursor(QCursor(Qt::ArrowCursor));
1921 QMessageBox::warning(
1922 this, tr("Download error")
1923 , tr("Python setup could not be downloaded, reason: %1.\nPlease install it manually.")
1924 .arg(result.errorString));
1925 return;
1928 setCursor(QCursor(Qt::ArrowCursor));
1929 QProcess installer;
1930 qDebug("Launching Python installer in passive mode...");
1932 const Path exePath = result.filePath + u".exe";
1933 Utils::Fs::renameFile(result.filePath, exePath);
1934 installer.start(exePath.toString(), {u"/passive"_s});
1936 // Wait for setup to complete
1937 installer.waitForFinished(10 * 60 * 1000);
1939 qDebug("Installer stdout: %s", installer.readAllStandardOutput().data());
1940 qDebug("Installer stderr: %s", installer.readAllStandardError().data());
1941 qDebug("Setup should be complete!");
1943 // Delete temp file
1944 Utils::Fs::removeFile(exePath);
1946 // Reload search engine
1947 if (Utils::ForeignApps::pythonInfo().isSupportedVersion())
1949 m_ui->actionSearchWidget->setChecked(true);
1950 displaySearchTab(true);
1953 #endif // Q_OS_WIN