Debian Codegraph @

src/librssguard/gui/messagesview.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "gui/messagesview.h"
4
5 #include "3rd-party/boolinq/boolinq.h"
6 #include "core/messagesmodel.h"
7 #include "core/messagesproxymodel.h"
8 #include "definitions/definitions.h"
9 #include "gui/dialogs/formmain.h"
10 #include "gui/messagebox.h"
11 #include "gui/reusable/labelsmenu.h"
12 #include "gui/reusable/styleditemdelegatewithoutfocus.h"
13 #include "gui/reusable/treeviewcolumnsmenu.h"
14 #include "gui/toolbars/messagestoolbar.h"
15 #include "miscellaneous/externaltool.h"
16 #include "miscellaneous/feedreader.h"
17 #include "miscellaneous/settings.h"
18 #include "network-web/webfactory.h"
19 #include "qnamespace.h"
20 #include "services/abstract/labelsnode.h"
21 #include "services/abstract/serviceroot.h"
22
23 #include <QClipboard>
24 #include <QFileIconProvider>
25 #include <QJsonObject>
26 #include <QKeyEvent>
27 #include <QMenu>
28 #include <QProcess>
29 #include <QScrollBar>
30 #include <QTimer>
31
32 MessagesView::MessagesView(QWidget* parent)
33 : BaseTreeView(parent), m_contextMenu(nullptr), m_columnsAdjusted(false), m_processingAnyMouseButton(false),
34 m_processingRightMouseButton(false) {
35 m_sourceModel = qApp->feedReader()->messagesModel();
36 m_proxyModel = qApp->feedReader()->messagesProxyModel();
37 m_sourceModel->setView(this);
38
39 // Forward count changes to the view.
40 createConnections();
41 setModel(m_proxyModel);
42 setupAppearance();
43 setupArticleMarkingPolicy();
44 header()->setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu);
45 connect(header(), &QHeaderView::customContextMenuRequested, this, [=](QPoint point) {
46 TreeViewColumnsMenu mm(header());
47 mm.exec(header()->mapToGlobal(point));
48 });
49 connect(&m_delayedArticleMarker, &QTimer::timeout, this, &MessagesView::markSelectedMessagesReadDelayed);
50 reloadFontSettings();
51 }
52
53 MessagesView::~MessagesView() {
54 qDebugNN << LOGSEC_GUI << "Destroying MessagesView instance.";
55 }
56
57 void MessagesView::reloadFontSettings() {
58 m_sourceModel->setupFonts();
59 }
60
61 void MessagesView::setupArticleMarkingPolicy() {
62 m_articleMarkingPolicy =
63 ArticleMarkingPolicy(qApp->settings()->value(GROUP(Messages), SETTING(Messages::ArticleMarkOnSelection)).toInt());
64 m_articleMarkingDelay =
65 qApp->settings()->value(GROUP(Messages), SETTING(Messages::ArticleMarkOnSelectionDelay)).toInt();
66
67 m_delayedArticleMarker.setSingleShot(true);
68 m_delayedArticleMarker.setInterval(m_articleMarkingDelay);
69 }
70
71 QByteArray MessagesView::saveHeaderState() const {
72 QJsonObject obj;
73
74 obj[QSL("header_count")] = header()->count();
75
76 // Store column attributes.
77 for (int i = 0; i < header()->count(); i++) {
78 obj[QSL("header_%1_idx").arg(i)] = header()->visualIndex(i);
79 obj[QSL("header_%1_size").arg(i)] = header()->sectionSize(i);
80 obj[QSL("header_%1_hidden").arg(i)] = header()->isSectionHidden(i);
81 }
82
83 // Store sort attributes.
84 SortColumnsAndOrders orders = m_sourceModel->sortColumnAndOrders();
85
86 obj[QSL("sort_count")] = orders.m_columns.size();
87
88 for (int i = 0; i < orders.m_columns.size(); i++) {
89 obj[QSL("sort_%1_order").arg(i)] = orders.m_orders.at(i);
90 obj[QSL("sort_%1_column").arg(i)] = orders.m_columns.at(i);
91 }
92
93 return QJsonDocument(obj).toJson(QJsonDocument::JsonFormat::Compact);
94 }
95
96 void MessagesView::restoreHeaderState(const QByteArray& dta) {
97 QJsonObject obj = QJsonDocument::fromJson(dta).object();
98 int saved_header_count = obj[QSL("header_count")].toInt();
99
100 if (saved_header_count < header()->count()) {
101 qWarningNN << LOGSEC_GUI << "Detected invalid state for article list.";
102 return;
103 }
104
105 int last_visible_column = 0;
106
107 // Restore column attributes.
108 for (int i = 0; i < saved_header_count && i < header()->count(); i++) {
109 int vi = obj[QSL("header_%1_idx").arg(i)].toInt();
110 int ss = obj[QSL("header_%1_size").arg(i)].toInt();
111 bool ish = obj[QSL("header_%1_hidden").arg(i)].toBool();
112
113 if (vi < header()->count()) {
114 header()->swapSections(header()->visualIndex(i), vi);
115 }
116
117 header()->resizeSection(i, ss);
118 header()->setSectionHidden(i, ish);
119
120 if (!ish && vi > last_visible_column) {
121 last_visible_column = vi;
122 }
123 }
124
125 // All columns are resizeable but last one is set to auto-stretch to fill remaining
126 // space. Sometimes this column is saved as too wide and causes
127 // horizontal scrollbar to appear. Therefore downsize it.
128 header()->resizeSection(header()->logicalIndex(last_visible_column), 1);
129
130 // Restore sort attributes.
131 int saved_sort_count = obj[QSL("sort_count")].toInt();
132
133 for (int i = saved_sort_count - 1; i > 0; i--) {
134 auto col = obj[QSL("sort_%1_column").arg(i)].toInt();
135 auto ordr = Qt::SortOrder(obj[QSL("sort_%1_order").arg(i)].toInt());
136
137 if (col < header()->count()) {
138 m_sourceModel->addSortState(col, ordr, false);
139 }
140 }
141
142 // Use newest sort as active.
143 if (saved_sort_count > 0) {
144 auto newest_col = obj[QSL("sort_0_column")].toInt();
145 auto newest_ordr = Qt::SortOrder(obj[QSL("sort_0_order")].toInt());
146
147 if (newest_col < header()->count()) {
148 header()->setSortIndicator(newest_col, newest_ordr);
149 }
150 }
151 }
152
153 void MessagesView::copyUrlOfSelectedArticles() const {
154 const QModelIndexList selected_indexes = selectionModel()->selectedRows();
155
156 if (selected_indexes.isEmpty()) {
157 return;
158 }
159
160 const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
161 QStringList urls;
162
163 for (const auto article_idx : mapped_indexes) {
164 urls << m_sourceModel->data(m_sourceModel->index(article_idx.row(), MSG_DB_URL_INDEX), Qt::ItemDataRole::EditRole)
165 .toString();
166 }
167
168 if (QGuiApplication::clipboard() != nullptr && !urls.isEmpty()) {
169 QGuiApplication::clipboard()->setText(urls.join(TextFactory::newline()), QClipboard::Mode::Clipboard);
170 }
171 }
172
173 void MessagesView::sort(int column,
174 Qt::SortOrder order,
175 bool repopulate_data,
176 bool change_header,
177 bool emit_changed_from_header,
178 bool ignore_multicolumn_sorting,
179 int additional_article_id) {
180 if (change_header && !emit_changed_from_header) {
181 header()->blockSignals(true);
182 }
183
184 m_sourceModel->addSortState(column, order, ignore_multicolumn_sorting);
185 m_proxyModel->setAdditionalArticleId(additional_article_id);
186
187 if (repopulate_data) {
188 m_sourceModel->repopulate(additional_article_id);
189 }
190
191 if (change_header) {
192 header()->setSortIndicator(column, order);
193 header()->blockSignals(false);
194 }
195 }
196
197 void MessagesView::createConnections() {
198 connect(this, &MessagesView::doubleClicked, this, &MessagesView::openSelectedSourceMessagesExternally);
199
200 // Adjust columns when layout gets changed.
201 connect(header(), &QHeaderView::geometriesChanged, this, &MessagesView::adjustColumns);
202 connect(header(), &QHeaderView::sortIndicatorChanged, this, &MessagesView::onSortIndicatorChanged);
203 }
204
205 void MessagesView::keyboardSearch(const QString& search) {
206 // WARNING: This is quite hacky way how to force selection of next item even
207 // with extended selection enabled.
208 setSelectionMode(QAbstractItemView::SelectionMode::SingleSelection);
209 QTreeView::keyboardSearch(search);
210 setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);
211 }
212
213 void MessagesView::reloadSelections() {
214 bool force_load_currently_selected_article = true;
215
216 const QDateTime dt1 = QDateTime::currentDateTime();
217 QModelIndex current_index = selectionModel()->currentIndex();
218 const bool is_current_selected =
219 selectionModel()->selectedRows().contains(m_proxyModel->index(current_index.row(), 0, current_index.parent()));
220 const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index);
221 const int selected_message_id =
222 m_sourceModel->data(mapped_current_index.row(), MSG_DB_ID_INDEX, Qt::ItemDataRole::EditRole).toInt();
223 const int col = header()->sortIndicatorSection();
224 const Qt::SortOrder ord = header()->sortIndicatorOrder();
225 bool do_not_mark_read_on_select = false;
226
227 // Reload the model now.
228 sort(col, ord, true, false, false, true, force_load_currently_selected_article ? selected_message_id : 0);
229
230 // Now, we must find the same previously focused message.
231 if (selected_message_id > 0) {
232 if (m_proxyModel->rowCount() == 0 || !is_current_selected) {
233 current_index = QModelIndex();
234 }
235 else {
236 for (int i = 0; i < m_proxyModel->rowCount(); i++) {
237 QModelIndex msg_idx = m_proxyModel->index(i, MSG_DB_TITLE_INDEX);
238 QModelIndex msg_source_idx = m_proxyModel->mapToSource(msg_idx);
239 int msg_id = m_sourceModel->data(msg_source_idx.row(), MSG_DB_ID_INDEX, Qt::ItemDataRole::EditRole).toInt();
240
241 if (msg_id == selected_message_id) {
242 current_index = msg_idx;
243
244 if (!m_sourceModel->data(msg_source_idx.row(), MSG_DB_READ_INDEX, Qt::ItemDataRole::EditRole)
245 .toBool() /* && selected_message.m_isRead */) {
246 do_not_mark_read_on_select = true;
247 }
248
249 break;
250 }
251
252 if (i == m_proxyModel->rowCount() - 1) {
253 current_index = QModelIndex();
254 }
255 }
256 }
257 }
258
259 if (current_index.isValid()) {
260 scrollTo(current_index);
261
262 m_processingRightMouseButton = do_not_mark_read_on_select;
263
264 setCurrentIndex(current_index);
265 reselectIndexes({current_index});
266
267 m_processingRightMouseButton = false;
268 }
269 else {
270 // Messages were probably removed from the model, nothing can
271 // be selected and no message can be displayed.
272 emit currentMessageRemoved(m_sourceModel->loadedItem());
273 }
274
275 const QDateTime dt2 = QDateTime::currentDateTime();
276
277 qDebugNN << LOGSEC_GUI << "Reloading of msg selections took " << dt1.msecsTo(dt2) << " miliseconds.";
278 }
279
280 void MessagesView::setupAppearance() {
281 if (qApp->settings()->value(GROUP(Messages), SETTING(Messages::MultilineArticleList)).toBool()) {
282 // Enable some word wrapping for multiline list items.
283 //
284 // NOTE: If user explicitly changed height of rows, then respect this even if he enabled multiline support.
285 setUniformRowHeights(qApp->settings()->value(GROUP(GUI), SETTING(GUI::HeightRowMessages)).toInt() > 0);
286 setWordWrap(true);
287 setTextElideMode(Qt::TextElideMode::ElideNone);
288 }
289 else {
290 setUniformRowHeights(true);
291 setWordWrap(false);
292 setTextElideMode(Qt::TextElideMode::ElideRight);
293 }
294
295 setFocusPolicy(Qt::FocusPolicy::StrongFocus);
296 setAcceptDrops(false);
297 setDragEnabled(false);
298 setDragDropMode(QAbstractItemView::DragDropMode::NoDragDrop);
299 setExpandsOnDoubleClick(false);
300 setRootIsDecorated(false);
301 setEditTriggers(QAbstractItemView::EditTrigger::NoEditTriggers);
302 setItemsExpandable(false);
303 setSortingEnabled(true);
304 setAllColumnsShowFocus(false);
305 setSelectionMode(QAbstractItemView::SelectionMode::ExtendedSelection);
306 setItemDelegate(new StyledItemDelegateWithoutFocus(qApp->settings()
307 ->value(GROUP(GUI), SETTING(GUI::HeightRowMessages))
308 .toInt(),
309 qApp->settings()
310 ->value(GROUP(Messages), SETTING(Messages::ArticleListPadding))
311 .toInt(),
312 this));
313
314 header()->setDefaultSectionSize(MESSAGES_VIEW_DEFAULT_COL);
315 header()->setMinimumSectionSize(MESSAGES_VIEW_MINIMUM_COL);
316 header()->setFirstSectionMovable(true);
317 header()->setCascadingSectionResizes(false);
318 header()->setStretchLastSection(true);
319
320 adjustColumns();
321 }
322
323 void MessagesView::focusInEvent(QFocusEvent* event) {
324 QTreeView::focusInEvent(event);
325
326 qDebugNN << LOGSEC_GUI << "Message list got focus with reason" << QUOTE_W_SPACE_DOT(event->reason());
327
328 if ((event->reason() == Qt::FocusReason::TabFocusReason || event->reason() == Qt::FocusReason::BacktabFocusReason ||
329 event->reason() == Qt::FocusReason::ShortcutFocusReason) &&
330 currentIndex().isValid()) {
331 selectionModel()->select(currentIndex(),
332 QItemSelectionModel::SelectionFlag::Select | QItemSelectionModel::SelectionFlag::Rows);
333 }
334 }
335
336 void MessagesView::keyPressEvent(QKeyEvent* event) {
337 BaseTreeView::keyPressEvent(event);
338
339 if (event->key() == Qt::Key::Key_Delete) {
340 deleteSelectedMessages();
341 }
342 else if (event->key() == Qt::Key::Key_Backspace) {
343 restoreSelectedMessages();
344 }
345 }
346
347 void MessagesView::contextMenuEvent(QContextMenuEvent* event) {
348 const QModelIndex clicked_index = indexAt(event->pos());
349
350 if (!clicked_index.isValid()) {
351 TreeViewColumnsMenu menu(header());
352
353 menu.exec(event->globalPos());
354 }
355 else {
356 // Context menu is not initialized, initialize.
357 initializeContextMenu();
358 m_contextMenu->exec(event->globalPos());
359 }
360 }
361
362 void MessagesView::initializeContextMenu() {
363 if (m_contextMenu == nullptr) {
364 m_contextMenu = new QMenu(tr("Context menu for articles"), this);
365 }
366
367 m_contextMenu->clear();
368 QList<Message> selected_messages;
369
370 if (m_sourceModel->loadedItem() != nullptr) {
371 QModelIndexList selected_indexes = selectionModel()->selectedRows();
372 const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
373 auto rows = boolinq::from(mapped_indexes)
374 .select([](const QModelIndex& idx) {
375 return idx.row();
376 })
377 .toStdList();
378
379 selected_messages = m_sourceModel->messagesAt(FROM_STD_LIST(QList<int>, rows));
380 }
381
382 // External tools.
383 QFileIconProvider icon_provider;
384 QMenu* menu_ext_tools = new QMenu(tr("Open with external tool"), m_contextMenu);
385 auto tools = ExternalTool::toolsFromSettings();
386
387 menu_ext_tools->setIcon(qApp->icons()->fromTheme(QSL("document-open")));
388
389 for (const ExternalTool& tool : std::as_const(tools)) {
390 QAction* act_tool = new QAction(QFileInfo(tool.executable()).fileName(), menu_ext_tools);
391
392 act_tool->setIcon(icon_provider.icon(QFileInfo(tool.executable())));
393 act_tool->setToolTip(tool.executable());
394 act_tool->setData(QVariant::fromValue(tool));
395 menu_ext_tools->addAction(act_tool);
396
397 connect(act_tool, &QAction::triggered, this, &MessagesView::openSelectedMessagesWithExternalTool);
398 }
399
400 if (menu_ext_tools->actions().isEmpty()) {
401 QAction* act_not_tools = new QAction(tr("No external tools activated"));
402
403 act_not_tools->setEnabled(false);
404 menu_ext_tools->addAction(act_not_tools);
405 }
406
407 // Labels.
408 auto labels = m_sourceModel->loadedItem() != nullptr
409 ? m_sourceModel->loadedItem()->getParentServiceRoot()->labelsNode()->labels()
410 : QList<Label*>();
411 LabelsMenu* menu_labels = new LabelsMenu(selected_messages, labels, m_contextMenu);
412
413 connect(menu_labels, &LabelsMenu::labelsChanged, this, [this]() {
414 QModelIndex current_index = selectionModel()->currentIndex();
415
416 if (current_index.isValid()) {
417 emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()),
418 m_sourceModel->loadedItem());
419 }
420 else {
421 emit currentMessageRemoved(m_sourceModel->loadedItem());
422 }
423 });
424
425 // Rest.
426 m_contextMenu->addMenu(menu_ext_tools);
427 m_contextMenu->addMenu(menu_labels);
428 m_contextMenu->addActions(QList<QAction*>() << qApp->mainForm()->m_ui->m_actionSendMessageViaEmail
429 << qApp->mainForm()->m_ui->m_actionOpenSelectedSourceArticlesExternally
430 << qApp->mainForm()->m_ui->m_actionOpenSelectedMessagesInternally
431 << qApp->mainForm()->m_ui->m_actionOpenSelectedMessagesInternallyNoTab
432 << qApp->mainForm()->m_ui->m_actionPlaySelectedArticlesInMediaPlayer
433 << qApp->mainForm()->m_ui->m_actionCopyUrlSelectedArticles
434 << qApp->mainForm()->m_ui->m_actionMarkSelectedMessagesAsRead
435 << qApp->mainForm()->m_ui->m_actionMarkSelectedMessagesAsUnread
436 << qApp->mainForm()->m_ui->m_actionSwitchImportanceOfSelectedMessages
437 << qApp->mainForm()->m_ui->m_actionDeleteSelectedMessages);
438
439 if (m_sourceModel->loadedItem() != nullptr) {
440 if (m_sourceModel->loadedItem()->kind() == RootItem::Kind::Bin) {
441 m_contextMenu->addAction(qApp->mainForm()->m_ui->m_actionRestoreSelectedMessages);
442 }
443
444 auto extra_context_menu =
445 m_sourceModel->loadedItem()->getParentServiceRoot()->contextMenuMessagesList(selected_messages);
446
447 if (!extra_context_menu.isEmpty()) {
448 m_contextMenu->addSeparator();
449 m_contextMenu->addActions(extra_context_menu);
450 }
451 }
452 }
453
454 void MessagesView::mousePressEvent(QMouseEvent* event) {
455 m_processingAnyMouseButton = true;
456 m_processingRightMouseButton = event->button() == Qt::MouseButton::RightButton;
457
458 QTreeView::mousePressEvent(event);
459
460 m_processingAnyMouseButton = false;
461 m_processingRightMouseButton = false;
462
463 switch (event->button()) {
464 case Qt::MouseButton::LeftButton: {
465 // Make sure that message importance is switched when user
466 // clicks the "important" column.
467 const QModelIndex clicked_index = indexAt(event->pos());
468
469 if (clicked_index.isValid()) {
470 const QModelIndex mapped_index = m_proxyModel->mapToSource(clicked_index);
471
472 if (mapped_index.column() == MSG_DB_IMPORTANT_INDEX) {
473 if (m_sourceModel->switchMessageImportance(mapped_index.row())) {
474 emit currentMessageChanged(m_sourceModel->messageAt(mapped_index.row()), m_sourceModel->loadedItem());
475 }
476 }
477 else if (mapped_index.column() == MSG_DB_READ_INDEX) {
478 if (m_sourceModel->switchMessageReadUnread(mapped_index.row())) {
479 emit currentMessageChanged(m_sourceModel->messageAt(mapped_index.row()), m_sourceModel->loadedItem());
480 }
481 }
482 }
483
484 break;
485 }
486
487 case Qt::MouseButton::MiddleButton: {
488 // Make sure that message importance is switched when user
489 // clicks the "important" column.
490 const QModelIndex clicked_index = indexAt(event->pos());
491
492 if (clicked_index.isValid()) {
493 const QModelIndex mapped_index = m_proxyModel->mapToSource(clicked_index);
494 const QString url = m_sourceModel->messageAt(mapped_index.row()).m_url;
495
496 if (!url.isEmpty()) {
497 qApp->mainForm()->tabWidget()->addLinkedBrowser(url);
498 }
499 }
500
501 break;
502 }
503
504 default:
505 break;
506 }
507 }
508
509 void MessagesView::mouseMoveEvent(QMouseEvent* event) {
510 event->accept();
511 }
512
513 void MessagesView::selectionChanged(const QItemSelection& selected, const QItemSelection& deselected) {
514 const QModelIndexList selected_rows = selectionModel()->selectedRows();
515 const QModelIndex current_index = currentIndex();
516 const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index);
517
518 qDebugNN << LOGSEC_GUI << "Current row changed - proxy '" << current_index << "', source '" << mapped_current_index
519 << "'.";
520
521 if (mapped_current_index.isValid() && selected_rows.size() == 1) {
522 Message message = m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row());
523
524 // Set this message as read only if current item
525 // wasn't changed by "mark selected messages unread" action.
526 if (!m_processingRightMouseButton) {
527 if (!message.m_isRead) {
528 if (m_articleMarkingPolicy == ArticleMarkingPolicy::MarkImmediately) {
529 qDebugNN << LOGSEC_GUI << "Marking article as read immediately.";
530
531 m_sourceModel->setMessageRead(mapped_current_index.row(), RootItem::ReadStatus::Read);
532 message.m_isRead = true;
533 }
534 else if (m_articleMarkingPolicy == ArticleMarkingPolicy::MarkWithDelay) {
535 qDebugNN << LOGSEC_GUI << "(Re)Starting timer to mark article as read with a delay.";
536 m_delayedArticleIndex = current_index;
537 m_delayedArticleMarker.start();
538 }
539 else {
540 // NOTE: Article can only be marked as read manually, so just change.
541 }
542 }
543 }
544
545 emit currentMessageChanged(message, m_sourceModel->loadedItem());
546 }
547 else {
548 emit currentMessageRemoved(m_sourceModel->loadedItem());
549 }
550
551 if (selected_rows.isEmpty()) {
552 setCurrentIndex({});
553 }
554
555 if (!m_processingAnyMouseButton &&
556 qApp->settings()->value(GROUP(Messages), SETTING(Messages::KeepCursorInCenter)).toBool()) {
557 scrollTo(currentIndex(), QAbstractItemView::ScrollHint::PositionAtCenter);
558 }
559
560 QTreeView::selectionChanged(selected, deselected);
561 }
562
563 void MessagesView::markSelectedMessagesReadDelayed() {
564 qDebugNN << LOGSEC_GUI << "Delay has passed! Marking article as read NOW.";
565
566 const QModelIndexList selected_rows = selectionModel()->selectedRows();
567 const QModelIndex current_index = m_delayedArticleIndex;
568
569 if (selected_rows.size() == 1 && current_index.isValid() && !m_processingRightMouseButton &&
570 m_articleMarkingPolicy == ArticleMarkingPolicy::MarkWithDelay) {
571 const QModelIndex mapped_current_index = m_proxyModel->mapToSource(current_index);
572 Message message = m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row());
573
574 m_sourceModel->setMessageRead(mapped_current_index.row(), RootItem::ReadStatus::Read);
575 message.m_isRead = true;
576 emit currentMessageChanged(message, m_sourceModel->loadedItem());
577 }
578 }
579
580 void MessagesView::loadItem(RootItem* item) {
581 m_delayedArticleMarker.stop();
582
583 const int col = header()->sortIndicatorSection();
584 const Qt::SortOrder ord = header()->sortIndicatorOrder();
585
586 scrollToTop();
587 sort(col, ord, false, true, false, true);
588 m_sourceModel->loadMessages(item);
589
590 bool switch_entire_rtl_list =
591 qApp->settings()->value(GROUP(Messages), SETTING(Messages::SwitchArticleListRtl)).toBool();
592
593 if (switch_entire_rtl_list && item != nullptr) {
594 if (item->kind() == RootItem::Kind::Feed) {
595 auto* fd = item->toFeed();
596 setLayoutDirection((fd->rtlBehavior() == RtlBehavior::Everywhere ||
597 fd->rtlBehavior() == RtlBehavior::EverywhereExceptFeedList)
598 ? Qt::LayoutDirection::RightToLeft
599 : Qt::LayoutDirection::LayoutDirectionAuto);
600 }
601 else {
602 auto fds = item->getSubTreeFeeds();
603 bool all_feeds_rtl = !fds.isEmpty() && std::all_of(fds.begin(), fds.end(), [](Feed* fd) {
604 return fd->rtlBehavior() == RtlBehavior::Everywhere ||
605 fd->rtlBehavior() == RtlBehavior::EverywhereExceptFeedList;
606 });
607
608 setLayoutDirection(all_feeds_rtl ? Qt::LayoutDirection::RightToLeft : Qt::LayoutDirection::LayoutDirectionAuto);
609 }
610 }
611 else {
612 setLayoutDirection(Qt::LayoutDirection::LayoutDirectionAuto);
613 }
614
615 // Messages are loaded, make sure that previously
616 // active message is not shown in browser.
617 emit currentMessageRemoved(m_sourceModel->loadedItem());
618 }
619
620 void MessagesView::changeFilter(MessagesProxyModel::MessageListFilter filter) {
621 m_proxyModel->setMessageListFilter(filter);
622 reloadSelections();
623 }
624
625 void MessagesView::openSelectedSourceMessagesExternally() {
626 auto rws = selectionModel()->selectedRows();
627
628 for (const QModelIndex& index : std::as_const(rws)) {
629 QString link = m_sourceModel->messageAt(m_proxyModel->mapToSource(index).row())
630 .m_url.replace(QRegularExpression(QSL("[\\t\\n]")), QString());
631
632 qApp->web()->openUrlInExternalBrowser(link);
633 }
634
635 // Finally, mark opened messages as read.
636 if (!selectionModel()->selectedRows().isEmpty()) {
637 QTimer::singleShot(0, this, &MessagesView::markSelectedMessagesRead);
638 }
639
640 if (qApp->settings()
641 ->value(GROUP(Messages), SETTING(Messages::BringAppToFrontAfterMessageOpenedExternally))
642 .toBool()) {
643 QTimer::singleShot(1000, this, []() {
644 qApp->mainForm()->display();
645 });
646 }
647 }
648
649 #if defined(ENABLE_MEDIAPLAYER)
650 void MessagesView::playSelectedArticleInMediaPlayer() {
651 auto rws = selectionModel()->selectedRows();
652
653 if (!rws.isEmpty()) {
654 auto msg = m_sourceModel->messageAt(m_proxyModel->mapToSource(rws.first()).row());
655
656 if (msg.m_url.isEmpty()) {
657 qApp->showGuiMessage(Notification::Event::GeneralEvent,
658 GuiMessage(tr("No URL"),
659 tr("Article cannot be played in media player as it has no URL"),
660 QSystemTrayIcon::MessageIcon::Warning),
661 GuiMessageDestination(true, true));
662 }
663 else {
664 emit playLinkInMediaPlayer(msg.m_url);
665 }
666 }
667 }
668 #endif
669
670 void MessagesView::openSelectedMessagesInternally() {
671 auto rws = selectionModel()->selectedRows();
672
673 if (!rws.isEmpty()) {
674 auto msg = m_sourceModel->messageAt(m_proxyModel->mapToSource(rws.first()).row());
675
676 emit openSingleMessageInNewTab(m_sourceModel->loadedItem(), msg);
677 }
678 }
679
680 void MessagesView::openSelectedMessageUrl() {
681 auto rws = selectionModel()->selectedRows();
682
683 if (!rws.isEmpty()) {
684 auto msg = m_sourceModel->messageAt(m_proxyModel->mapToSource(rws.at(0)).row());
685
686 if (!msg.m_url.isEmpty()) {
687 emit openLinkMiniBrowser(msg.m_url);
688 }
689 }
690 }
691
692 void MessagesView::sendSelectedMessageViaEmail() {
693 if (selectionModel()->selectedRows().size() == 1) {
694 const Message message =
695 m_sourceModel->messageAt(m_proxyModel->mapToSource(selectionModel()->selectedRows().at(0)).row());
696
697 if (!qApp->web()->sendMessageViaEmail(message)) {
698 MsgBox::show(this,
699 QMessageBox::Critical,
700 tr("Problem with starting external e-mail client"),
701 tr("External e-mail client could not be started."));
702 }
703 }
704 }
705
706 void MessagesView::markSelectedMessagesRead() {
707 setSelectedMessagesReadStatus(RootItem::ReadStatus::Read);
708 }
709
710 void MessagesView::markSelectedMessagesUnread() {
711 setSelectedMessagesReadStatus(RootItem::ReadStatus::Unread);
712 }
713
714 void MessagesView::setSelectedMessagesReadStatus(RootItem::ReadStatus read) {
715 const QModelIndexList selected_indexes = selectionModel()->selectedRows();
716
717 if (selected_indexes.isEmpty()) {
718 return;
719 }
720
721 const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
722
723 m_sourceModel->setBatchMessagesRead(mapped_indexes, read);
724 QModelIndex current_index = selectionModel()->currentIndex();
725
726 if (current_index.isValid() && selected_indexes.size() == 1) {
727 emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()),
728 m_sourceModel->loadedItem());
729 }
730 else {
731 emit currentMessageRemoved(m_sourceModel->loadedItem());
732 }
733 }
734
735 void MessagesView::deleteSelectedMessages() {
736 const QModelIndexList selected_indexes = selectionModel()->selectedRows();
737
738 if (selected_indexes.isEmpty()) {
739 return;
740 }
741
742 const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
743
744 m_sourceModel->setBatchMessagesDeleted(mapped_indexes);
745 QModelIndex current_index =
746 currentIndex().isValid() ? moveCursor(QAbstractItemView::CursorAction::MoveDown, Qt::KeyboardModifier::NoModifier)
747 : currentIndex();
748
749 if (current_index.isValid() && selected_indexes.size() == 1) {
750 setCurrentIndex(current_index);
751 }
752 else {
753 emit currentMessageRemoved(m_sourceModel->loadedItem());
754 }
755 }
756
757 void MessagesView::restoreSelectedMessages() {
758 QModelIndex current_index = selectionModel()->currentIndex();
759
760 if (!current_index.isValid()) {
761 return;
762 }
763
764 const QModelIndexList selected_indexes = selectionModel()->selectedRows();
765 const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
766
767 m_sourceModel->setBatchMessagesRestored(mapped_indexes);
768 current_index = m_proxyModel->index(current_index.row(), current_index.column());
769
770 if (current_index.isValid()) {
771 emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()),
772 m_sourceModel->loadedItem());
773 }
774 else {
775 emit currentMessageRemoved(m_sourceModel->loadedItem());
776 }
777 }
778
779 void MessagesView::switchSelectedMessagesImportance() {
780 const QModelIndexList selected_indexes = selectionModel()->selectedRows();
781
782 if (selected_indexes.isEmpty()) {
783 return;
784 }
785
786 const QModelIndexList mapped_indexes = m_proxyModel->mapListToSource(selected_indexes);
787
788 m_sourceModel->switchBatchMessageImportance(mapped_indexes);
789 QModelIndex current_index = selectionModel()->currentIndex();
790
791 if (current_index.isValid() && selected_indexes.size() == 1) {
792 emit currentMessageChanged(m_sourceModel->messageAt(m_proxyModel->mapToSource(current_index).row()),
793 m_sourceModel->loadedItem());
794 }
795 else {
796 // Messages were probably removed from the model, nothing can
797 // be selected and no message can be displayed.
798 emit currentMessageRemoved(m_sourceModel->loadedItem());
799 }
800 }
801
802 void MessagesView::reselectIndexes(const QModelIndexList& indexes) {
803 if (indexes.size() < RESELECT_MESSAGE_THRESSHOLD) {
804 QItemSelection selection;
805
806 for (const QModelIndex& index : indexes) {
807 selection.merge(QItemSelection(index, index), QItemSelectionModel::Select);
808 }
809
810 selectionModel()->select(selection, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows);
811 }
812 }
813
814 void MessagesView::selectNextItem() {
815 selectItemWithCursorAction(QAbstractItemView::CursorAction::MoveDown);
816 }
817
818 void MessagesView::selectPreviousItem() {
819 selectItemWithCursorAction(QAbstractItemView::CursorAction::MoveUp);
820 }
821
822 void MessagesView::selectItemWithCursorAction(CursorAction act) {
823 const QModelIndex index_previous = moveCursor(act, Qt::KeyboardModifier::NoModifier);
824
825 if (index_previous.isValid()) {
826 setCurrentIndex(index_previous);
827 setFocus();
828 }
829 }
830
831 void MessagesView::selectNextUnreadItem() {
832 const QModelIndexList selected_rows = selectionModel()->selectedRows();
833 int active_row;
834
835 if (!selected_rows.isEmpty()) {
836 // Okay, something is selected, start from it.
837 active_row = selected_rows.at(0).row();
838 }
839 else {
840 active_row = 0;
841 }
842
843 const QModelIndex next_unread = m_proxyModel->getNextPreviousUnreadItemIndex(active_row);
844
845 if (next_unread.isValid()) {
846 setCurrentIndex(next_unread);
847 setFocus();
848 }
849 }
850
851 void MessagesView::searchMessages(SearchLineEdit::SearchMode mode,
852 Qt::CaseSensitivity sensitivity,
853 int custom_criteria,
854 const QString& phrase) {
855 qDebugNN << LOGSEC_GUI << "Running search of messages with pattern" << QUOTE_W_SPACE_DOT(phrase);
856
857 switch (mode) {
858 case SearchLineEdit::SearchMode::Wildcard:
859 m_proxyModel->setFilterWildcard(phrase);
860 break;
861
862 case SearchLineEdit::SearchMode::RegularExpression:
863 m_proxyModel->setFilterRegularExpression(phrase);
864 break;
865
866 case SearchLineEdit::SearchMode::FixedString:
867 default:
868 m_proxyModel->setFilterFixedString(phrase);
869 break;
870 }
871
872 m_proxyModel->setFilterCaseSensitivity(sensitivity);
873
874 BaseToolBar::SearchFields where_search = BaseToolBar::SearchFields(custom_criteria);
875
876 m_proxyModel->setFilterKeyColumn(where_search == BaseToolBar::SearchFields::SearchTitleOnly ? MSG_DB_TITLE_INDEX
877 : -1);
878
879 if (selectionModel()->selectedRows().isEmpty()) {
880 emit currentMessageRemoved(m_sourceModel->loadedItem());
881 }
882 else {
883 // Scroll to selected message, it could become scrolled out due to filter change.
884 scrollTo(selectionModel()->selectedRows().at(0),
885 !m_processingAnyMouseButton &&
886 qApp->settings()->value(GROUP(Messages), SETTING(Messages::KeepCursorInCenter)).toBool()
887 ? QAbstractItemView::ScrollHint::PositionAtCenter
888 : QAbstractItemView::ScrollHint::EnsureVisible);
889 }
890 }
891
892 void MessagesView::highlightMessages(MessagesModel::MessageHighlighter highlighter) {
893 m_sourceModel->highlightMessages(highlighter);
894 }
895
896 void MessagesView::openSelectedMessagesWithExternalTool() {
897 auto* sndr = qobject_cast<QAction*>(sender());
898
899 if (sndr != nullptr) {
900 auto tool = sndr->data().value<ExternalTool>();
901 auto rws = selectionModel()->selectedRows();
902
903 for (const QModelIndex& index : std::as_const(rws)) {
904 const QString link =
905 m_sourceModel->data(m_proxyModel->mapToSource(index).row(), MSG_DB_URL_INDEX, Qt::ItemDataRole::EditRole)
906 .toString()
907 .replace(QRegularExpression(QSL("[\\t\\n]")), QString());
908
909 if (!link.isEmpty()) {
910 if (!tool.run(link)) {
911 qApp->showGuiMessage(Notification::Event::GeneralEvent,
912 {tr("Cannot run external tool"),
913 tr("External tool '%1' could not be started.").arg(tool.executable()),
914 QSystemTrayIcon::MessageIcon::Critical});
915 }
916 }
917 }
918 }
919 }
920
921 void MessagesView::adjustColumns() {
922 qDebugNN << LOGSEC_GUI << "Article list header geometries changed.";
923
924 if (header()->count() > 0 && !m_columnsAdjusted) {
925 m_columnsAdjusted = true;
926
927 // Setup column resize strategies.
928 for (int i = 0; i < header()->count(); i++) {
929 header()->setSectionResizeMode(i, QHeaderView::ResizeMode::Interactive);
930 }
931
932 // Hide columns.
933 hideColumn(MSG_DB_ID_INDEX);
934 hideColumn(MSG_DB_DELETED_INDEX);
935 hideColumn(MSG_DB_URL_INDEX);
936 hideColumn(MSG_DB_CONTENTS_INDEX);
937 hideColumn(MSG_DB_PDELETED_INDEX);
938 hideColumn(MSG_DB_ENCLOSURES_INDEX);
939 hideColumn(MSG_DB_SCORE_INDEX);
940 hideColumn(MSG_DB_ACCOUNT_ID_INDEX);
941 hideColumn(MSG_DB_CUSTOM_ID_INDEX);
942 hideColumn(MSG_DB_CUSTOM_HASH_INDEX);
943 hideColumn(MSG_DB_FEED_CUSTOM_ID_INDEX);
944 hideColumn(MSG_DB_FEED_TITLE_INDEX);
945 hideColumn(MSG_DB_FEED_IS_RTL_INDEX);
946 hideColumn(MSG_DB_HAS_ENCLOSURES);
947 hideColumn(MSG_DB_LABELS);
948 hideColumn(MSG_DB_LABELS_IDS);
949 }
950 }
951
952 void MessagesView::onSortIndicatorChanged(int column, Qt::SortOrder order) {
953 // Repopulate the shit.
954 sort(column, order, true, false, false, false);
955
956 emit currentMessageRemoved(m_sourceModel->loadedItem());
957 }