2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2022-2023 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2012 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 "addnewtorrentdialog.h"
40 #include <QFileDialog>
42 #include <QMessageBox>
43 #include <QPushButton>
45 #include <QSignalBlocker>
51 #include "base/bittorrent/addtorrentparams.h"
52 #include "base/bittorrent/downloadpriority.h"
53 #include "base/bittorrent/infohash.h"
54 #include "base/bittorrent/session.h"
55 #include "base/bittorrent/torrent.h"
56 #include "base/bittorrent/torrentcontenthandler.h"
57 #include "base/bittorrent/torrentcontentlayout.h"
58 #include "base/bittorrent/torrentdescriptor.h"
59 #include "base/global.h"
60 #include "base/preferences.h"
61 #include "base/settingsstorage.h"
62 #include "base/torrentfileguard.h"
63 #include "base/utils/compare.h"
64 #include "base/utils/fs.h"
65 #include "base/utils/misc.h"
66 #include "base/utils/string.h"
68 #include "torrenttagsdialog.h"
70 #include "ui_addnewtorrentdialog.h"
74 #define SETTINGS_KEY(name) u"AddNewTorrentDialog/" name
75 const QString KEY_SAVEPATHHISTORY
= SETTINGS_KEY(u
"SavePathHistory"_s
);
76 const QString KEY_DOWNLOADPATHHISTORY
= SETTINGS_KEY(u
"DownloadPathHistory"_s
);
79 inline SettingsStorage
*settings()
81 return SettingsStorage::instance();
84 // savePath is a folder, not an absolute file path
85 int indexOfPath(const FileSystemPathComboEdit
*fsPathEdit
, const Path
&savePath
)
87 for (int i
= 0; i
< fsPathEdit
->count(); ++i
)
89 if (fsPathEdit
->item(i
) == savePath
)
95 qint64
queryFreeDiskSpace(const Path
&path
)
97 const Path root
= path
.rootItem();
99 qint64 freeSpace
= Utils::Fs::freeDiskSpaceOnPath(current
);
101 // for non-existent directories (which will be created on demand) `Utils::Fs::freeDiskSpaceOnPath`
102 // will return invalid value so instead query its parent/ancestor paths
103 while ((freeSpace
< 0) && (current
!= root
))
105 current
= current
.parentPath();
106 freeSpace
= Utils::Fs::freeDiskSpaceOnPath(current
);
111 void setPath(FileSystemPathComboEdit
*fsPathEdit
, const Path
&newPath
)
113 int existingIndex
= indexOfPath(fsPathEdit
, newPath
);
114 if (existingIndex
< 0)
116 // New path, prepend to combo box
117 fsPathEdit
->insertItem(0, newPath
);
121 fsPathEdit
->setCurrentIndex(existingIndex
);
124 void updatePathHistory(const QString
&settingsKey
, const Path
&path
, const int maxLength
)
126 // Add last used save path to the front of history
128 auto pathList
= settings()->loadValue
<QStringList
>(settingsKey
);
130 const int selectedSavePathIndex
= pathList
.indexOf(path
.toString());
131 if (selectedSavePathIndex
> -1)
132 pathList
.move(selectedSavePathIndex
, 0);
134 pathList
.prepend(path
.toString());
136 settings()->storeValue(settingsKey
, QStringList(pathList
.mid(0, maxLength
)));
140 class AddNewTorrentDialog::TorrentContentAdaptor final
141 : public BitTorrent::TorrentContentHandler
144 TorrentContentAdaptor(const BitTorrent::TorrentInfo
&torrentInfo
, PathList
&filePaths
145 , QVector
<BitTorrent::DownloadPriority
> &filePriorities
, std::function
<void ()> onFilePrioritiesChanged
)
146 : m_torrentInfo
{torrentInfo
}
147 , m_filePaths
{filePaths
}
148 , m_filePriorities
{filePriorities
}
149 , m_onFilePrioritiesChanged
{std::move(onFilePrioritiesChanged
)}
151 Q_ASSERT(filePaths
.isEmpty() || (filePaths
.size() == m_torrentInfo
.filesCount()));
153 m_originalRootFolder
= Path::findRootFolder(m_torrentInfo
.filePaths());
154 m_currentContentLayout
= (m_originalRootFolder
.isEmpty()
155 ? BitTorrent::TorrentContentLayout::NoSubfolder
156 : BitTorrent::TorrentContentLayout::Subfolder
);
158 if (const int fileCount
= filesCount(); !m_filePriorities
.isEmpty() && (fileCount
>= 0))
159 m_filePriorities
.resize(fileCount
, BitTorrent::DownloadPriority::Normal
);
162 bool hasMetadata() const override
164 return m_torrentInfo
.isValid();
167 int filesCount() const override
169 return m_torrentInfo
.filesCount();
172 qlonglong
fileSize(const int index
) const override
174 Q_ASSERT((index
>= 0) && (index
< filesCount()));
175 return m_torrentInfo
.fileSize(index
);
178 Path
filePath(const int index
) const override
180 Q_ASSERT((index
>= 0) && (index
< filesCount()));
181 return (m_filePaths
.isEmpty() ? m_torrentInfo
.filePath(index
) : m_filePaths
.at(index
));
184 PathList
filePaths() const
186 return (m_filePaths
.isEmpty() ? m_torrentInfo
.filePaths() : m_filePaths
);
189 void renameFile(const int index
, const Path
&newFilePath
) override
191 Q_ASSERT((index
>= 0) && (index
< filesCount()));
192 const Path currentFilePath
= filePath(index
);
193 if (currentFilePath
== newFilePath
)
196 if (m_filePaths
.isEmpty())
197 m_filePaths
= m_torrentInfo
.filePaths();
199 m_filePaths
[index
] = newFilePath
;
202 void applyContentLayout(const BitTorrent::TorrentContentLayout contentLayout
)
204 Q_ASSERT(hasMetadata());
205 Q_ASSERT(!m_filePaths
.isEmpty());
207 const auto originalContentLayout
= (m_originalRootFolder
.isEmpty()
208 ? BitTorrent::TorrentContentLayout::NoSubfolder
209 : BitTorrent::TorrentContentLayout::Subfolder
);
210 const auto newContentLayout
= ((contentLayout
== BitTorrent::TorrentContentLayout::Original
)
211 ? originalContentLayout
: contentLayout
);
212 if (newContentLayout
!= m_currentContentLayout
)
214 if (newContentLayout
== BitTorrent::TorrentContentLayout::NoSubfolder
)
216 Path::stripRootFolder(m_filePaths
);
220 const auto rootFolder
= ((originalContentLayout
== BitTorrent::TorrentContentLayout::Subfolder
)
221 ? m_originalRootFolder
: m_filePaths
.at(0).removedExtension());
222 Path::addRootFolder(m_filePaths
, rootFolder
);
225 m_currentContentLayout
= newContentLayout
;
229 QVector
<BitTorrent::DownloadPriority
> filePriorities() const override
231 return m_filePriorities
.isEmpty()
232 ? QVector
<BitTorrent::DownloadPriority
>(filesCount(), BitTorrent::DownloadPriority::Normal
)
236 QVector
<qreal
> filesProgress() const override
238 return QVector
<qreal
>(filesCount(), 0);
241 QVector
<qreal
> availableFileFractions() const override
243 return QVector
<qreal
>(filesCount(), 0);
246 void fetchAvailableFileFractions(std::function
<void (QVector
<qreal
>)> resultHandler
) const override
248 resultHandler(availableFileFractions());
251 void prioritizeFiles(const QVector
<BitTorrent::DownloadPriority
> &priorities
) override
253 Q_ASSERT(priorities
.size() == filesCount());
254 m_filePriorities
= priorities
;
255 if (m_onFilePrioritiesChanged
)
256 m_onFilePrioritiesChanged();
259 Path
actualStorageLocation() const override
264 Path
actualFilePath([[maybe_unused
]] int fileIndex
) const override
269 void flushCache() const override
274 const BitTorrent::TorrentInfo
&m_torrentInfo
;
275 PathList
&m_filePaths
;
276 QVector
<BitTorrent::DownloadPriority
> &m_filePriorities
;
277 std::function
<void ()> m_onFilePrioritiesChanged
;
278 Path m_originalRootFolder
;
279 BitTorrent::TorrentContentLayout m_currentContentLayout
;
282 struct AddNewTorrentDialog::Context
284 BitTorrent::TorrentDescriptor torrentDescr
;
285 BitTorrent::AddTorrentParams torrentParams
;
288 AddNewTorrentDialog::AddNewTorrentDialog(const BitTorrent::TorrentDescriptor
&torrentDescr
289 , const BitTorrent::AddTorrentParams
&inParams
, QWidget
*parent
)
291 , m_ui
{new Ui::AddNewTorrentDialog
}
292 , m_filterLine
{new LineEdit(this)}
293 , m_storeDialogSize
{SETTINGS_KEY(u
"DialogSize"_s
)}
294 , m_storeDefaultCategory
{SETTINGS_KEY(u
"DefaultCategory"_s
)}
295 , m_storeRememberLastSavePath
{SETTINGS_KEY(u
"RememberLastSavePath"_s
)}
296 , m_storeTreeHeaderState
{u
"GUI/Qt6/" SETTINGS_KEY(u
"TreeHeaderState"_s
)}
297 , m_storeSplitterState
{u
"GUI/Qt6/" SETTINGS_KEY(u
"SplitterState"_s
)}
301 m_ui
->savePath
->setMode(FileSystemPathEdit::Mode::DirectorySave
);
302 m_ui
->savePath
->setDialogCaption(tr("Choose save path"));
303 m_ui
->savePath
->setMaxVisibleItems(20);
305 m_ui
->downloadPath
->setMode(FileSystemPathEdit::Mode::DirectorySave
);
306 m_ui
->downloadPath
->setDialogCaption(tr("Choose save path"));
307 m_ui
->downloadPath
->setMaxVisibleItems(20);
309 m_ui
->stopConditionComboBox
->setToolTip(
310 u
"<html><body><p><b>" + tr("None") + u
"</b> - " + tr("No stop condition is set.") + u
"</p><p><b>"
311 + tr("Metadata received") + u
"</b> - " + tr("Torrent will stop after metadata is received.")
312 + u
" <em>" + tr("Torrents that have metadata initially will be added as stopped.") + u
"</em></p><p><b>"
313 + tr("Files checked") + u
"</b> - " + tr("Torrent will stop after files are initially checked.")
314 + u
" <em>" + tr("This will also download metadata if it wasn't there initially.") + u
"</em></p></body></html>");
315 m_ui
->stopConditionComboBox
->addItem(tr("None"), QVariant::fromValue(BitTorrent::Torrent::StopCondition::None
));
316 m_ui
->stopConditionComboBox
->addItem(tr("Files checked"), QVariant::fromValue(BitTorrent::Torrent::StopCondition::FilesChecked
));
318 m_ui
->checkBoxRememberLastSavePath
->setChecked(m_storeRememberLastSavePath
);
319 m_ui
->doNotDeleteTorrentCheckBox
->setVisible(TorrentFileGuard::autoDeleteMode() != TorrentFileGuard::Never
);
321 // Torrent content filtering
322 m_filterLine
->setPlaceholderText(tr("Filter files..."));
323 m_filterLine
->setSizePolicy(QSizePolicy::Expanding
, QSizePolicy::Fixed
);
324 m_ui
->contentFilterLayout
->insertWidget(3, m_filterLine
);
325 const auto *focusSearchHotkey
= new QShortcut(QKeySequence::Find
, this);
326 connect(focusSearchHotkey
, &QShortcut::activated
, this, [this]()
328 m_filterLine
->setFocus();
329 m_filterLine
->selectAll();
334 if (const QByteArray state
= m_storeTreeHeaderState
; !state
.isEmpty())
335 m_ui
->contentTreeView
->header()->restoreState(state
);
336 // Hide useless columns after loading the header state
337 m_ui
->contentTreeView
->hideColumn(TorrentContentWidget::Progress
);
338 m_ui
->contentTreeView
->hideColumn(TorrentContentWidget::Remaining
);
339 m_ui
->contentTreeView
->hideColumn(TorrentContentWidget::Availability
);
340 m_ui
->contentTreeView
->setColumnsVisibilityMode(TorrentContentWidget::ColumnsVisibilityMode::Locked
);
341 m_ui
->contentTreeView
->setDoubleClickAction(TorrentContentWidget::DoubleClickAction::Rename
);
343 connect(m_ui
->buttonBox
, &QDialogButtonBox::accepted
, this, &QDialog::accept
);
344 connect(m_ui
->buttonBox
, &QDialogButtonBox::rejected
, this, &QDialog::reject
);
345 connect(m_ui
->buttonSave
, &QPushButton::clicked
, this, &AddNewTorrentDialog::saveTorrentFile
);
346 connect(m_ui
->savePath
, &FileSystemPathEdit::selectedPathChanged
, this, &AddNewTorrentDialog::onSavePathChanged
);
347 connect(m_ui
->downloadPath
, &FileSystemPathEdit::selectedPathChanged
, this, &AddNewTorrentDialog::onDownloadPathChanged
);
348 connect(m_ui
->groupBoxDownloadPath
, &QGroupBox::toggled
, this, &AddNewTorrentDialog::onUseDownloadPathChanged
);
349 connect(m_ui
->comboTMM
, &QComboBox::currentIndexChanged
, this, &AddNewTorrentDialog::TMMChanged
);
350 connect(m_ui
->startTorrentCheckBox
, &QCheckBox::toggled
, this, [this](const bool checked
)
352 m_ui
->stopConditionLabel
->setEnabled(checked
);
353 m_ui
->stopConditionComboBox
->setEnabled(checked
);
355 connect(m_ui
->contentLayoutComboBox
, &QComboBox::currentIndexChanged
, this, &AddNewTorrentDialog::contentLayoutChanged
);
356 connect(m_ui
->categoryComboBox
, &QComboBox::currentIndexChanged
, this, &AddNewTorrentDialog::categoryChanged
);
357 connect(m_ui
->tagsEditButton
, &QAbstractButton::clicked
, this, [this]
359 auto *dlg
= new TorrentTagsDialog(m_currentContext
->torrentParams
.tags
, this);
360 dlg
->setAttribute(Qt::WA_DeleteOnClose
);
361 connect(dlg
, &TorrentTagsDialog::accepted
, this, [this, dlg
]
363 m_currentContext
->torrentParams
.tags
= dlg
->tags();
364 m_ui
->tagsLineEdit
->setText(Utils::String::joinIntoString(m_currentContext
->torrentParams
.tags
, u
", "_s
));
368 connect(m_filterLine
, &LineEdit::textChanged
, m_ui
->contentTreeView
, &TorrentContentWidget::setFilterPattern
);
369 connect(m_ui
->buttonSelectAll
, &QPushButton::clicked
, m_ui
->contentTreeView
, &TorrentContentWidget::checkAll
);
370 connect(m_ui
->buttonSelectNone
, &QPushButton::clicked
, m_ui
->contentTreeView
, &TorrentContentWidget::checkNone
);
371 connect(Preferences::instance(), &Preferences::changed
, []
373 const int length
= Preferences::instance()->addNewTorrentDialogSavePathHistoryLength();
374 settings()->storeValue(KEY_SAVEPATHHISTORY
375 , QStringList(settings()->loadValue
<QStringList
>(KEY_SAVEPATHHISTORY
).mid(0, length
)));
378 setCurrentContext(std::make_shared
<Context
>(Context
{torrentDescr
, inParams
}));
381 AddNewTorrentDialog::~AddNewTorrentDialog()
387 bool AddNewTorrentDialog::isDoNotDeleteTorrentChecked() const
389 return m_ui
->doNotDeleteTorrentCheckBox
->isChecked();
392 void AddNewTorrentDialog::loadState()
394 if (const QSize dialogSize
= m_storeDialogSize
; dialogSize
.isValid())
397 m_ui
->splitter
->restoreState(m_storeSplitterState
);;
400 void AddNewTorrentDialog::saveState()
402 Q_ASSERT(m_currentContext
);
403 if (!m_currentContext
) [[unlikely
]]
406 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
407 const bool hasMetadata
= torrentDescr
.info().has_value();
409 m_storeDialogSize
= size();
410 m_storeSplitterState
= m_ui
->splitter
->saveState();
412 m_storeTreeHeaderState
= m_ui
->contentTreeView
->header()->saveState();
415 void AddNewTorrentDialog::showEvent(QShowEvent
*event
)
417 QDialog::showEvent(event
);
418 if (!Preferences::instance()->isAddNewTorrentDialogTopLevel())
425 void AddNewTorrentDialog::setCurrentContext(const std::shared_ptr
<Context
> context
)
428 if (!context
) [[unlikely
]]
431 m_currentContext
= context
;
433 const QSignalBlocker comboTMMSignalBlocker
{m_ui
->comboTMM
};
434 const QSignalBlocker startTorrentCheckBoxSignalBlocker
{m_ui
->startTorrentCheckBox
};
435 const QSignalBlocker contentLayoutComboBoxSignalBlocker
{m_ui
->contentLayoutComboBox
};
436 const QSignalBlocker categoryComboBoxSignalBlocker
{m_ui
->categoryComboBox
};
438 const BitTorrent::AddTorrentParams
&addTorrentParams
= m_currentContext
->torrentParams
;
439 const auto *session
= BitTorrent::Session::instance();
441 // TODO: set dialog file properties using m_torrentParams.filePriorities
443 m_ui
->comboTMM
->setCurrentIndex(addTorrentParams
.useAutoTMM
.value_or(!session
->isAutoTMMDisabledByDefault()) ? 1 : 0);
444 m_ui
->addToQueueTopCheckBox
->setChecked(addTorrentParams
.addToQueueTop
.value_or(session
->isAddTorrentToQueueTop()));
445 m_ui
->startTorrentCheckBox
->setChecked(!addTorrentParams
.addStopped
.value_or(session
->isAddTorrentStopped()));
446 m_ui
->stopConditionLabel
->setEnabled(m_ui
->startTorrentCheckBox
->isChecked());
447 m_ui
->stopConditionComboBox
->setEnabled(m_ui
->startTorrentCheckBox
->isChecked());
448 m_ui
->contentLayoutComboBox
->setCurrentIndex(
449 static_cast<int>(addTorrentParams
.contentLayout
.value_or(session
->torrentContentLayout())));
450 m_ui
->sequentialCheckBox
->setChecked(addTorrentParams
.sequential
);
451 m_ui
->firstLastCheckBox
->setChecked(addTorrentParams
.firstLastPiecePriority
);
452 m_ui
->skipCheckingCheckBox
->setChecked(addTorrentParams
.skipChecking
);
453 m_ui
->tagsLineEdit
->setText(Utils::String::joinIntoString(addTorrentParams
.tags
, u
", "_s
));
456 QStringList categories
= session
->categories();
457 std::sort(categories
.begin(), categories
.end(), Utils::Compare::NaturalLessThan
<Qt::CaseInsensitive
>());
458 const QString defaultCategory
= m_storeDefaultCategory
;
460 if (!addTorrentParams
.category
.isEmpty())
461 m_ui
->categoryComboBox
->addItem(addTorrentParams
.category
);
462 if (!defaultCategory
.isEmpty())
463 m_ui
->categoryComboBox
->addItem(defaultCategory
);
464 m_ui
->categoryComboBox
->addItem(u
""_s
);
466 for (const QString
&category
: asConst(categories
))
468 if ((category
!= defaultCategory
) && (category
!= addTorrentParams
.category
))
469 m_ui
->categoryComboBox
->addItem(category
);
472 m_filterLine
->blockSignals(true);
473 m_filterLine
->clear();
476 if (m_ui
->comboTMM
->currentIndex() == 0) // 0 is Manual mode
477 m_ui
->savePath
->setFocus();
479 m_ui
->categoryComboBox
->setFocus();
481 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
482 const BitTorrent::InfoHash infoHash
= torrentDescr
.infoHash();
483 const bool hasMetadata
= torrentDescr
.info().has_value();
486 m_ui
->stopConditionComboBox
->removeItem(m_ui
->stopConditionComboBox
->findData(QVariant::fromValue(BitTorrent::Torrent::StopCondition::MetadataReceived
)));
488 m_ui
->stopConditionComboBox
->insertItem(1, tr("Metadata received"), QVariant::fromValue(BitTorrent::Torrent::StopCondition::MetadataReceived
));
489 const auto stopCondition
= addTorrentParams
.stopCondition
.value_or(session
->torrentStopCondition());
490 if (hasMetadata
&& (stopCondition
== BitTorrent::Torrent::StopCondition::MetadataReceived
))
492 m_ui
->startTorrentCheckBox
->setChecked(false);
493 m_ui
->stopConditionComboBox
->setCurrentIndex(m_ui
->stopConditionComboBox
->findData(QVariant::fromValue(BitTorrent::Torrent::StopCondition::None
)));
497 m_ui
->startTorrentCheckBox
->setChecked(!addTorrentParams
.addStopped
.value_or(session
->isAddTorrentStopped()));
498 m_ui
->stopConditionComboBox
->setCurrentIndex(m_ui
->stopConditionComboBox
->findData(QVariant::fromValue(stopCondition
)));
501 m_ui
->labelInfohash1Data
->setText(infoHash
.v1().isValid() ? infoHash
.v1().toString() : tr("N/A"));
502 m_ui
->labelInfohash2Data
->setText(infoHash
.v2().isValid() ? infoHash
.v2().toString() : tr("N/A"));
506 m_ui
->lblMetaLoading
->setVisible(false);
507 m_ui
->progMetaLoading
->setVisible(false);
508 m_ui
->buttonSave
->setVisible(false);
514 const QString torrentName
= torrentDescr
.name();
515 setWindowTitle(torrentName
.isEmpty() ? tr("Magnet link") : torrentName
);
516 m_ui
->labelCommentData
->setText(tr("Not Available", "This comment is unavailable"));
517 m_ui
->labelDateData
->setText(tr("Not Available", "This date is unavailable"));
518 updateDiskSpaceLabel();
519 setMetadataProgressIndicator(true, tr("Retrieving metadata..."));
522 TMMChanged(m_ui
->comboTMM
->currentIndex());
525 void AddNewTorrentDialog::updateCurrentContext()
527 Q_ASSERT(m_currentContext
);
528 if (!m_currentContext
) [[unlikely
]]
531 BitTorrent::AddTorrentParams
&addTorrentParams
= m_currentContext
->torrentParams
;
533 addTorrentParams
.skipChecking
= m_ui
->skipCheckingCheckBox
->isChecked();
536 addTorrentParams
.category
= m_ui
->categoryComboBox
->currentText();
537 if (m_ui
->defaultCategoryCheckbox
->isChecked())
538 m_storeDefaultCategory
= addTorrentParams
.category
;
540 m_storeRememberLastSavePath
= m_ui
->checkBoxRememberLastSavePath
->isChecked();
542 addTorrentParams
.addToQueueTop
= m_ui
->addToQueueTopCheckBox
->isChecked();
543 addTorrentParams
.addStopped
= !m_ui
->startTorrentCheckBox
->isChecked();
544 addTorrentParams
.stopCondition
= m_ui
->stopConditionComboBox
->currentData().value
<BitTorrent::Torrent::StopCondition
>();
545 addTorrentParams
.contentLayout
= static_cast<BitTorrent::TorrentContentLayout
>(m_ui
->contentLayoutComboBox
->currentIndex());
547 addTorrentParams
.sequential
= m_ui
->sequentialCheckBox
->isChecked();
548 addTorrentParams
.firstLastPiecePriority
= m_ui
->firstLastCheckBox
->isChecked();
550 const bool useAutoTMM
= (m_ui
->comboTMM
->currentIndex() == 1); // 1 is Automatic mode. Handle all non 1 values as manual mode.
551 addTorrentParams
.useAutoTMM
= useAutoTMM
;
554 const int savePathHistoryLength
= Preferences::instance()->addNewTorrentDialogSavePathHistoryLength();
555 const Path savePath
= m_ui
->savePath
->selectedPath();
556 addTorrentParams
.savePath
= savePath
;
557 updatePathHistory(KEY_SAVEPATHHISTORY
, savePath
, savePathHistoryLength
);
559 addTorrentParams
.useDownloadPath
= m_ui
->groupBoxDownloadPath
->isChecked();
560 if (addTorrentParams
.useDownloadPath
)
562 const Path downloadPath
= m_ui
->downloadPath
->selectedPath();
563 addTorrentParams
.downloadPath
= downloadPath
;
564 updatePathHistory(KEY_DOWNLOADPATHHISTORY
, downloadPath
, savePathHistoryLength
);
568 addTorrentParams
.downloadPath
= Path();
573 addTorrentParams
.savePath
= Path();
574 addTorrentParams
.downloadPath
= Path();
575 addTorrentParams
.useDownloadPath
= std::nullopt
;
579 void AddNewTorrentDialog::updateDiskSpaceLabel()
581 Q_ASSERT(m_currentContext
);
582 if (!m_currentContext
) [[unlikely
]]
585 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
586 const bool hasMetadata
= torrentDescr
.info().has_value();
588 // Determine torrent size
589 qlonglong torrentSize
= 0;
592 const auto torrentInfo
= *torrentDescr
.info();
593 const QVector
<BitTorrent::DownloadPriority
> &priorities
= m_contentAdaptor
->filePriorities();
594 Q_ASSERT(priorities
.size() == torrentInfo
.filesCount());
595 for (int i
= 0; i
< priorities
.size(); ++i
)
597 if (priorities
[i
] > BitTorrent::DownloadPriority::Ignored
)
598 torrentSize
+= torrentInfo
.fileSize(i
);
602 const QString freeSpace
= Utils::Misc::friendlyUnit(queryFreeDiskSpace(m_ui
->savePath
->selectedPath()));
603 const QString sizeString
= tr("%1 (Free space on disk: %2)").arg(
604 ((torrentSize
> 0) ? Utils::Misc::friendlyUnit(torrentSize
) : tr("Not available", "This size is unavailable."))
606 m_ui
->labelSizeData
->setText(sizeString
);
609 void AddNewTorrentDialog::onSavePathChanged([[maybe_unused
]] const Path
&newPath
)
612 m_savePathIndex
= m_ui
->savePath
->currentIndex();
613 updateDiskSpaceLabel();
616 void AddNewTorrentDialog::onDownloadPathChanged([[maybe_unused
]] const Path
&newPath
)
619 const int currentPathIndex
= m_ui
->downloadPath
->currentIndex();
620 if (currentPathIndex
>= 0)
621 m_downloadPathIndex
= m_ui
->downloadPath
->currentIndex();
624 void AddNewTorrentDialog::onUseDownloadPathChanged(const bool checked
)
626 m_useDownloadPath
= checked
;
627 m_ui
->downloadPath
->setCurrentIndex(checked
? m_downloadPathIndex
: -1);
630 void AddNewTorrentDialog::categoryChanged([[maybe_unused
]] const int index
)
632 if (m_ui
->comboTMM
->currentIndex() == 1)
634 const auto *btSession
= BitTorrent::Session::instance();
635 const QString categoryName
= m_ui
->categoryComboBox
->currentText();
637 const Path savePath
= btSession
->categorySavePath(categoryName
);
638 m_ui
->savePath
->setSelectedPath(savePath
);
640 const Path downloadPath
= btSession
->categoryDownloadPath(categoryName
);
641 m_ui
->downloadPath
->setSelectedPath(downloadPath
);
643 m_ui
->groupBoxDownloadPath
->setChecked(!m_ui
->downloadPath
->selectedPath().isEmpty());
645 updateDiskSpaceLabel();
649 void AddNewTorrentDialog::contentLayoutChanged()
651 Q_ASSERT(m_currentContext
);
652 if (!m_currentContext
) [[unlikely
]]
655 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
656 const bool hasMetadata
= torrentDescr
.info().has_value();
661 const auto contentLayout
= static_cast<BitTorrent::TorrentContentLayout
>(m_ui
->contentLayoutComboBox
->currentIndex());
662 m_contentAdaptor
->applyContentLayout(contentLayout
);
663 m_ui
->contentTreeView
->setContentHandler(m_contentAdaptor
.get()); // to cause reloading
666 void AddNewTorrentDialog::saveTorrentFile()
668 Q_ASSERT(m_currentContext
);
669 if (!m_currentContext
) [[unlikely
]]
672 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
673 const bool hasMetadata
= torrentDescr
.info().has_value();
675 Q_ASSERT(hasMetadata
);
676 if (!hasMetadata
) [[unlikely
]]
679 const auto torrentInfo
= *torrentDescr
.info();
681 const QString filter
{tr("Torrent file (*%1)").arg(TORRENT_FILE_EXTENSION
)};
683 Path path
{QFileDialog::getSaveFileName(this, tr("Save as torrent file")
684 , QDir::home().absoluteFilePath(torrentInfo
.name() + TORRENT_FILE_EXTENSION
)
689 if (!path
.hasExtension(TORRENT_FILE_EXTENSION
))
690 path
+= TORRENT_FILE_EXTENSION
;
692 if (const auto result
= torrentDescr
.saveToFile(path
); !result
)
694 QMessageBox::critical(this, tr("I/O Error")
695 , tr("Couldn't export torrent metadata file '%1'. Reason: %2.").arg(path
.toString(), result
.error()));
699 void AddNewTorrentDialog::populateSavePaths()
701 Q_ASSERT(m_currentContext
);
702 if (!m_currentContext
) [[unlikely
]]
705 const BitTorrent::AddTorrentParams
&addTorrentParams
= m_currentContext
->torrentParams
;
706 const auto *btSession
= BitTorrent::Session::instance();
708 m_ui
->savePath
->blockSignals(true);
709 m_ui
->savePath
->clear();
710 const auto savePathHistory
= settings()->loadValue
<QStringList
>(KEY_SAVEPATHHISTORY
);
711 if (savePathHistory
.size() > 0)
713 for (const QString
&path
: savePathHistory
)
714 m_ui
->savePath
->addItem(Path(path
));
718 m_ui
->savePath
->addItem(btSession
->savePath());
721 if (m_savePathIndex
>= 0)
723 m_ui
->savePath
->setCurrentIndex(std::min(m_savePathIndex
, (m_ui
->savePath
->count() - 1)));
727 if (!addTorrentParams
.savePath
.isEmpty())
728 setPath(m_ui
->savePath
, addTorrentParams
.savePath
);
729 else if (!m_storeRememberLastSavePath
)
730 setPath(m_ui
->savePath
, btSession
->savePath());
732 m_ui
->savePath
->setCurrentIndex(0);
734 m_savePathIndex
= m_ui
->savePath
->currentIndex();
737 m_ui
->savePath
->blockSignals(false);
739 m_ui
->downloadPath
->blockSignals(true);
740 m_ui
->downloadPath
->clear();
741 const auto downloadPathHistory
= settings()->loadValue
<QStringList
>(KEY_DOWNLOADPATHHISTORY
);
742 if (downloadPathHistory
.size() > 0)
744 for (const QString
&path
: downloadPathHistory
)
745 m_ui
->downloadPath
->addItem(Path(path
));
749 m_ui
->downloadPath
->addItem(btSession
->downloadPath());
752 if (m_downloadPathIndex
>= 0)
754 m_ui
->downloadPath
->setCurrentIndex(m_useDownloadPath
? std::min(m_downloadPathIndex
, (m_ui
->downloadPath
->count() - 1)) : -1);
755 m_ui
->groupBoxDownloadPath
->setChecked(m_useDownloadPath
);
759 const bool useDownloadPath
= addTorrentParams
.useDownloadPath
.value_or(btSession
->isDownloadPathEnabled());
760 m_ui
->groupBoxDownloadPath
->setChecked(useDownloadPath
);
762 if (!addTorrentParams
.downloadPath
.isEmpty())
763 setPath(m_ui
->downloadPath
, addTorrentParams
.downloadPath
);
764 else if (!m_storeRememberLastSavePath
)
765 setPath(m_ui
->downloadPath
, btSession
->downloadPath());
767 m_ui
->downloadPath
->setCurrentIndex(0);
769 m_downloadPathIndex
= m_ui
->downloadPath
->currentIndex();
770 if (!useDownloadPath
)
771 m_ui
->downloadPath
->setCurrentIndex(-1);
774 m_ui
->downloadPath
->blockSignals(false);
775 m_ui
->groupBoxDownloadPath
->blockSignals(false);
778 void AddNewTorrentDialog::accept()
780 Q_ASSERT(m_currentContext
);
781 if (!m_currentContext
) [[unlikely
]]
784 updateCurrentContext();
785 emit
torrentAccepted(m_currentContext
->torrentDescr
, m_currentContext
->torrentParams
);
787 Preferences::instance()->setAddNewTorrentDialogEnabled(!m_ui
->checkBoxNeverShow
->isChecked());
792 void AddNewTorrentDialog::reject()
794 Q_ASSERT(m_currentContext
);
795 if (!m_currentContext
) [[unlikely
]]
798 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
799 const bool hasMetadata
= torrentDescr
.info().has_value();
802 setMetadataProgressIndicator(false);
803 BitTorrent::Session::instance()->cancelDownloadMetadata(torrentDescr
.infoHash().toTorrentID());
809 void AddNewTorrentDialog::updateMetadata(const BitTorrent::TorrentInfo
&metadata
)
811 Q_ASSERT(m_currentContext
);
812 if (!m_currentContext
) [[unlikely
]]
815 Q_ASSERT(metadata
.isValid());
816 if (!metadata
.isValid()) [[unlikely
]]
819 BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
820 Q_ASSERT(metadata
.matchesInfoHash(torrentDescr
.infoHash()));
821 if (!metadata
.matchesInfoHash(torrentDescr
.infoHash())) [[unlikely
]]
824 torrentDescr
.setTorrentInfo(metadata
);
825 setMetadataProgressIndicator(true, tr("Parsing metadata..."));
829 setMetadataProgressIndicator(false, tr("Metadata retrieval complete"));
831 if (const auto stopCondition
= m_ui
->stopConditionComboBox
->currentData().value
<BitTorrent::Torrent::StopCondition
>()
832 ; stopCondition
== BitTorrent::Torrent::StopCondition::MetadataReceived
)
834 m_ui
->startTorrentCheckBox
->setChecked(false);
836 const auto index
= m_ui
->stopConditionComboBox
->currentIndex();
837 m_ui
->stopConditionComboBox
->setCurrentIndex(m_ui
->stopConditionComboBox
->findData(
838 QVariant::fromValue(BitTorrent::Torrent::StopCondition::None
)));
839 m_ui
->stopConditionComboBox
->removeItem(index
);
842 m_ui
->buttonSave
->setVisible(true);
843 if (torrentDescr
.infoHash().v2().isValid())
845 m_ui
->buttonSave
->setEnabled(false);
846 m_ui
->buttonSave
->setToolTip(tr("Cannot create v2 torrent until its data is fully downloaded."));
850 void AddNewTorrentDialog::setMetadataProgressIndicator(bool visibleIndicator
, const QString
&labelText
)
852 // Always show info label when waiting for metadata
853 m_ui
->lblMetaLoading
->setVisible(true);
854 m_ui
->lblMetaLoading
->setText(labelText
);
855 m_ui
->progMetaLoading
->setVisible(visibleIndicator
);
858 void AddNewTorrentDialog::setupTreeview()
860 Q_ASSERT(m_currentContext
);
861 if (!m_currentContext
) [[unlikely
]]
864 const BitTorrent::TorrentDescriptor
&torrentDescr
= m_currentContext
->torrentDescr
;
865 const bool hasMetadata
= torrentDescr
.info().has_value();
867 Q_ASSERT(hasMetadata
);
868 if (!hasMetadata
) [[unlikely
]]
872 setWindowTitle(torrentDescr
.name());
874 const auto &torrentInfo
= *torrentDescr
.info();
876 // Set torrent information
877 m_ui
->labelCommentData
->setText(Utils::Misc::parseHtmlLinks(torrentInfo
.comment().toHtmlEscaped()));
878 m_ui
->labelDateData
->setText(!torrentInfo
.creationDate().isNull() ? QLocale().toString(torrentInfo
.creationDate(), QLocale::ShortFormat
) : tr("Not available"));
880 BitTorrent::AddTorrentParams
&addTorrentParams
= m_currentContext
->torrentParams
;
881 if (addTorrentParams
.filePaths
.isEmpty())
882 addTorrentParams
.filePaths
= torrentInfo
.filePaths();
884 m_contentAdaptor
= std::make_unique
<TorrentContentAdaptor
>(torrentInfo
, addTorrentParams
.filePaths
885 , addTorrentParams
.filePriorities
, [this] { updateDiskSpaceLabel(); });
887 const auto contentLayout
= static_cast<BitTorrent::TorrentContentLayout
>(m_ui
->contentLayoutComboBox
->currentIndex());
888 m_contentAdaptor
->applyContentLayout(contentLayout
);
890 if (BitTorrent::Session::instance()->isExcludedFileNamesEnabled())
892 // Check file name blacklist for torrents that are manually added
893 QVector
<BitTorrent::DownloadPriority
> priorities
= m_contentAdaptor
->filePriorities();
894 BitTorrent::Session::instance()->applyFilenameFilter(m_contentAdaptor
->filePaths(), priorities
);
895 m_contentAdaptor
->prioritizeFiles(priorities
);
898 m_ui
->contentTreeView
->setContentHandler(m_contentAdaptor
.get());
900 m_filterLine
->blockSignals(false);
902 updateDiskSpaceLabel();
905 void AddNewTorrentDialog::TMMChanged(int index
)
908 { // 0 is Manual mode and 1 is Automatic mode. Handle all non 1 values as manual mode.
910 m_ui
->groupBoxSavePath
->setEnabled(true);
914 const auto *session
= BitTorrent::Session::instance();
916 m_ui
->groupBoxSavePath
->setEnabled(false);
918 m_ui
->savePath
->blockSignals(true);
919 m_ui
->savePath
->clear();
920 const Path savePath
= session
->categorySavePath(m_ui
->categoryComboBox
->currentText());
921 m_ui
->savePath
->addItem(savePath
);
923 m_ui
->downloadPath
->blockSignals(true);
924 m_ui
->downloadPath
->clear();
925 const Path downloadPath
= session
->categoryDownloadPath(m_ui
->categoryComboBox
->currentText());
926 m_ui
->downloadPath
->addItem(downloadPath
);
928 m_ui
->groupBoxDownloadPath
->blockSignals(true);
929 m_ui
->groupBoxDownloadPath
->setChecked(!downloadPath
.isEmpty());
932 updateDiskSpaceLabel();