Debian Codegraph @

src/librssguard/core/feedsproxymodel.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "core/feedsproxymodel.h"
4
5 #include "core/feedsmodel.h"
6 #include "database/databasequeries.h"
7 #include "definitions/definitions.h"
8 #include "definitions/globals.h"
9 #include "gui/feedsview.h"
10 #include "miscellaneous/application.h"
11 #include "miscellaneous/regexfactory.h"
12 #include "miscellaneous/settings.h"
13 #include "services/abstract/rootitem.h"
14
15 #include <QMimeData>
16 #include <QTimer>
17
18 using RootItemPtr = RootItem*;
19
20 FeedsProxyModel::FeedsProxyModel(FeedsModel* source_model, QObject* parent)
21 : QSortFilterProxyModel(parent), m_sourceModel(source_model), m_view(nullptr), m_selectedItem(nullptr),
22 m_sortAlphabetically(false), m_filter(FeedListFilter::NoFiltering) {
23 setObjectName(QSL("FeedsProxyModel"));
24
25 initializeFilters();
26
27 setSortRole(Qt::ItemDataRole::EditRole);
28 setSortCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive);
29 setRecursiveFilteringEnabled(true);
30 setFilterKeyColumn(FDS_MODEL_TITLE_INDEX);
31 setFilterRole(Qt::ItemDataRole::EditRole);
32 setDynamicSortFilter(true);
33 setSourceModel(m_sourceModel);
34
35 // Describes priorities of node types for sorting.
36 // Smaller index means that item is "smaller" which
37 // means it should be more on top when sorting
38 // in ascending order.
39 m_priorities = {RootItem::Kind::Category,
40 RootItem::Kind::Feed,
41 RootItem::Kind::Labels,
42 RootItem::Kind::Probes,
43 RootItem::Kind::Important,
44 RootItem::Kind::Unread,
45 RootItem::Kind::Bin};
46 }
47
48 FeedsProxyModel::~FeedsProxyModel() {
49 qDebugNN << LOGSEC_FEEDMODEL << "Destroying FeedsProxyModel instance";
50 }
51
52 QModelIndexList FeedsProxyModel::match(const QModelIndex& start,
53 int role,
54 const QVariant& value,
55 int hits,
56 Qt::MatchFlags flags) const {
57 QModelIndexList result;
58 const int match_type = flags & 0x0F;
59 const Qt::CaseSensitivity cs = Qt::CaseSensitivity::CaseInsensitive;
60 const bool recurse = Globals::hasFlag(flags, Qt::MatchFlag::MatchRecursive);
61 const bool wrap = Globals::hasFlag(flags, Qt::MatchFlag::MatchWrap);
62 const bool all_hits = (hits == -1);
63 QString entered_text;
64 const QModelIndex p = parent(start);
65 int from = start.row();
66 int to = rowCount(p);
67
68 for (int i = 0; (wrap && i < 2) || (!wrap && i < 1); ++i) {
69 for (int r = from; (r < to) && (all_hits || result.count() < hits); ++r) {
70 QModelIndex idx = index(r, start.column(), p);
71
72 if (!idx.isValid()) {
73 continue;
74 }
75
76 QModelIndex mapped_idx = mapToSource(idx);
77 QVariant item_value = m_sourceModel->itemForIndex(mapped_idx)->title();
78
79 // QVariant based matching.
80 if (match_type == Qt::MatchFlag::MatchExactly) {
81 if (value == item_value) {
82 result.append(idx);
83 }
84 }
85
86 // QString based matching.
87 else {
88 if (entered_text.isEmpty()) {
89 entered_text = value.toString();
90 }
91
92 QString item_text = item_value.toString();
93
94 switch (match_type) {
95 #if QT_VERSION >= 0x050F00 // Qt >= 5.15.0
96 case Qt::MatchFlag::MatchRegularExpression:
97 #else
98 case Qt::MatchFlag::MatchRegExp:
99 #endif
100 if (QRegularExpression(entered_text,
101 QRegularExpression::PatternOption::CaseInsensitiveOption |
102 QRegularExpression::PatternOption::UseUnicodePropertiesOption)
103 .match(item_text)
104 .hasMatch()) {
105 result.append(idx);
106 }
107
108 break;
109
110 case Qt::MatchFlag::MatchWildcard:
111 if (QRegularExpression(RegexFactory::wildcardToRegularExpression(entered_text),
112 QRegularExpression::PatternOption::CaseInsensitiveOption |
113 QRegularExpression::PatternOption::UseUnicodePropertiesOption)
114 .match(item_text)
115 .hasMatch()) {
116 result.append(idx);
117 }
118
119 break;
120
121 case Qt::MatchFlag::MatchStartsWith:
122 if (item_text.startsWith(entered_text, cs)) {
123 result.append(idx);
124 }
125
126 break;
127
128 case Qt::MatchFlag::MatchEndsWith:
129 if (item_text.endsWith(entered_text, cs)) {
130 result.append(idx);
131 }
132
133 break;
134
135 case Qt::MatchFlag::MatchFixedString:
136 if (item_text.compare(entered_text, cs) == 0) {
137 result.append(idx);
138 }
139
140 break;
141
142 case Qt::MatchFlag::MatchContains:
143 default:
144 if (item_text.contains(entered_text, cs)) {
145 result.append(idx);
146 }
147
148 break;
149 }
150 }
151
152 if (recurse && hasChildren(idx)) {
153 result += match(index(0, idx.column(), idx),
154 role,
155 (entered_text.isEmpty() ? value : entered_text),
156 (all_hits ? -1 : hits - result.count()),
157 flags);
158 }
159 }
160
161 from = 0;
162 to = start.row();
163 }
164
165 return result;
166 }
167
168 bool FeedsProxyModel::canDropMimeData(const QMimeData* data,
169 Qt::DropAction action,
170 int row,
171 int column,
172 const QModelIndex& parent) const {
173 if (action != Qt::DropAction::MoveAction) {
174 return false;
175 }
176
177 QByteArray dragged_items_data = data->data(QSL(MIME_TYPE_ITEM_POINTER));
178 QDataStream stream(&dragged_items_data, QIODevice::OpenModeFlag::ReadOnly);
179 const bool order_change = row >= 0 && !m_sortAlphabetically;
180 const QModelIndex target_parent = mapToSource(parent);
181
182 if (stream.atEnd()) {
183 return false;
184 }
185
186 quintptr pointer_to_item;
187 stream >> pointer_to_item;
188
189 RootItem* dragged_item = RootItemPtr(pointer_to_item);
190
191 // Dragged item must service root, feed or category.
192 //
193 // If row is less than zero, it means we are moving dragged item into new parent. If row is at least
194 // zero, then we are sorting the dragged item.
195 //
196 // Otherwise the target row identifies the item just below the drop target placement insertion line.
197 QModelIndex target_idx = order_change ? mapToSource(index(row, 0, parent)) : target_parent;
198 RootItem* target_item = m_sourceModel->itemForIndex(target_idx);
199 RootItem* target_parent_item = m_sourceModel->itemForIndex(target_parent);
200
201 if (target_item != nullptr) {
202 qDebugNN << LOGSEC_FEEDMODEL << "Considering target for drop operation:" << QUOTE_W_SPACE(target_item->title())
203 << "with index" << QUOTE_W_SPACE(target_idx)
204 << "and target parent:" << QUOTE_W_SPACE_DOT(target_parent_item->title());
205
206 switch (dragged_item->kind()) {
207 case RootItem::Kind::Feed:
208 case RootItem::Kind::Category:
209 // Feeds can be reordered or inserted under service root or category.
210 // Categories can be reordered or inserted under service root or another category.
211 return target_parent_item->kind() == RootItem::Kind::Category ||
212 target_parent_item->kind() == RootItem::Kind::ServiceRoot;
213
214 case RootItem::Kind::ServiceRoot:
215 // Service root cannot be inserted under different parent, can only be reordered.
216 if (!order_change) {
217 return false;
218 }
219 else {
220 return target_parent_item->kind() == RootItem::Kind::Root;
221 }
222
223 default:
224 break;
225 }
226 }
227
228 return false;
229 }
230
231 bool FeedsProxyModel::dropMimeData(const QMimeData* data,
232 Qt::DropAction action,
233 int row,
234 int column,
235 const QModelIndex& parent) {
236 Q_UNUSED(column)
237
238 if (action == Qt::DropAction::IgnoreAction) {
239 return true;
240 }
241 else if (action != Qt::DropAction::MoveAction) {
242 return false;
243 }
244
245 QByteArray dragged_items_data = data->data(QSL(MIME_TYPE_ITEM_POINTER));
246
247 if (dragged_items_data.isEmpty()) {
248 return false;
249 }
250 else {
251 QDataStream stream(&dragged_items_data, QIODevice::OpenModeFlag::ReadOnly);
252 const bool order_change = row >= 0 && !m_sortAlphabetically;
253 const QModelIndex source_parent = mapToSource(parent);
254
255 while (!stream.atEnd()) {
256 quintptr pointer_to_item;
257 stream >> pointer_to_item;
258
259 // We have item we want to drag, we also determine the target item.
260 RootItemPtr dragged_item = RootItemPtr(pointer_to_item);
261 RootItem* target_item = m_sourceModel->itemForIndex(source_parent);
262 ServiceRoot* dragged_item_root = dragged_item->getParentServiceRoot();
263 ServiceRoot* target_item_root = target_item->getParentServiceRoot();
264
265 if ((dragged_item == target_item || dragged_item->parent() == target_item) && !order_change) {
266 qDebugNN << LOGSEC_FEEDMODEL
267 << "Dragged item is equal to target item or its parent is equal to target item. Cancelling drag-drop "
268 "action.";
269 return false;
270 }
271
272 if (dragged_item_root != target_item_root) {
273 // Transferring of items between different accounts is not possible.
274 qApp->showGuiMessage(Notification::Event::GeneralEvent,
275 {tr("Cannot perform drag & drop operation"),
276 tr("You can't transfer dragged item into different account, this is not supported."),
277 QSystemTrayIcon::MessageIcon::Critical});
278 qDebugNN << LOGSEC_FEEDMODEL
279 << "Dragged item cannot be dragged into different account. Cancelling drag-drop action.";
280 return false;
281 }
282
283 if (dragged_item != target_item && dragged_item->parent() != target_item &&
284 dragged_item->performDragDropChange(target_item)) {
285 // Drag & drop is supported by the dragged item and was
286 // completed on data level and in item hierarchy.
287 emit requireItemValidationAfterDragDrop(m_sourceModel->indexForItem(dragged_item));
288
289 qDebugNN << LOGSEC_FEEDMODEL << "Dropping item" << QUOTE_W_SPACE(dragged_item->title()) << "under new parent"
290 << QUOTE_W_SPACE_DOT(target_item->title());
291 }
292
293 if (order_change) {
294 auto db = qApp->database()->driver()->connection(metaObject()->className());
295 RootItem* place_above_item = m_sourceModel->itemForIndex(mapToSource(index(row, 0, parent)));
296 int target_sort_order = place_above_item->sortOrder();
297
298 qDebugNN << LOGSEC_FEEDMODEL << "Resorting/placing item" << QUOTE_W_SPACE(dragged_item->title())
299 << "with sord order" << QUOTE_W_SPACE(dragged_item->sortOrder()) << "above item"
300 << QUOTE_W_SPACE(place_above_item->title()) << "with new sort order"
301 << QUOTE_W_SPACE_DOT(target_sort_order);
302
303 if (target_sort_order > dragged_item->sortOrder()) {
304 target_sort_order--;
305 }
306
307 DatabaseQueries::moveItem(dragged_item, false, false, target_sort_order, db);
308 }
309
310 invalidate();
311 }
312
313 return true;
314 }
315
316 return false;
317 }
318
319 bool FeedsProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const {
320 if (left.isValid() && right.isValid()) {
321 // Make necessary castings.
322 const RootItem* left_item = m_sourceModel->itemForIndex(left);
323 const RootItem* right_item = m_sourceModel->itemForIndex(right);
324
325 // NOTE: Here we want to accomplish that ALL
326 // categories are queued one after another and all
327 // feeds are queued one after another too.
328 // Moreover, sort everything alphabetically or
329 // by item counts, depending on the sort column.
330 if (left_item->keepOnTop()) {
331 return sortOrder() == Qt::SortOrder::AscendingOrder;
332 }
333 else if (right_item->keepOnTop()) {
334 return sortOrder() == Qt::SortOrder::DescendingOrder;
335 }
336 else if (left_item->kind() == right_item->kind()) {
337 if (m_sortAlphabetically) {
338 // Both items are of the same type.
339 if (left.column() == FDS_MODEL_COUNTS_INDEX) {
340 // User wants to sort according to counts.
341 return left_item->countOfUnreadMessages() < right_item->countOfUnreadMessages();
342 }
343 else {
344 // In other cases, sort by title.
345 return QString::localeAwareCompare(left_item->title().toLower(), right_item->title().toLower()) < 0;
346 }
347 }
348 else {
349 // We sort some types with sort order, other alphabetically.
350 switch (left_item->kind()) {
351 case RootItem::Kind::Feed:
352 case RootItem::Kind::Category:
353 case RootItem::Kind::ServiceRoot:
354 return sortOrder() == Qt::SortOrder::AscendingOrder ? left_item->sortOrder() < right_item->sortOrder()
355 : left_item->sortOrder() > right_item->sortOrder();
356
357 default:
358 return sortOrder() == Qt::SortOrder::AscendingOrder
359 ? QString::localeAwareCompare(left_item->title().toLower(), right_item->title().toLower()) < 0
360 : QString::localeAwareCompare(left_item->title().toLower(), right_item->title().toLower()) > 0;
361 }
362 }
363 }
364 else {
365 // We sort using priorities.
366 auto left_priority = m_priorities.indexOf(left_item->kind());
367 auto right_priority = m_priorities.indexOf(right_item->kind());
368
369 return sortOrder() == Qt::SortOrder::AscendingOrder ? left_priority < right_priority
370 : right_priority < left_priority;
371 }
372 }
373 else {
374 return false;
375 }
376 }
377
378 bool FeedsProxyModel::filterAcceptsRow(int source_row, const QModelIndex& source_parent) const {
379 bool should_show = filterAcceptsRowInternal(source_row, source_parent);
380
381 if (should_show && m_hiddenIndices.contains(QPair<int, QModelIndex>(source_row, source_parent))) {
382 qDebugNN << LOGSEC_CORE << "Item"
383 << QUOTE_W_SPACE(m_sourceModel
384 ->data(m_sourceModel->index(source_row, 0, source_parent), Qt::ItemDataRole::EditRole)
385 .toString())
386 << "was previously hidden and now shows up, expand.";
387
388 const_cast<FeedsProxyModel*>(this)->m_hiddenIndices.removeAll(QPair<int, QModelIndex>(source_row, source_parent));
389
390 // Now, item now should be displayed and previously it was not.
391 // Expand!
392 emit indexNotFilteredOutAnymore(m_sourceModel->index(source_row, 0, source_parent));
393 }
394
395 if (!should_show) {
396 const_cast<FeedsProxyModel*>(this)->m_hiddenIndices.append(QPair<int, QModelIndex>(source_row, source_parent));
397 }
398
399 return should_show;
400 }
401
402 void FeedsProxyModel::initializeFilters() {
403 m_filters[FeedListFilter::ShowEmpty] = [this](const RootItem* item) {
404 return item->countOfAllMessages() == 0;
405 };
406
407 m_filters[FeedListFilter::ShowNonEmpty] = [this](const RootItem* item) {
408 return item->countOfAllMessages() != 0;
409 };
410
411 m_filters[FeedListFilter::ShowQuiet] = [this](const RootItem* item) {
412 Feed* feed = item->toFeed();
413
414 return feed != nullptr && feed->isQuiet();
415 };
416
417 m_filters[FeedListFilter::ShowSwitchedOff] = [this](const RootItem* item) {
418 Feed* feed = item->toFeed();
419
420 return feed != nullptr && feed->isSwitchedOff();
421 };
422
423 m_filters[FeedListFilter::ShowUnread] = [this](const RootItem* item) {
424 return item->countOfUnreadMessages() > 0;
425 };
426
427 m_filters[FeedListFilter::ShowWithArticleFilters] = [this](const RootItem* item) {
428 Feed* feed = item->toFeed();
429
430 return feed != nullptr && !feed->messageFilters().isEmpty();
431 };
432
433 m_filters[FeedListFilter::ShowWithError] = [this](const RootItem* item) {
434 Feed* feed = item->toFeed();
435
436 return feed != nullptr &&
437 (feed->status() == Feed::Status::AuthError || feed->status() == Feed::Status::NetworkError ||
438 feed->status() == Feed::Status::OtherError || feed->status() == Feed::Status::ParsingError);
439 };
440
441 m_filters[FeedListFilter::ShowWithNewArticles] = [this](const RootItem* item) {
442 Feed* feed = item->toFeed();
443
444 return feed != nullptr && feed->status() == Feed::Status::NewMessages;
445 };
446
447 m_filterKeys = m_filters.keys();
448 }
449
450 bool FeedsProxyModel::filterAcceptsRowInternal(int source_row, const QModelIndex& source_parent) const {
451 const QModelIndex idx = m_sourceModel->index(source_row, 0, source_parent);
452
453 if (!idx.isValid()) {
454 return false;
455 }
456
457 const RootItem* item = m_sourceModel->itemForIndex(idx);
458
459 if (m_selectedItem == item) {
460 return true;
461 }
462
463 ServiceRoot* par_account = item->getParentServiceRoot();
464
465 if (item->kind() == RootItem::Kind::Important && !par_account->nodeShowImportant()) {
466 return false;
467 }
468
469 if (item->kind() == RootItem::Kind::Unread && !par_account->nodeShowUnread()) {
470 return false;
471 }
472
473 if (item->kind() == RootItem::Kind::Probes && !par_account->nodeShowProbes()) {
474 return false;
475 }
476
477 if (item->kind() == RootItem::Kind::Labels && !par_account->nodeShowLabels()) {
478 return false;
479 }
480
481 if (item->kind() != RootItem::Kind::Category && item->kind() != RootItem::Kind::Feed &&
482 item->kind() != RootItem::Kind::Label) {
483 // Some items are always visible.
484 return true;
485 }
486
487 bool should_show = QSortFilterProxyModel::filterAcceptsRow(source_row, source_parent);
488
489 // if (item->kind() == RootItem::Kind::Feed) {
490 // const Feed* feed = item->toFeed();
491
492 for (FeedListFilter val : m_filterKeys) {
493 if (Globals::hasFlag(m_filter, val)) {
494 // This particular filter is enabled.
495 if (m_filters[val](item)) {
496 // The item matches the feed filter.
497 // Display it if it matches internal string-based filter too.
498 return should_show;
499 }
500 }
501 }
502
503 if (m_filter != FeedListFilter::NoFiltering) {
504 // Some filter is enabled but this item does not meet it.
505 return false;
506 }
507 //}
508
509 return should_show;
510 }
511
512 bool FeedsProxyModel::sortAlphabetically() const {
513 return m_sortAlphabetically;
514 }
515
516 void FeedsProxyModel::sort(int column, Qt::SortOrder order) {
517 QSortFilterProxyModel::sort(column, order);
518 }
519
520 void FeedsProxyModel::setView(FeedsView* newView) {
521 m_view = newView;
522 }
523
524 const RootItem* FeedsProxyModel::selectedItem() const {
525 return m_selectedItem;
526 }
527
528 void FeedsProxyModel::setSelectedItem(const RootItem* selected_item) {
529 m_selectedItem = selected_item;
530 }
531
532 void FeedsProxyModel::setSortAlphabetically(bool sort_alphabetically) {
533 if (sort_alphabetically != m_sortAlphabetically) {
534 m_sortAlphabetically = sort_alphabetically;
535 qApp->settings()->setValue(GROUP(Feeds), Feeds::SortAlphabetically, sort_alphabetically);
536 invalidate();
537 }
538 }
539
540 QModelIndexList FeedsProxyModel::mapListToSource(const QModelIndexList& indexes) const {
541 QModelIndexList source_indexes;
542 source_indexes.reserve(indexes.size());
543
544 for (const QModelIndex& index : indexes) {
545 source_indexes << mapToSource(index);
546 }
547
548 return source_indexes;
549 }
550
551 void FeedsProxyModel::setFeedListFilter(FeedListFilter filter) {
552 m_filter = filter;
553
554 #if QT_VERSION_MAJOR == 5
555 invalidateFilter();
556 #else
557 invalidateRowsFilter();
558 #endif
559 }