Bump to 4.6.7
[qBittorrent.git] / src / gui / torrentcontentwidget.cpp
blob0fbc2fb158963fe32145652ab2ac73d52ad88fc1
1 /*
2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2022 Vladimir Golovnev <glassez@yandex.ru>
4 * Copyright (C) 2014 Ivan Sorokin <vanyacpp@gmail.com>
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 "torrentcontentwidget.h"
32 #include <QDir>
33 #include <QHeaderView>
34 #include <QKeyEvent>
35 #include <QLineEdit>
36 #include <QMenu>
37 #include <QMessageBox>
38 #include <QModelIndexList>
39 #include <QShortcut>
40 #include <QThread>
41 #include <QWheelEvent>
43 #include "base/bittorrent/torrentcontenthandler.h"
44 #include "base/path.h"
45 #include "base/utils/string.h"
46 #include "autoexpandabledialog.h"
47 #include "raisedmessagebox.h"
48 #include "torrentcontentfiltermodel.h"
49 #include "torrentcontentitemdelegate.h"
50 #include "torrentcontentmodel.h"
51 #include "torrentcontentmodelitem.h"
52 #include "uithememanager.h"
53 #include "utils.h"
55 #ifdef Q_OS_MACOS
56 #include "gui/macutilities.h"
57 #endif
59 namespace
61 QList<QPersistentModelIndex> toPersistentIndexes(const QModelIndexList &indexes)
63 QList<QPersistentModelIndex> persistentIndexes;
64 persistentIndexes.reserve(indexes.size());
65 for (const QModelIndex &index : indexes)
66 persistentIndexes.append(index);
68 return persistentIndexes;
72 TorrentContentWidget::TorrentContentWidget(QWidget *parent)
73 : QTreeView(parent)
75 setExpandsOnDoubleClick(false);
76 setSortingEnabled(true);
77 setUniformRowHeights(true);
78 header()->setSortIndicator(0, Qt::AscendingOrder);
79 header()->setFirstSectionMovable(true);
80 header()->setContextMenuPolicy(Qt::CustomContextMenu);
82 m_model = new TorrentContentModel(this);
83 connect(m_model, &TorrentContentModel::renameFailed, this, [this](const QString &errorMessage)
85 RaisedMessageBox::warning(this, tr("Rename error"), errorMessage, QMessageBox::Ok);
86 });
88 m_filterModel = new TorrentContentFilterModel(this);
89 m_filterModel->setSourceModel(m_model);
90 QTreeView::setModel(m_filterModel);
92 auto *itemDelegate = new TorrentContentItemDelegate(this);
93 setItemDelegate(itemDelegate);
95 connect(this, &QAbstractItemView::clicked, this, qOverload<const QModelIndex &>(&QAbstractItemView::edit));
96 connect(this, &QAbstractItemView::doubleClicked, this, &TorrentContentWidget::onItemDoubleClicked);
97 connect(this, &QWidget::customContextMenuRequested, this, &TorrentContentWidget::displayContextMenu);
98 connect(header(), &QWidget::customContextMenuRequested, this, &TorrentContentWidget::displayColumnHeaderMenu);
99 connect(header(), &QHeaderView::sectionMoved, this, &TorrentContentWidget::stateChanged);
100 connect(header(), &QHeaderView::sectionResized, this, &TorrentContentWidget::stateChanged);
101 connect(header(), &QHeaderView::sortIndicatorChanged, this, &TorrentContentWidget::stateChanged);
103 const auto *renameFileHotkey = new QShortcut(Qt::Key_F2, this, nullptr, nullptr, Qt::WidgetShortcut);
104 connect(renameFileHotkey, &QShortcut::activated, this, &TorrentContentWidget::renameSelectedFile);
106 connect(model(), &QAbstractItemModel::modelReset, this, &TorrentContentWidget::expandRecursively);
109 void TorrentContentWidget::setContentHandler(BitTorrent::TorrentContentHandler *contentHandler)
111 m_model->setContentHandler(contentHandler);
112 if (!contentHandler)
113 return;
115 expandRecursively();
118 BitTorrent::TorrentContentHandler *TorrentContentWidget::contentHandler() const
120 return m_model->contentHandler();
123 void TorrentContentWidget::refresh()
125 setUpdatesEnabled(false);
126 m_model->refresh();
127 setUpdatesEnabled(true);
130 bool TorrentContentWidget::openByEnterKey() const
132 return m_openFileHotkeyEnter;
135 void TorrentContentWidget::setOpenByEnterKey(const bool value)
137 if (value == openByEnterKey())
138 return;
140 if (value)
142 m_openFileHotkeyReturn = new QShortcut(Qt::Key_Return, this, nullptr, nullptr, Qt::WidgetShortcut);
143 connect(m_openFileHotkeyReturn, &QShortcut::activated, this, &TorrentContentWidget::openSelectedFile);
144 m_openFileHotkeyEnter = new QShortcut(Qt::Key_Enter, this, nullptr, nullptr, Qt::WidgetShortcut);
145 connect(m_openFileHotkeyEnter, &QShortcut::activated, this, &TorrentContentWidget::openSelectedFile);
147 else
149 delete m_openFileHotkeyEnter;
150 m_openFileHotkeyEnter = nullptr;
151 delete m_openFileHotkeyReturn;
152 m_openFileHotkeyReturn = nullptr;
156 TorrentContentWidget::DoubleClickAction TorrentContentWidget::doubleClickAction() const
158 return m_doubleClickAction;
161 void TorrentContentWidget::setDoubleClickAction(DoubleClickAction action)
163 m_doubleClickAction = action;
166 TorrentContentWidget::ColumnsVisibilityMode TorrentContentWidget::columnsVisibilityMode() const
168 return m_columnsVisibilityMode;
171 void TorrentContentWidget::setColumnsVisibilityMode(ColumnsVisibilityMode mode)
173 m_columnsVisibilityMode = mode;
176 int TorrentContentWidget::getFileIndex(const QModelIndex &index) const
178 return m_filterModel->getFileIndex(index);
181 Path TorrentContentWidget::getItemPath(const QModelIndex &index) const
183 Path path;
184 for (QModelIndex i = index; i.isValid(); i = i.parent())
185 path = Path(i.data().toString()) / path;
186 return path;
189 void TorrentContentWidget::setFilterPattern(const QString &patternText)
191 const QString pattern = Utils::String::wildcardToRegexPattern(patternText);
192 m_filterModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption));
193 if (patternText.isEmpty())
195 collapseAll();
196 expand(m_filterModel->index(0, 0));
198 else
200 expandAll();
204 void TorrentContentWidget::checkAll()
206 for (int i = 0; i < model()->rowCount(); ++i)
207 model()->setData(model()->index(i, TorrentContentModelItem::COL_NAME), Qt::Checked, Qt::CheckStateRole);
210 void TorrentContentWidget::checkNone()
212 for (int i = 0; i < model()->rowCount(); ++i)
213 model()->setData(model()->index(i, TorrentContentModelItem::COL_NAME), Qt::Unchecked, Qt::CheckStateRole);
216 void TorrentContentWidget::keyPressEvent(QKeyEvent *event)
218 if ((event->key() != Qt::Key_Space) && (event->key() != Qt::Key_Select))
220 QTreeView::keyPressEvent(event);
221 return;
224 event->accept();
226 const QVariant value = currentNameCell().data(Qt::CheckStateRole);
227 if (!value.isValid())
229 Q_ASSERT(false);
230 return;
233 const Qt::CheckState state = (static_cast<Qt::CheckState>(value.toInt()) == Qt::Checked)
234 ? Qt::Unchecked : Qt::Checked;
235 const QList<QPersistentModelIndex> selection = toPersistentIndexes(selectionModel()->selectedRows(TorrentContentModelItem::COL_NAME));
237 for (const QPersistentModelIndex &index : selection)
238 model()->setData(index, state, Qt::CheckStateRole);
241 void TorrentContentWidget::renameSelectedFile()
243 const QModelIndexList selectedIndexes = selectionModel()->selectedRows(0);
244 if (selectedIndexes.size() != 1)
245 return;
247 const QPersistentModelIndex modelIndex = selectedIndexes.first();
248 if (!modelIndex.isValid())
249 return;
251 // Ask for new name
252 const bool isFile = (m_filterModel->itemType(modelIndex) == TorrentContentModelItem::FileType);
253 bool ok = false;
254 QString newName = AutoExpandableDialog::getText(this, tr("Renaming"), tr("New name:"), QLineEdit::Normal
255 , modelIndex.data().toString(), &ok, isFile).trimmed();
256 if (!ok || !modelIndex.isValid())
257 return;
259 model()->setData(modelIndex, newName);
262 void TorrentContentWidget::applyPriorities(const BitTorrent::DownloadPriority priority)
264 const QList<QPersistentModelIndex> selectedRows = toPersistentIndexes(selectionModel()->selectedRows(Priority));
265 for (const QPersistentModelIndex &index : selectedRows)
267 model()->setData(index, static_cast<int>(priority));
271 void TorrentContentWidget::applyPrioritiesByOrder()
273 // Equally distribute the selected items into groups and for each group assign
274 // a download priority that will apply to each item. The number of groups depends on how
275 // many "download priority" are available to be assigned
277 const QList<QPersistentModelIndex> selectedRows = toPersistentIndexes(selectionModel()->selectedRows(Priority));
279 const qsizetype priorityGroups = 3;
280 const auto priorityGroupSize = std::max<qsizetype>((selectedRows.length() / priorityGroups), 1);
282 for (qsizetype i = 0; i < selectedRows.length(); ++i)
284 auto priority = BitTorrent::DownloadPriority::Ignored;
285 switch (i / priorityGroupSize)
287 case 0:
288 priority = BitTorrent::DownloadPriority::Maximum;
289 break;
290 case 1:
291 priority = BitTorrent::DownloadPriority::High;
292 break;
293 default:
294 case 2:
295 priority = BitTorrent::DownloadPriority::Normal;
296 break;
299 const QPersistentModelIndex &index = selectedRows[i];
300 model()->setData(index, static_cast<int>(priority));
304 void TorrentContentWidget::openSelectedFile()
306 const QModelIndexList selectedIndexes = selectionModel()->selectedRows(0);
307 if (selectedIndexes.size() != 1)
308 return;
309 openItem(selectedIndexes.first());
312 void TorrentContentWidget::setModel([[maybe_unused]] QAbstractItemModel *model)
314 Q_ASSERT_X(false, Q_FUNC_INFO, "Changing the model of TorrentContentWidget is not allowed.");
317 QModelIndex TorrentContentWidget::currentNameCell() const
319 const QModelIndex current = currentIndex();
320 if (!current.isValid())
322 Q_ASSERT(false);
323 return {};
326 return current.siblingAtColumn(TorrentContentModelItem::COL_NAME);
329 void TorrentContentWidget::displayColumnHeaderMenu()
331 QMenu *menu = new QMenu(this);
332 menu->setAttribute(Qt::WA_DeleteOnClose);
333 menu->setToolTipsVisible(true);
335 if (m_columnsVisibilityMode == ColumnsVisibilityMode::Editable)
337 menu->setTitle(tr("Column visibility"));
338 for (int i = 0; i < TorrentContentModelItem::NB_COL; ++i)
340 const auto columnName = model()->headerData(i, Qt::Horizontal, Qt::DisplayRole).toString();
341 QAction *action = menu->addAction(columnName, this, [this, i](bool checked)
343 setColumnHidden(i, !checked);
345 if (checked && (columnWidth(i) <= 5))
346 resizeColumnToContents(i);
348 emit stateChanged();
350 action->setCheckable(true);
351 action->setChecked(!isColumnHidden(i));
353 if (i == TorrentContentModelItem::COL_NAME)
354 action->setEnabled(false);
357 menu->addSeparator();
360 QAction *resizeAction = menu->addAction(tr("Resize columns"), this, [this]()
362 for (int i = 0, count = header()->count(); i < count; ++i)
364 if (!isColumnHidden(i))
365 resizeColumnToContents(i);
368 emit stateChanged();
370 resizeAction->setToolTip(tr("Resize all non-hidden columns to the size of their contents"));
372 menu->popup(QCursor::pos());
375 void TorrentContentWidget::displayContextMenu()
377 const QModelIndexList selectedRows = selectionModel()->selectedRows(0);
378 if (selectedRows.empty())
379 return;
381 QMenu *menu = new QMenu(this);
382 menu->setAttribute(Qt::WA_DeleteOnClose);
384 if (selectedRows.size() == 1)
386 const QModelIndex index = selectedRows[0];
388 if (!contentHandler()->actualStorageLocation().isEmpty())
390 menu->addAction(UIThemeManager::instance()->getIcon(u"folder-documents"_s), tr("Open")
391 , this, [this, index]() { openItem(index); });
392 menu->addAction(UIThemeManager::instance()->getIcon(u"directory"_s), tr("Open containing folder")
393 , this, [this, index]() { openParentFolder(index); });
395 menu->addAction(UIThemeManager::instance()->getIcon(u"edit-rename"_s), tr("Rename...")
396 , this, &TorrentContentWidget::renameSelectedFile);
397 menu->addSeparator();
399 QMenu *subMenu = menu->addMenu(tr("Priority"));
401 subMenu->addAction(tr("Do not download"), this, [this]
403 applyPriorities(BitTorrent::DownloadPriority::Ignored);
405 subMenu->addAction(tr("Normal"), this, [this]
407 applyPriorities(BitTorrent::DownloadPriority::Normal);
409 subMenu->addAction(tr("High"), this, [this]
411 applyPriorities(BitTorrent::DownloadPriority::High);
413 subMenu->addAction(tr("Maximum"), this, [this]
415 applyPriorities(BitTorrent::DownloadPriority::Maximum);
417 subMenu->addSeparator();
418 subMenu->addAction(tr("By shown file order"), this, &TorrentContentWidget::applyPrioritiesByOrder);
420 else
422 menu->addAction(tr("Do not download"), this, [this]
424 applyPriorities(BitTorrent::DownloadPriority::Ignored);
426 menu->addAction(tr("Normal priority"), this, [this]
428 applyPriorities(BitTorrent::DownloadPriority::Normal);
430 menu->addAction(tr("High priority"), this, [this]
432 applyPriorities(BitTorrent::DownloadPriority::High);
434 menu->addAction(tr("Maximum priority"), this, [this]
436 applyPriorities(BitTorrent::DownloadPriority::Maximum);
438 menu->addSeparator();
439 menu->addAction(tr("Priority by shown file order"), this, &TorrentContentWidget::applyPrioritiesByOrder);
442 // The selected torrent might have disappeared during exec()
443 // so we just close menu when an appropriate model is reset
444 connect(model(), &QAbstractItemModel::modelAboutToBeReset, menu, [menu]()
446 menu->setActiveAction(nullptr);
447 menu->close();
450 menu->popup(QCursor::pos());
453 void TorrentContentWidget::openItem(const QModelIndex &index) const
455 if (!index.isValid())
456 return;
458 m_model->contentHandler()->flushCache(); // Flush data
459 Utils::Gui::openPath(getFullPath(index));
462 void TorrentContentWidget::openParentFolder(const QModelIndex &index) const
464 const Path path = getFullPath(index);
465 m_model->contentHandler()->flushCache(); // Flush data
466 #ifdef Q_OS_MACOS
467 MacUtils::openFiles({path});
468 #else
469 Utils::Gui::openFolderSelect(path);
470 #endif
473 Path TorrentContentWidget::getFullPath(const QModelIndex &index) const
475 const auto *contentHandler = m_model->contentHandler();
476 if (const int fileIdx = getFileIndex(index); fileIdx >= 0)
478 const Path fullPath = contentHandler->actualStorageLocation() / contentHandler->actualFilePath(fileIdx);
479 return fullPath;
482 // folder type
483 const Path fullPath = contentHandler->actualStorageLocation() / getItemPath(index);
484 return fullPath;
487 void TorrentContentWidget::onItemDoubleClicked(const QModelIndex &index)
489 const auto *contentHandler = m_model->contentHandler();
490 Q_ASSERT(contentHandler && contentHandler->hasMetadata());
492 if (Q_UNLIKELY(!contentHandler || !contentHandler->hasMetadata()))
493 return;
495 if (m_doubleClickAction == DoubleClickAction::Rename)
496 renameSelectedFile();
497 else
498 openItem(index);
501 void TorrentContentWidget::expandRecursively()
503 QModelIndex currentIndex;
504 while (model()->rowCount(currentIndex) == 1)
506 currentIndex = model()->index(0, 0, currentIndex);
507 setExpanded(currentIndex, true);
511 void TorrentContentWidget::wheelEvent(QWheelEvent *event)
513 if (event->modifiers() & Qt::ShiftModifier)
515 // Shift + scroll = horizontal scroll
516 event->accept();
517 QWheelEvent scrollHEvent {event->position(), event->globalPosition()
518 , event->pixelDelta(), event->angleDelta().transposed(), event->buttons()
519 , event->modifiers(), event->phase(), event->inverted(), event->source()};
520 QTreeView::wheelEvent(&scrollHEvent);
521 return;
524 QTreeView::wheelEvent(event); // event delegated to base class