2 * Bittorrent Client using Qt and libtorrent.
3 * Copyright (C) 2018 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 "searchjobwidget.h"
32 #include <QApplication>
34 #include <QDesktopServices>
35 #include <QHeaderView>
39 #include <QStandardItemModel>
42 #include "base/preferences.h"
43 #include "base/search/searchdownloadhandler.h"
44 #include "base/search/searchhandler.h"
45 #include "base/search/searchpluginmanager.h"
46 #include "base/utils/misc.h"
47 #include "gui/interfaces/iguiapplication.h"
48 #include "gui/lineedit.h"
49 #include "gui/uithememanager.h"
50 #include "searchsortmodel.h"
51 #include "ui_searchjobwidget.h"
53 SearchJobWidget::SearchJobWidget(SearchHandler
*searchHandler
, IGUIApplication
*app
, QWidget
*parent
)
54 : GUIApplicationComponent(app
, parent
)
55 , m_ui
{new Ui::SearchJobWidget
}
56 , m_searchHandler
{searchHandler
}
57 , m_nameFilteringMode
{u
"Search/FilteringMode"_s
}
63 header()->setFirstSectionMovable(true);
64 header()->setStretchLastSection(false);
65 header()->setTextElideMode(Qt::ElideRight
);
67 // Set Search results list model
68 m_searchListModel
= new QStandardItemModel(0, SearchSortModel::NB_SEARCH_COLUMNS
, this);
69 m_searchListModel
->setHeaderData(SearchSortModel::NAME
, Qt::Horizontal
, tr("Name", "i.e: file name"));
70 m_searchListModel
->setHeaderData(SearchSortModel::SIZE
, Qt::Horizontal
, tr("Size", "i.e: file size"));
71 m_searchListModel
->setHeaderData(SearchSortModel::SEEDS
, Qt::Horizontal
, tr("Seeders", "i.e: Number of full sources"));
72 m_searchListModel
->setHeaderData(SearchSortModel::LEECHES
, Qt::Horizontal
, tr("Leechers", "i.e: Number of partial sources"));
73 m_searchListModel
->setHeaderData(SearchSortModel::ENGINE_URL
, Qt::Horizontal
, tr("Search engine"));
74 // Set columns text alignment
75 m_searchListModel
->setHeaderData(SearchSortModel::SIZE
, Qt::Horizontal
, QVariant(Qt::AlignRight
| Qt::AlignVCenter
), Qt::TextAlignmentRole
);
76 m_searchListModel
->setHeaderData(SearchSortModel::SEEDS
, Qt::Horizontal
, QVariant(Qt::AlignRight
| Qt::AlignVCenter
), Qt::TextAlignmentRole
);
77 m_searchListModel
->setHeaderData(SearchSortModel::LEECHES
, Qt::Horizontal
, QVariant(Qt::AlignRight
| Qt::AlignVCenter
), Qt::TextAlignmentRole
);
79 m_proxyModel
= new SearchSortModel(this);
80 m_proxyModel
->setDynamicSortFilter(true);
81 m_proxyModel
->setSourceModel(m_searchListModel
);
82 m_proxyModel
->setNameFilter(searchHandler
->pattern());
83 m_ui
->resultsBrowser
->setModel(m_proxyModel
);
85 m_ui
->resultsBrowser
->hideColumn(SearchSortModel::DL_LINK
); // Hide url column
86 m_ui
->resultsBrowser
->hideColumn(SearchSortModel::DESC_LINK
);
88 m_ui
->resultsBrowser
->setSelectionMode(QAbstractItemView::ExtendedSelection
);
89 m_ui
->resultsBrowser
->setRootIsDecorated(false);
90 m_ui
->resultsBrowser
->setAllColumnsShowFocus(true);
91 m_ui
->resultsBrowser
->setSortingEnabled(true);
92 m_ui
->resultsBrowser
->setEditTriggers(QAbstractItemView::NoEditTriggers
);
94 // Ensure that at least one column is visible at all times
95 bool atLeastOne
= false;
96 for (int i
= 0; i
< SearchSortModel::DL_LINK
; ++i
)
98 if (!m_ui
->resultsBrowser
->isColumnHidden(i
))
105 m_ui
->resultsBrowser
->setColumnHidden(SearchSortModel::NAME
, false);
106 // To also mitigate the above issue, we have to resize each column when
107 // its size is 0, because explicitly 'showing' the column isn't enough
108 // in the above scenario.
109 for (int i
= 0; i
< SearchSortModel::DL_LINK
; ++i
)
111 if ((m_ui
->resultsBrowser
->columnWidth(i
) <= 0) && !m_ui
->resultsBrowser
->isColumnHidden(i
))
112 m_ui
->resultsBrowser
->resizeColumnToContents(i
);
115 header()->setContextMenuPolicy(Qt::CustomContextMenu
);
116 connect(header(), &QWidget::customContextMenuRequested
, this, &SearchJobWidget::displayColumnHeaderMenu
);
117 connect(header(), &QHeaderView::sectionResized
, this, &SearchJobWidget::saveSettings
);
118 connect(header(), &QHeaderView::sectionMoved
, this, &SearchJobWidget::saveSettings
);
119 connect(header(), &QHeaderView::sortIndicatorChanged
, this, &SearchJobWidget::saveSettings
);
121 fillFilterComboBoxes();
125 m_lineEditSearchResultsFilter
= new LineEdit(this);
126 m_lineEditSearchResultsFilter
->setPlaceholderText(tr("Filter search results..."));
127 m_lineEditSearchResultsFilter
->setContextMenuPolicy(Qt::CustomContextMenu
);
128 connect(m_lineEditSearchResultsFilter
, &QWidget::customContextMenuRequested
, this, &SearchJobWidget::showFilterContextMenu
);
129 connect(m_lineEditSearchResultsFilter
, &LineEdit::textChanged
, this, &SearchJobWidget::filterSearchResults
);
130 m_ui
->horizontalLayout
->insertWidget(0, m_lineEditSearchResultsFilter
);
132 connect(m_ui
->filterMode
, qOverload
<int>(&QComboBox::currentIndexChanged
)
133 , this, &SearchJobWidget::updateFilter
);
134 connect(m_ui
->minSeeds
, &QAbstractSpinBox::editingFinished
, this, &SearchJobWidget::updateFilter
);
135 connect(m_ui
->minSeeds
, qOverload
<int>(&QSpinBox::valueChanged
)
136 , this, &SearchJobWidget::updateFilter
);
137 connect(m_ui
->maxSeeds
, &QAbstractSpinBox::editingFinished
, this, &SearchJobWidget::updateFilter
);
138 connect(m_ui
->maxSeeds
, qOverload
<int>(&QSpinBox::valueChanged
)
139 , this, &SearchJobWidget::updateFilter
);
140 connect(m_ui
->minSize
, &QAbstractSpinBox::editingFinished
, this, &SearchJobWidget::updateFilter
);
141 connect(m_ui
->minSize
, qOverload
<double>(&QDoubleSpinBox::valueChanged
)
142 , this, &SearchJobWidget::updateFilter
);
143 connect(m_ui
->maxSize
, &QAbstractSpinBox::editingFinished
, this, &SearchJobWidget::updateFilter
);
144 connect(m_ui
->maxSize
, qOverload
<double>(&QDoubleSpinBox::valueChanged
)
145 , this, &SearchJobWidget::updateFilter
);
146 connect(m_ui
->minSizeUnit
, qOverload
<int>(&QComboBox::currentIndexChanged
)
147 , this, &SearchJobWidget::updateFilter
);
148 connect(m_ui
->maxSizeUnit
, qOverload
<int>(&QComboBox::currentIndexChanged
)
149 , this, &SearchJobWidget::updateFilter
);
151 connect(m_ui
->resultsBrowser
, &QAbstractItemView::doubleClicked
, this, &SearchJobWidget::onItemDoubleClicked
);
153 connect(searchHandler
, &SearchHandler::newSearchResults
, this, &SearchJobWidget::appendSearchResults
);
154 connect(searchHandler
, &SearchHandler::searchFinished
, this, &SearchJobWidget::searchFinished
);
155 connect(searchHandler
, &SearchHandler::searchFailed
, this, &SearchJobWidget::searchFailed
);
156 connect(this, &QObject::destroyed
, searchHandler
, &QObject::deleteLater
);
158 setStatusTip(statusText(m_status
));
161 SearchJobWidget::~SearchJobWidget()
167 void SearchJobWidget::onItemDoubleClicked(const QModelIndex
&index
)
169 downloadTorrent(index
);
172 QHeaderView
*SearchJobWidget::header() const
174 return m_ui
->resultsBrowser
->header();
177 // Set the color of a row in data model
178 void SearchJobWidget::setRowColor(int row
, const QColor
&color
)
180 m_proxyModel
->setDynamicSortFilter(false);
181 for (int i
= 0; i
< m_proxyModel
->columnCount(); ++i
)
182 m_proxyModel
->setData(m_proxyModel
->index(row
, i
), color
, Qt::ForegroundRole
);
184 m_proxyModel
->setDynamicSortFilter(true);
187 SearchJobWidget::Status
SearchJobWidget::status() const
192 int SearchJobWidget::visibleResultsCount() const
194 return m_proxyModel
->rowCount();
197 LineEdit
*SearchJobWidget::lineEditSearchResultsFilter() const
199 return m_lineEditSearchResultsFilter
;
202 void SearchJobWidget::cancelSearch()
204 m_searchHandler
->cancelSearch();
207 void SearchJobWidget::downloadTorrents(const AddTorrentOption option
)
209 const QModelIndexList rows
= m_ui
->resultsBrowser
->selectionModel()->selectedRows();
210 for (const QModelIndex
&rowIndex
: rows
)
211 downloadTorrent(rowIndex
, option
);
214 void SearchJobWidget::openTorrentPages() const
216 const QModelIndexList rows
{m_ui
->resultsBrowser
->selectionModel()->selectedRows()};
217 for (const QModelIndex
&rowIndex
: rows
)
219 const QString descrLink
= m_proxyModel
->data(
220 m_proxyModel
->index(rowIndex
.row(), SearchSortModel::DESC_LINK
)).toString();
221 if (!descrLink
.isEmpty())
222 QDesktopServices::openUrl(QUrl::fromEncoded(descrLink
.toUtf8()));
226 void SearchJobWidget::copyTorrentURLs() const
228 copyField(SearchSortModel::DESC_LINK
);
231 void SearchJobWidget::copyTorrentDownloadLinks() const
233 copyField(SearchSortModel::DL_LINK
);
236 void SearchJobWidget::copyTorrentNames() const
238 copyField(SearchSortModel::NAME
);
241 void SearchJobWidget::copyField(const int column
) const
243 const QModelIndexList rows
{m_ui
->resultsBrowser
->selectionModel()->selectedRows()};
246 for (const QModelIndex
&rowIndex
: rows
)
248 const QString field
= m_proxyModel
->data(
249 m_proxyModel
->index(rowIndex
.row(), column
)).toString();
250 if (!field
.isEmpty())
255 QApplication::clipboard()->setText(list
.join(u
'\n'));
258 void SearchJobWidget::setStatus(Status value
)
260 if (m_status
== value
) return;
263 setStatusTip(statusText(value
));
264 emit
statusChanged();
267 void SearchJobWidget::downloadTorrent(const QModelIndex
&rowIndex
, const AddTorrentOption option
)
269 const QString torrentUrl
= m_proxyModel
->data(
270 m_proxyModel
->index(rowIndex
.row(), SearchSortModel::DL_LINK
)).toString();
271 const QString siteUrl
= m_proxyModel
->data(
272 m_proxyModel
->index(rowIndex
.row(), SearchSortModel::ENGINE_URL
)).toString();
274 if (torrentUrl
.startsWith(u
"magnet:", Qt::CaseInsensitive
))
276 addTorrentToSession(torrentUrl
, option
);
280 SearchDownloadHandler
*downloadHandler
= m_searchHandler
->manager()->downloadTorrent(siteUrl
, torrentUrl
);
281 connect(downloadHandler
, &SearchDownloadHandler::downloadFinished
282 , this, [this, option
](const QString
&source
) { addTorrentToSession(source
, option
); });
283 connect(downloadHandler
, &SearchDownloadHandler::downloadFinished
, downloadHandler
, &SearchDownloadHandler::deleteLater
);
285 setRowColor(rowIndex
.row(), QApplication::palette().color(QPalette::LinkVisited
));
288 void SearchJobWidget::addTorrentToSession(const QString
&source
, const AddTorrentOption option
)
290 app()->addTorrentManager()->addTorrent(source
, {}, option
);
293 void SearchJobWidget::updateResultsCount()
295 const int totalResults
= m_searchListModel
->rowCount();
296 const int filteredResults
= m_proxyModel
->rowCount();
297 m_ui
->resultsLbl
->setText(tr("Results (showing <i>%1</i> out of <i>%2</i>):", "i.e: Search results")
298 .arg(filteredResults
).arg(totalResults
));
300 m_noSearchResults
= (totalResults
== 0);
301 emit
resultsCountUpdated();
304 void SearchJobWidget::updateFilter()
306 using Utils::Misc::SizeUnit
;
308 m_proxyModel
->enableNameFilter(filteringMode() == NameFilteringMode::OnlyNames
);
309 // we update size and seeds filter parameters in the model even if they are disabled
310 m_proxyModel
->setSeedsFilter(m_ui
->minSeeds
->value(), m_ui
->maxSeeds
->value());
311 m_proxyModel
->setSizeFilter(
312 sizeInBytes(m_ui
->minSize
->value(), static_cast<SizeUnit
>(m_ui
->minSizeUnit
->currentIndex())),
313 sizeInBytes(m_ui
->maxSize
->value(), static_cast<SizeUnit
>(m_ui
->maxSizeUnit
->currentIndex())));
315 m_nameFilteringMode
= filteringMode();
317 m_proxyModel
->invalidate();
318 updateResultsCount();
321 void SearchJobWidget::fillFilterComboBoxes()
323 using Utils::Misc::SizeUnit
;
324 using Utils::Misc::unitString
;
326 QStringList unitStrings
;
327 unitStrings
.append(unitString(SizeUnit::Byte
));
328 unitStrings
.append(unitString(SizeUnit::KibiByte
));
329 unitStrings
.append(unitString(SizeUnit::MebiByte
));
330 unitStrings
.append(unitString(SizeUnit::GibiByte
));
331 unitStrings
.append(unitString(SizeUnit::TebiByte
));
332 unitStrings
.append(unitString(SizeUnit::PebiByte
));
333 unitStrings
.append(unitString(SizeUnit::ExbiByte
));
335 m_ui
->minSizeUnit
->clear();
336 m_ui
->maxSizeUnit
->clear();
337 m_ui
->minSizeUnit
->addItems(unitStrings
);
338 m_ui
->maxSizeUnit
->addItems(unitStrings
);
340 m_ui
->minSize
->setValue(0);
341 m_ui
->minSizeUnit
->setCurrentIndex(static_cast<int>(SizeUnit::MebiByte
));
343 m_ui
->maxSize
->setValue(-1);
344 m_ui
->maxSizeUnit
->setCurrentIndex(static_cast<int>(SizeUnit::GibiByte
));
346 m_ui
->filterMode
->clear();
348 m_ui
->filterMode
->addItem(tr("Torrent names only"), static_cast<int>(NameFilteringMode::OnlyNames
));
349 m_ui
->filterMode
->addItem(tr("Everywhere"), static_cast<int>(NameFilteringMode::Everywhere
));
351 const QVariant selectedMode
= static_cast<int>(m_nameFilteringMode
.get(NameFilteringMode::OnlyNames
));
352 const int index
= m_ui
->filterMode
->findData(selectedMode
);
353 m_ui
->filterMode
->setCurrentIndex((index
== -1) ? 0 : index
);
356 void SearchJobWidget::filterSearchResults(const QString
&name
)
358 const QString pattern
= (Preferences::instance()->getRegexAsFilteringPatternForSearchJob()
359 ? name
: Utils::String::wildcardToRegexPattern(name
));
360 m_proxyModel
->setFilterRegularExpression(QRegularExpression(pattern
, QRegularExpression::CaseInsensitiveOption
));
361 updateResultsCount();
364 void SearchJobWidget::showFilterContextMenu()
366 const Preferences
*pref
= Preferences::instance();
368 QMenu
*menu
= m_lineEditSearchResultsFilter
->createStandardContextMenu();
369 menu
->setAttribute(Qt::WA_DeleteOnClose
);
370 menu
->addSeparator();
372 QAction
*useRegexAct
= menu
->addAction(tr("Use regular expressions"));
373 useRegexAct
->setCheckable(true);
374 useRegexAct
->setChecked(pref
->getRegexAsFilteringPatternForSearchJob());
375 connect(useRegexAct
, &QAction::toggled
, pref
, &Preferences::setRegexAsFilteringPatternForSearchJob
);
376 connect(useRegexAct
, &QAction::toggled
, this, [this]() { filterSearchResults(m_lineEditSearchResultsFilter
->text()); });
378 menu
->popup(QCursor::pos());
381 void SearchJobWidget::contextMenuEvent(QContextMenuEvent
*event
)
383 auto *menu
= new QMenu(this);
384 menu
->setAttribute(Qt::WA_DeleteOnClose
);
386 menu
->addAction(UIThemeManager::instance()->getIcon(u
"download"_s
)
387 , tr("Open download window"), this, [this]() { downloadTorrents(AddTorrentOption::ShowDialog
); });
388 menu
->addAction(UIThemeManager::instance()->getIcon(u
"downloading"_s
, u
"download"_s
)
389 , tr("Download"), this, [this]() { downloadTorrents(AddTorrentOption::SkipDialog
); });
390 menu
->addSeparator();
391 menu
->addAction(UIThemeManager::instance()->getIcon(u
"application-url"_s
), tr("Open description page")
392 , this, &SearchJobWidget::openTorrentPages
);
394 QMenu
*copySubMenu
= menu
->addMenu(
395 UIThemeManager::instance()->getIcon(u
"edit-copy"_s
), tr("Copy"));
397 copySubMenu
->addAction(UIThemeManager::instance()->getIcon(u
"name"_s
, u
"edit-copy"_s
), tr("Name")
398 , this, &SearchJobWidget::copyTorrentNames
);
399 copySubMenu
->addAction(UIThemeManager::instance()->getIcon(u
"insert-link"_s
, u
"edit-copy"_s
), tr("Download link")
400 , this, &SearchJobWidget::copyTorrentDownloadLinks
);
401 copySubMenu
->addAction(UIThemeManager::instance()->getIcon(u
"application-url"_s
, u
"edit-copy"_s
), tr("Description page URL")
402 , this, &SearchJobWidget::copyTorrentURLs
);
404 menu
->popup(event
->globalPos());
407 QString
SearchJobWidget::statusText(SearchJobWidget::Status st
)
411 case Status::Ongoing
:
412 return tr("Searching...");
413 case Status::Finished
:
414 return tr("Search has finished");
415 case Status::Aborted
:
416 return tr("Search aborted");
418 return tr("An error occurred during search...");
419 case Status::NoResults
:
420 return tr("Search returned no results");
426 SearchJobWidget::NameFilteringMode
SearchJobWidget::filteringMode() const
428 return static_cast<NameFilteringMode
>(m_ui
->filterMode
->itemData(m_ui
->filterMode
->currentIndex()).toInt());
431 void SearchJobWidget::loadSettings()
433 header()->restoreState(Preferences::instance()->getSearchTabHeaderState());
436 void SearchJobWidget::saveSettings() const
438 Preferences::instance()->setSearchTabHeaderState(header()->saveState());
441 int SearchJobWidget::visibleColumnsCount() const
444 for (int i
= 0, iMax
= m_ui
->resultsBrowser
->header()->count(); i
< iMax
; ++i
)
446 if (!m_ui
->resultsBrowser
->isColumnHidden(i
))
453 void SearchJobWidget::displayColumnHeaderMenu()
455 auto *menu
= new QMenu(this);
456 menu
->setAttribute(Qt::WA_DeleteOnClose
);
457 menu
->setTitle(tr("Column visibility"));
458 menu
->setToolTipsVisible(true);
460 for (int i
= 0; i
< SearchSortModel::DL_LINK
; ++i
)
462 const auto columnName
= m_searchListModel
->headerData(i
, Qt::Horizontal
, Qt::DisplayRole
).toString();
463 QAction
*action
= menu
->addAction(columnName
, this, [this, i
](const bool checked
)
465 if (!checked
&& (visibleColumnsCount() <= 1))
468 m_ui
->resultsBrowser
->setColumnHidden(i
, !checked
);
470 if (checked
&& (m_ui
->resultsBrowser
->columnWidth(i
) <= 5))
471 m_ui
->resultsBrowser
->resizeColumnToContents(i
);
475 action
->setCheckable(true);
476 action
->setChecked(!m_ui
->resultsBrowser
->isColumnHidden(i
));
479 menu
->addSeparator();
480 QAction
*resizeAction
= menu
->addAction(tr("Resize columns"), this, [this]()
482 for (int i
= 0, count
= m_ui
->resultsBrowser
->header()->count(); i
< count
; ++i
)
484 if (!m_ui
->resultsBrowser
->isColumnHidden(i
))
485 m_ui
->resultsBrowser
->resizeColumnToContents(i
);
489 resizeAction
->setToolTip(tr("Resize all non-hidden columns to the size of their contents"));
491 menu
->popup(QCursor::pos());
494 void SearchJobWidget::searchFinished(bool cancelled
)
497 setStatus(Status::Aborted
);
498 else if (m_noSearchResults
)
499 setStatus(Status::NoResults
);
501 setStatus(Status::Finished
);
504 void SearchJobWidget::searchFailed()
506 setStatus(Status::Error
);
509 void SearchJobWidget::appendSearchResults(const QVector
<SearchResult
> &results
)
511 for (const SearchResult
&result
: results
)
513 // Add item to search result list
514 int row
= m_searchListModel
->rowCount();
515 m_searchListModel
->insertRow(row
);
517 const auto setModelData
= [this, row
] (const int column
, const QString
&displayData
518 , const QVariant
&underlyingData
, const Qt::Alignment textAlignmentData
= {})
520 const QMap
<int, QVariant
> data
=
522 {Qt::DisplayRole
, displayData
},
523 {SearchSortModel::UnderlyingDataRole
, underlyingData
},
524 {Qt::TextAlignmentRole
, QVariant
{textAlignmentData
}}
526 m_searchListModel
->setItemData(m_searchListModel
->index(row
, column
), data
);
529 setModelData(SearchSortModel::NAME
, result
.fileName
, result
.fileName
);
530 setModelData(SearchSortModel::DL_LINK
, result
.fileUrl
, result
.fileUrl
);
531 setModelData(SearchSortModel::ENGINE_URL
, result
.siteUrl
, result
.siteUrl
);
532 setModelData(SearchSortModel::DESC_LINK
, result
.descrLink
, result
.descrLink
);
533 setModelData(SearchSortModel::SIZE
, Utils::Misc::friendlyUnit(result
.fileSize
), result
.fileSize
, (Qt::AlignRight
| Qt::AlignVCenter
));
534 setModelData(SearchSortModel::SEEDS
, QString::number(result
.nbSeeders
), result
.nbSeeders
, (Qt::AlignRight
| Qt::AlignVCenter
));
535 setModelData(SearchSortModel::LEECHES
, QString::number(result
.nbLeechers
), result
.nbLeechers
, (Qt::AlignRight
| Qt::AlignVCenter
));
538 updateResultsCount();
541 void SearchJobWidget::keyPressEvent(QKeyEvent
*event
)
543 switch (event
->key())
550 QWidget::keyPressEvent(event
);