Colorize collapsed threads based on aggregated tags
[trojita.git] / src / Gui / Window.cpp
blobc6fb1379d91833bafbd12f98d97b91702bf8c03a
1 /* Copyright (C) 2006 - 2015 Jan Kundrát <jkt@flaska.net>
2 Copyright (C) 2013 - 2015 Pali Rohár <pali.rohar@gmail.com>
4 This file is part of the Trojita Qt IMAP e-mail client,
5 http://trojita.flaska.net/
7 This program is free software; you can redistribute it and/or
8 modify it under the terms of the GNU General Public License as
9 published by the Free Software Foundation; either version 2 of
10 the License or (at your option) version 3 or any later version
11 accepted by the membership of KDE e.V. (or its successor approved
12 by the membership of KDE e.V.), which shall act as a proxy
13 defined in Section 14 of version 3 of the license.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include <QAuthenticator>
25 #include <QDesktopServices>
26 #include <QDesktopWidget>
27 #include <QDir>
28 #include <QDockWidget>
29 #include <QFileDialog>
30 #include <QHeaderView>
31 #include <QItemSelectionModel>
32 #include <QKeyEvent>
33 #include <QMenuBar>
34 #include <QMessageBox>
35 #include <QProgressBar>
36 #include <QScrollBar>
37 #include <QSplitter>
38 #include <QSslError>
39 #include <QSslKey>
40 #include <QStackedWidget>
41 #include <QStatusBar>
42 #include <QTextDocument>
43 #include <QToolBar>
44 #include <QToolButton>
45 #include <QToolTip>
46 #include <QUrl>
47 #include <QWheelEvent>
49 #include "configure.cmake.h"
50 #include "Common/Application.h"
51 #include "Common/Paths.h"
52 #include "Common/PortNumbers.h"
53 #include "Common/SettingsNames.h"
54 #include "Composer/Mailto.h"
55 #include "Composer/SenderIdentitiesModel.h"
56 #ifdef TROJITA_HAVE_CRYPTO_MESSAGES
57 # ifdef TROJITA_HAVE_GPGMEPP
58 # include "Cryptography/GpgMe++.h"
59 # endif
60 #endif
61 #include "Imap/Model/ImapAccess.h"
62 #include "Imap/Model/MailboxTree.h"
63 #include "Imap/Model/Model.h"
64 #include "Imap/Model/ModelWatcher.h"
65 #include "Imap/Model/MsgListModel.h"
66 #include "Imap/Model/NetworkWatcher.h"
67 #include "Imap/Model/PrettyMailboxModel.h"
68 #include "Imap/Model/PrettyMsgListModel.h"
69 #include "Imap/Model/SpecialFlagNames.h"
70 #include "Imap/Model/ThreadingMsgListModel.h"
71 #include "Imap/Model/FavoriteTagsModel.h"
72 #include "Imap/Model/Utils.h"
73 #include "Imap/Tasks/ImapTask.h"
74 #include "Imap/Network/FileDownloadManager.h"
75 #include "MSA/ImapSubmit.h"
76 #include "MSA/Sendmail.h"
77 #include "MSA/SMTP.h"
78 #include "Plugins/AddressbookPlugin.h"
79 #include "Plugins/PasswordPlugin.h"
80 #include "Plugins/PluginManager.h"
81 #include "CompleteMessageWidget.h"
82 #include "ComposeWidget.h"
83 #include "MailBoxTreeView.h"
84 #include "MessageListWidget.h"
85 #include "MessageView.h"
86 #include "MessageSourceWidget.h"
87 #include "Gui/MessageHeadersWidget.h"
88 #include "MsgListView.h"
89 #include "OnePanelAtTimeWidget.h"
90 #include "PasswordDialog.h"
91 #include "ProtocolLoggerWidget.h"
92 #include "SettingsDialog.h"
93 #include "SimplePartWidget.h"
94 #include "Streams/SocketFactory.h"
95 #include "TaskProgressIndicator.h"
96 #include "Util.h"
97 #include "Window.h"
98 #include "ShortcutHandler/ShortcutHandler.h"
100 #include "ui_CreateMailboxDialog.h"
101 #include "ui_AboutDialog.h"
103 #include "Imap/Model/ModelTest/modeltest.h"
104 #include "UiUtils/IconLoader.h"
105 #include "UiUtils/QaimDfsIterator.h"
107 /** @short All user-facing widgets and related classes */
108 namespace Gui
111 static const char * const netErrorUnseen = "net_error_unseen";
113 MainWindow::MainWindow(QSettings *settings): QMainWindow(), m_imapAccess(0), m_mainHSplitter(0), m_mainVSplitter(0),
114 m_mainStack(0), m_layoutMode(LAYOUT_COMPACT), m_skipSavingOfUI(true), m_delayedStateSaving(0), m_actionSortNone(0),
115 m_ignoreStoredPassword(false), m_settings(settings), m_pluginManager(0), m_networkErrorMessageBox(0), m_trayIcon(0)
117 setAttribute(Qt::WA_AlwaysShowToolTips);
118 // m_pluginManager must be created before calling createWidgets
119 m_pluginManager = new Plugins::PluginManager(this, m_settings,
120 Common::SettingsNames::addressbookPlugin, Common::SettingsNames::passwordPlugin);
121 connect(m_pluginManager, &Plugins::PluginManager::pluginsChanged, this, &MainWindow::slotPluginsChanged);
122 connect(m_pluginManager, &Plugins::PluginManager::pluginError, this, [this](const QString &errorMessage) {
123 Gui::Util::messageBoxWarning(this, tr("Plugin Error"),
124 //: The %1 placeholder is a full error message as provided by Qt, ready for human consumption.
125 trUtf8("A plugin failed to load, therefore some functionality might be lost. "
126 "You might want to update your system or report a bug to your vendor."
127 "\n\n%1").arg(errorMessage));
129 #ifdef TROJITA_HAVE_CRYPTO_MESSAGES
130 Plugins::PluginManager::MimePartReplacers replacers;
131 #ifdef TROJITA_HAVE_GPGMEPP
132 replacers.emplace_back(std::make_shared<Cryptography::GpgMeReplacer>());
133 #endif
134 m_pluginManager->setMimePartReplacers(replacers);
135 #endif
137 // ImapAccess contains a wrapper for retrieving passwords through some plugin.
138 // That PasswordWatcher is used by the SettingsDialog's widgets *and* by this class,
139 // which means that ImapAccess has to be constructed before we go and open the settings dialog.
141 // FIXME: use another account-id at some point in future
142 // we are now using the profile to avoid overwriting passwords of
143 // other profiles in secure storage
144 QString profileName = QString::fromUtf8(qgetenv("TROJITA_PROFILE"));
145 m_imapAccess = new Imap::ImapAccess(this, m_settings, m_pluginManager, profileName);
146 connect(m_imapAccess, &Imap::ImapAccess::cacheError, this, &MainWindow::cacheError);
147 connect(m_imapAccess, &Imap::ImapAccess::checkSslPolicy, this, &MainWindow::checkSslPolicy, Qt::QueuedConnection);
149 ShortcutHandler *shortcutHandler = new ShortcutHandler(this);
150 shortcutHandler->setSettingsObject(m_settings);
151 defineActions();
152 shortcutHandler->readSettings(); // must happen after defineActions()
154 // must be created before calling createWidgets
155 m_favoriteTags = new Imap::Mailbox::FavoriteTagsModel(this);
156 m_favoriteTags->loadFromSettings(*m_settings);
158 createWidgets();
160 Imap::migrateSettings(m_settings);
162 m_senderIdentities = new Composer::SenderIdentitiesModel(this);
163 m_senderIdentities->loadFromSettings(*m_settings);
165 if (! m_settings->contains(Common::SettingsNames::imapMethodKey)) {
166 QTimer::singleShot(0, this, SLOT(slotShowSettings()));
170 setupModels();
171 createActions();
172 createMenus();
173 slotToggleSysTray();
174 slotPluginsChanged();
176 slotFavoriteTagsChanged();
177 connect(m_favoriteTags, &QAbstractItemModel::modelReset, this, &MainWindow::slotFavoriteTagsChanged);
178 connect(m_favoriteTags, &QAbstractItemModel::layoutChanged, this, &MainWindow::slotFavoriteTagsChanged);
179 connect(m_favoriteTags, &QAbstractItemModel::rowsMoved, this, &MainWindow::slotFavoriteTagsChanged);
180 connect(m_favoriteTags, &QAbstractItemModel::rowsInserted, this, &MainWindow::slotFavoriteTagsChanged);
181 connect(m_favoriteTags, &QAbstractItemModel::rowsRemoved, this, &MainWindow::slotFavoriteTagsChanged);
182 connect(m_favoriteTags, &QAbstractItemModel::dataChanged, this, &MainWindow::slotFavoriteTagsChanged);
184 // Please note that Qt 4.6.1 really requires passing the method signature this way, *not* using the SLOT() macro
185 QDesktopServices::setUrlHandler(QStringLiteral("mailto"), this, "slotComposeMailUrl");
186 QDesktopServices::setUrlHandler(QStringLiteral("x-trojita-manage-contact"), this, "slotManageContact");
188 slotUpdateWindowTitle();
190 recoverDrafts();
192 if (m_actionLayoutWide->isEnabled() &&
193 m_settings->value(Common::SettingsNames::guiMainWindowLayout) == Common::SettingsNames::guiMainWindowLayoutWide) {
194 m_actionLayoutWide->trigger();
195 } else if (m_settings->value(Common::SettingsNames::guiMainWindowLayout) == Common::SettingsNames::guiMainWindowLayoutOneAtTime) {
196 m_actionLayoutOneAtTime->trigger();
197 } else {
198 m_actionLayoutCompact->trigger();
201 connect(qApp, &QGuiApplication::applicationStateChanged, this,
202 [&](Qt::ApplicationState state) {
203 if (state == Qt::ApplicationActive && m_networkErrorMessageBox && m_networkErrorMessageBox->property(netErrorUnseen).toBool()) {
204 m_networkErrorMessageBox->setProperty(netErrorUnseen, false);
205 m_networkErrorMessageBox->show();
209 // Don't listen to QDesktopWidget::resized; that is emitted too early (when it gets fired, the screen size has changed, but
210 // the workspace area is still the old one). Instead, listen to workAreaResized which gets emitted at an appropriate time.
211 // The delay is still there to guarantee some smoothing; on jkt's box there are typically three events in a rapid sequence
212 // (some of them most likely due to the fact that at first, the actual desktop gets resized, the plasma panel reacts
213 // to that and only after the panel gets resized, the available size of "the rest" is correct again).
214 // Which is why it makes sense to introduce some delay in there. The 0.5s delay is my best guess and "should work" (especially
215 // because every change bumps the timer anyway, as Thomas pointed out).
216 QTimer *delayedResize = new QTimer(this);
217 delayedResize->setSingleShot(true);
218 delayedResize->setInterval(500);
219 connect(delayedResize, &QTimer::timeout, this, &MainWindow::desktopGeometryChanged);
220 connect(qApp->desktop(), &QDesktopWidget::workAreaResized, delayedResize, static_cast<void (QTimer::*)()>(&QTimer::start));
221 m_skipSavingOfUI = false;
224 void MainWindow::defineActions()
226 ShortcutHandler *shortcutHandler = ShortcutHandler::instance();
227 shortcutHandler->defineAction(QStringLiteral("action_application_exit"), QStringLiteral("application-exit"), tr("E&xit"), QKeySequence::Quit);
228 shortcutHandler->defineAction(QStringLiteral("action_compose_mail"), QStringLiteral("document-edit"), tr("&New Message..."), QKeySequence::New);
229 shortcutHandler->defineAction(QStringLiteral("action_compose_draft"), QStringLiteral("document-open-recent"), tr("&Edit Draft..."));
230 shortcutHandler->defineAction(QStringLiteral("action_show_menubar"), QStringLiteral("view-list-text"), tr("Show Main Menu &Bar"), tr("Ctrl+M"));
231 shortcutHandler->defineAction(QStringLiteral("action_expunge"), QStringLiteral("trash-empty"), tr("Exp&unge"), tr("Ctrl+E"));
232 shortcutHandler->defineAction(QStringLiteral("action_mark_as_read"), QStringLiteral("mail-mark-read"), tr("Mark as &Read"), QStringLiteral("M"));
233 shortcutHandler->defineAction(QStringLiteral("action_go_to_next_unread"), QStringLiteral("arrow-right"), tr("&Next Unread Message"), QStringLiteral("N"));
234 shortcutHandler->defineAction(QStringLiteral("action_go_to_previous_unread"), QStringLiteral("arrow-left"), tr("&Previous Unread Message"), QStringLiteral("P"));
235 shortcutHandler->defineAction(QStringLiteral("action_mark_as_deleted"), QStringLiteral("list-remove"), tr("Mark as &Deleted"), QKeySequence(Qt::Key_Delete).toString());
236 shortcutHandler->defineAction(QStringLiteral("action_mark_as_flagged"), QStringLiteral("mail-flagged"), tr("Mark as &Flagged"), QStringLiteral("S"));
237 shortcutHandler->defineAction(QStringLiteral("action_mark_as_junk"), QStringLiteral("mail-mark-junk"), tr("Mark as &Junk"), QStringLiteral("J"));
238 shortcutHandler->defineAction(QStringLiteral("action_mark_as_notjunk"), QStringLiteral("mail-mark-notjunk"), tr("Mark as Not &junk"), QStringLiteral("Shift+J"));
239 shortcutHandler->defineAction(QStringLiteral("action_save_message_as"), QStringLiteral("document-save"), tr("&Save Message..."));
240 shortcutHandler->defineAction(QStringLiteral("action_view_message_source"), QString(), tr("View Message &Source..."));
241 shortcutHandler->defineAction(QStringLiteral("action_view_message_headers"), QString(), tr("View Message &Headers..."), tr("Ctrl+U"));
242 shortcutHandler->defineAction(QStringLiteral("action_reply_private"), QStringLiteral("mail-reply-sender"), tr("&Private Reply"), tr("Ctrl+Shift+A"));
243 shortcutHandler->defineAction(QStringLiteral("action_reply_all_but_me"), QStringLiteral("mail-reply-all"), tr("Reply to All &but Me"), tr("Ctrl+Shift+R"));
244 shortcutHandler->defineAction(QStringLiteral("action_reply_all"), QStringLiteral("mail-reply-all"), tr("Reply to &All"), tr("Ctrl+Alt+Shift+R"));
245 shortcutHandler->defineAction(QStringLiteral("action_reply_list"), QStringLiteral("mail-reply-list"), tr("Reply to &Mailing List"), tr("Ctrl+L"));
246 shortcutHandler->defineAction(QStringLiteral("action_reply_guess"), QString(), tr("Reply by &Guess"), tr("Ctrl+R"));
247 shortcutHandler->defineAction(QStringLiteral("action_forward_attachment"), QStringLiteral("mail-forward"), tr("&Forward"), tr("Ctrl+Shift+F"));
248 shortcutHandler->defineAction(QStringLiteral("action_bounce"), QStringLiteral("mail-bounce"), tr("Edit as New E-Mail Message..."));
249 shortcutHandler->defineAction(QStringLiteral("action_archive"), QStringLiteral("mail-move-to-archive"), tr("&Archive"), QStringLiteral("A"));
250 shortcutHandler->defineAction(QStringLiteral("action_contact_editor"), QStringLiteral("contact-unknown"), tr("Address Book..."));
251 shortcutHandler->defineAction(QStringLiteral("action_network_offline"), QStringLiteral("network-disconnect"), tr("&Offline"));
252 shortcutHandler->defineAction(QStringLiteral("action_network_expensive"), QStringLiteral("network-wireless"), tr("&Expensive Connection"));
253 shortcutHandler->defineAction(QStringLiteral("action_network_online"), QStringLiteral("network-connect"), tr("&Free Access"));
254 shortcutHandler->defineAction(QStringLiteral("action_messagewindow_close"), QStringLiteral("window-close"), tr("Close Standalone Message Window"));
255 shortcutHandler->defineAction(QStringLiteral("action_open_messagewindow"), QString(), tr("Open message in New Window..."), QStringLiteral("Ctrl+Return"));
256 shortcutHandler->defineAction(QStringLiteral("action_oneattime_go_back"), QStringLiteral("go-previous"), tr("Navigate Back"), QKeySequence(QKeySequence::Back).toString());
257 shortcutHandler->defineAction(QStringLiteral("action_zoom_in"), QStringLiteral("zoom-in"), tr("Zoom In"), QKeySequence::ZoomIn);
258 shortcutHandler->defineAction(QStringLiteral("action_zoom_out"), QStringLiteral("zoom-out"), tr("Zoom Out"), QKeySequence::ZoomOut);
259 shortcutHandler->defineAction(QStringLiteral("action_zoom_original"), QStringLiteral("zoom-original"), tr("Original Size"));
260 shortcutHandler->defineAction(QStringLiteral("action_focus_mailbox_tree"), QString(), tr("Move Focus to Mailbox List"));
261 shortcutHandler->defineAction(QStringLiteral("action_focus_msg_list"), QString(), tr("Move Focus to Message List"));
262 shortcutHandler->defineAction(QStringLiteral("action_tag_1"), QStringLiteral("mail-tag-1"), tr("Tag with &1st tag"), QStringLiteral("1"));
263 shortcutHandler->defineAction(QStringLiteral("action_tag_2"), QStringLiteral("mail-tag-2"), tr("Tag with &2nd tag"), QStringLiteral("2"));
264 shortcutHandler->defineAction(QStringLiteral("action_tag_3"), QStringLiteral("mail-tag-3"), tr("Tag with &3rd tag"), QStringLiteral("3"));
265 shortcutHandler->defineAction(QStringLiteral("action_tag_4"), QStringLiteral("mail-tag-4"), tr("Tag with &4th tag"), QStringLiteral("4"));
266 shortcutHandler->defineAction(QStringLiteral("action_tag_5"), QStringLiteral("mail-tag-5"), tr("Tag with &5th tag"), QStringLiteral("5"));
269 void MainWindow::createActions()
271 // The shortcuts are a little bit complicated, unfortunately. This is what the other applications use by default:
273 // Thunderbird:
274 // private: Ctrl+R
275 // all: Ctrl+Shift+R
276 // list: Ctrl+Shift+L
277 // forward: Ctrl+L
278 // (no shortcuts for type of forwarding)
279 // bounce: ctrl+B
280 // new message: Ctrl+N
282 // KMail:
283 // "reply": R
284 // private: Shift+A
285 // all: A
286 // list: L
287 // forward as attachment: F
288 // forward inline: Shift+F
289 // bounce: E
290 // new: Ctrl+N
292 m_actionContactEditor = ShortcutHandler::instance()->createAction(QStringLiteral("action_contact_editor"), this, SLOT(invokeContactEditor()), this);
294 m_mainToolbar = addToolBar(tr("Navigation"));
295 m_mainToolbar->setObjectName(QStringLiteral("mainToolbar"));
297 reloadMboxList = new QAction(style()->standardIcon(QStyle::SP_ArrowRight), tr("&Update List of Child Mailboxes"), this);
298 connect(reloadMboxList, &QAction::triggered, this, &MainWindow::slotReloadMboxList);
300 resyncMbox = new QAction(UiUtils::loadIcon(QStringLiteral("view-refresh")), tr("Check for &New Messages"), this);
301 connect(resyncMbox, &QAction::triggered, this, &MainWindow::slotResyncMbox);
303 reloadAllMailboxes = new QAction(tr("&Reload Everything"), this);
304 // connect later
306 exitAction = ShortcutHandler::instance()->createAction(QStringLiteral("action_application_exit"), qApp, SLOT(quit()), this);
307 exitAction->setStatusTip(tr("Exit the application"));
309 netOffline = ShortcutHandler::instance()->createAction(QStringLiteral("action_network_offline"));
310 netOffline->setCheckable(true);
311 // connect later
312 netExpensive = ShortcutHandler::instance()->createAction(QStringLiteral("action_network_expensive"));
313 netExpensive->setCheckable(true);
314 // connect later
315 netOnline = ShortcutHandler::instance()->createAction(QStringLiteral("action_network_online"));
316 netOnline->setCheckable(true);
317 // connect later
319 QActionGroup *netPolicyGroup = new QActionGroup(this);
320 netPolicyGroup->setExclusive(true);
321 netPolicyGroup->addAction(netOffline);
322 netPolicyGroup->addAction(netExpensive);
323 netPolicyGroup->addAction(netOnline);
325 //: a debugging tool showing the full contents of the whole IMAP server; all folders, messages and their parts
326 showFullView = new QAction(UiUtils::loadIcon(QStringLiteral("edit-find-mail")), tr("Show Full &Tree Window"), this);
327 showFullView->setCheckable(true);
328 connect(showFullView, &QAction::triggered, allDock, &QWidget::setVisible);
329 connect(allDock, &QDockWidget::visibilityChanged, showFullView, &QAction::setChecked);
331 //: list of active "tasks", entities which are performing certain action like downloading a message or syncing a mailbox
332 showTaskView = new QAction(tr("Show ImapTask t&ree"), this);
333 showTaskView->setCheckable(true);
334 connect(showTaskView, &QAction::triggered, taskDock, &QWidget::setVisible);
335 connect(taskDock, &QDockWidget::visibilityChanged, showTaskView, &QAction::setChecked);
337 //: a debugging tool showing the mime tree of the current message
338 showMimeView = new QAction(tr("Show &MIME tree"), this);
339 showMimeView->setCheckable(true);
340 connect(showMimeView, &QAction::triggered, mailMimeDock, &QWidget::setVisible);
341 connect(mailMimeDock, &QDockWidget::visibilityChanged, showMimeView, &QAction::setChecked);
343 showImapLogger = new QAction(tr("Show IMAP protocol &log"), this);
344 showImapLogger->setCheckable(true);
345 connect(showImapLogger, &QAction::toggled, imapLoggerDock, &QWidget::setVisible);
346 connect(imapLoggerDock, &QDockWidget::visibilityChanged, showImapLogger, &QAction::setChecked);
348 //: file to save the debug log into
349 logPersistent = new QAction(tr("Log &into %1").arg(Imap::Mailbox::persistentLogFileName()), this);
350 logPersistent->setCheckable(true);
351 connect(logPersistent, &QAction::triggered, imapLogger, &ProtocolLoggerWidget::slotSetPersistentLogging);
352 connect(imapLogger, &ProtocolLoggerWidget::persistentLoggingChanged, logPersistent, &QAction::setChecked);
354 showImapCapabilities = new QAction(tr("IMAP Server In&formation..."), this);
355 connect(showImapCapabilities, &QAction::triggered, this, &MainWindow::slotShowImapInfo);
357 showMenuBar = ShortcutHandler::instance()->createAction(QStringLiteral("action_show_menubar"), this);
358 showMenuBar->setCheckable(true);
359 showMenuBar->setChecked(true);
360 connect(showMenuBar, &QAction::triggered, menuBar(), &QMenuBar::setVisible);
361 connect(showMenuBar, &QAction::triggered, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
363 showToolBar = new QAction(tr("Show &Toolbar"), this);
364 showToolBar->setCheckable(true);
365 connect(showToolBar, &QAction::triggered, m_mainToolbar, &QWidget::setVisible);
366 connect(m_mainToolbar, &QToolBar::visibilityChanged, showToolBar, &QAction::setChecked);
367 connect(m_mainToolbar, &QToolBar::visibilityChanged, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
369 configSettings = new QAction(UiUtils::loadIcon(QStringLiteral("configure")), tr("&Settings..."), this);
370 connect(configSettings, &QAction::triggered, this, &MainWindow::slotShowSettings);
372 QAction *triggerSearch = new QAction(this);
373 addAction(triggerSearch);
374 triggerSearch->setShortcut(QKeySequence(QStringLiteral(":, =")));
375 connect(triggerSearch, &QAction::triggered, msgListWidget, &MessageListWidget::focusRawSearch);
377 triggerSearch = new QAction(this);
378 addAction(triggerSearch);
379 triggerSearch->setShortcut(QKeySequence(QStringLiteral("/")));
380 connect(triggerSearch, &QAction::triggered, msgListWidget, &MessageListWidget::focusSearch);
382 addAction(ShortcutHandler::instance()->createAction(QStringLiteral("action_focus_mailbox_tree"), mboxTree,
383 SLOT(setFocus()), this));
384 addAction(ShortcutHandler::instance()->createAction(QStringLiteral("action_focus_msg_list"), msgListWidget->tree,
385 SLOT(setFocus()), this));
387 m_oneAtTimeGoBack = ShortcutHandler::instance()->createAction(QStringLiteral("action_oneattime_go_back"), this);
388 m_oneAtTimeGoBack->setEnabled(false);
390 composeMail = ShortcutHandler::instance()->createAction(QStringLiteral("action_compose_mail"), this, SLOT(slotComposeMail()), this);
391 m_editDraft = ShortcutHandler::instance()->createAction(QStringLiteral("action_compose_draft"), this, SLOT(slotEditDraft()), this);
393 expunge = ShortcutHandler::instance()->createAction(QStringLiteral("action_expunge"), this, SLOT(slotExpunge()), this);
395 m_forwardAsAttachment = ShortcutHandler::instance()->createAction(QStringLiteral("action_forward_attachment"), this, SLOT(slotForwardAsAttachment()), this);
396 m_bounce = ShortcutHandler::instance()->createAction(QStringLiteral("action_bounce"), this, SLOT(slotBounce()), this);
397 markAsRead = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_read"), this);
398 markAsRead->setCheckable(true);
399 msgListWidget->tree->addAction(markAsRead);
400 connect(markAsRead, &QAction::triggered, this, &MainWindow::handleMarkAsRead);
402 m_nextMessage = ShortcutHandler::instance()->createAction(QStringLiteral("action_go_to_next_unread"), this, SLOT(slotNextUnread()), this);
403 msgListWidget->tree->addAction(m_nextMessage);
404 m_messageWidget->messageView->addAction(m_nextMessage);
406 m_previousMessage = ShortcutHandler::instance()->createAction(QStringLiteral("action_go_to_previous_unread"), this, SLOT(slotPreviousUnread()), this);
407 msgListWidget->tree->addAction(m_previousMessage);
408 m_messageWidget->messageView->addAction(m_previousMessage);
410 markAsDeleted = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_deleted"), this);
411 markAsDeleted->setCheckable(true);
412 msgListWidget->tree->addAction(markAsDeleted);
413 connect(markAsDeleted, &QAction::triggered, this, &MainWindow::handleMarkAsDeleted);
415 markAsFlagged = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_flagged"), this);
416 markAsFlagged->setCheckable(true);
417 connect(markAsFlagged, &QAction::triggered, this, &MainWindow::handleMarkAsFlagged);
419 markAsJunk = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_junk"), this);
420 markAsJunk->setCheckable(true);
421 connect(markAsJunk, &QAction::triggered, this, &MainWindow::handleMarkAsJunk);
423 markAsNotJunk = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_notjunk"), this);
424 markAsNotJunk->setCheckable(true);
425 connect(markAsNotJunk, &QAction::triggered, this, &MainWindow::handleMarkAsNotJunk);
427 saveWholeMessage = ShortcutHandler::instance()->createAction(QStringLiteral("action_save_message_as"), this, SLOT(slotSaveCurrentMessageBody()), this);
428 msgListWidget->tree->addAction(saveWholeMessage);
430 viewMsgSource = ShortcutHandler::instance()->createAction(QStringLiteral("action_view_message_source"), this, SLOT(slotViewMsgSource()), this);
431 msgListWidget->tree->addAction(viewMsgSource);
433 viewMsgHeaders = ShortcutHandler::instance()->createAction(QStringLiteral("action_view_message_headers"), this, SLOT(slotViewMsgHeaders()), this);
434 msgListWidget->tree->addAction(viewMsgHeaders);
436 msgListWidget->tree->addAction(ShortcutHandler::instance()->createAction(QStringLiteral("action_open_messagewindow"), this,
437 SLOT(openCompleteMessageWidget()), this));
439 moveToArchive = ShortcutHandler::instance()->createAction(QStringLiteral("action_archive"), this);
440 connect(moveToArchive, &QAction::triggered, this, &MainWindow::handleMoveToArchive);
442 auto addTagAction = [=](int row) {
443 QAction *tag = ShortcutHandler::instance()->createAction(QStringLiteral("action_tag_").append(QString::number(row)), this);
444 tag->setCheckable(true);
445 msgListWidget->tree->addAction(tag);
446 connect(tag, &QAction::triggered, this, [=](const bool checked) {
447 handleTag(checked, row - 1);
449 return tag;
451 tag1 = addTagAction(1);
452 tag2 = addTagAction(2);
453 tag3 = addTagAction(3);
454 tag4 = addTagAction(4);
455 tag5 = addTagAction(5);
457 //: "mailbox" as a "folder of messages", not as a "mail account"
458 createChildMailbox = new QAction(tr("Create &Child Mailbox..."), this);
459 connect(createChildMailbox, &QAction::triggered, this, &MainWindow::slotCreateMailboxBelowCurrent);
461 //: "mailbox" as a "folder of messages", not as a "mail account"
462 createTopMailbox = new QAction(tr("Create &New Mailbox..."), this);
463 connect(createTopMailbox, &QAction::triggered, this, &MainWindow::slotCreateTopMailbox);
465 m_actionMarkMailboxAsRead = new QAction(tr("&Mark Mailbox as Read"), this);
466 connect(m_actionMarkMailboxAsRead, &QAction::triggered, this, &MainWindow::slotMarkCurrentMailboxRead);
468 //: "mailbox" as a "folder of messages", not as a "mail account"
469 deleteCurrentMailbox = new QAction(tr("&Remove Mailbox"), this);
470 connect(deleteCurrentMailbox, &QAction::triggered, this, &MainWindow::slotDeleteCurrentMailbox);
472 #ifdef XTUPLE_CONNECT
473 xtIncludeMailboxInSync = new QAction(tr("&Synchronize with xTuple"), this);
474 xtIncludeMailboxInSync->setCheckable(true);
475 connect(xtIncludeMailboxInSync, SIGNAL(triggered()), this, SLOT(slotXtSyncCurrentMailbox()));
476 #endif
478 m_replyPrivate = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_private"), this, SLOT(slotReplyTo()), this);
479 m_replyPrivate->setEnabled(false);
481 m_replyAllButMe = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_all_but_me"), this, SLOT(slotReplyAllButMe()), this);
482 m_replyAllButMe->setEnabled(false);
484 m_replyAll = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_all"), this, SLOT(slotReplyAll()), this);
485 m_replyAll->setEnabled(false);
487 m_replyList = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_list"), this, SLOT(slotReplyList()), this);
488 m_replyList->setEnabled(false);
490 m_replyGuess = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_guess"), this, SLOT(slotReplyGuess()), this);
491 m_replyGuess->setEnabled(true);
493 actionThreadMsgList = new QAction(UiUtils::loadIcon(QStringLiteral("format-justify-right")), tr("Show Messages in &Threads"), this);
494 actionThreadMsgList->setCheckable(true);
495 // This action is enabled/disabled by model's capabilities
496 actionThreadMsgList->setEnabled(false);
497 if (m_settings->value(Common::SettingsNames::guiMsgListShowThreading).toBool()) {
498 actionThreadMsgList->setChecked(true);
499 // The actual threading will be performed only when model updates its capabilities
501 connect(actionThreadMsgList, &QAction::triggered, this, &MainWindow::slotThreadMsgList);
503 QActionGroup *sortOrderGroup = new QActionGroup(this);
504 m_actionSortAscending = new QAction(tr("&Ascending"), sortOrderGroup);
505 m_actionSortAscending->setCheckable(true);
506 m_actionSortAscending->setChecked(true);
507 m_actionSortDescending = new QAction(tr("&Descending"), sortOrderGroup);
508 m_actionSortDescending->setCheckable(true);
509 // QActionGroup has no toggle signal, but connecting descending will implicitly catch the acscending complement ;-)
510 connect(m_actionSortDescending, &QAction::toggled, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
511 connect(m_actionSortDescending, &QAction::toggled, this, &MainWindow::slotScrollToCurrent);
512 connect(sortOrderGroup, &QActionGroup::triggered, this, &MainWindow::slotSortingPreferenceChanged);
514 QActionGroup *sortColumnGroup = new QActionGroup(this);
515 m_actionSortNone = new QAction(tr("&No sorting"), sortColumnGroup);
516 m_actionSortNone->setCheckable(true);
517 m_actionSortThreading = new QAction(tr("Sorted by &Threading"), sortColumnGroup);
518 m_actionSortThreading->setCheckable(true);
519 m_actionSortByArrival = new QAction(tr("A&rrival"), sortColumnGroup);
520 m_actionSortByArrival->setCheckable(true);
521 m_actionSortByCc = new QAction(tr("&Cc (Carbon Copy)"), sortColumnGroup);
522 m_actionSortByCc->setCheckable(true);
523 m_actionSortByDate = new QAction(tr("Date from &Message Headers"), sortColumnGroup);
524 m_actionSortByDate->setCheckable(true);
525 m_actionSortByFrom = new QAction(tr("&From Address"), sortColumnGroup);
526 m_actionSortByFrom->setCheckable(true);
527 m_actionSortBySize = new QAction(tr("&Size"), sortColumnGroup);
528 m_actionSortBySize->setCheckable(true);
529 m_actionSortBySubject = new QAction(tr("S&ubject"), sortColumnGroup);
530 m_actionSortBySubject->setCheckable(true);
531 m_actionSortByTo = new QAction(tr("T&o Address"), sortColumnGroup);
532 m_actionSortByTo->setCheckable(true);
533 connect(sortColumnGroup, &QActionGroup::triggered, this, &MainWindow::slotSortingPreferenceChanged);
534 slotSortingConfirmed(-1, Qt::AscendingOrder);
536 actionHideRead = new QAction(tr("&Hide Read Messages"), this);
537 actionHideRead->setCheckable(true);
538 if (m_settings->value(Common::SettingsNames::guiMsgListHideRead).toBool()) {
539 actionHideRead->setChecked(true);
540 prettyMsgListModel->setHideRead(true);
542 connect(actionHideRead, &QAction::triggered, this, &MainWindow::slotHideRead);
544 QActionGroup *layoutGroup = new QActionGroup(this);
545 m_actionLayoutCompact = new QAction(tr("&Compact"), layoutGroup);
546 m_actionLayoutCompact->setCheckable(true);
547 m_actionLayoutCompact->setChecked(true);
548 connect(m_actionLayoutCompact, &QAction::triggered, this, &MainWindow::slotLayoutCompact);
549 m_actionLayoutWide = new QAction(tr("&Wide"), layoutGroup);
550 m_actionLayoutWide->setCheckable(true);
551 connect(m_actionLayoutWide, &QAction::triggered, this, &MainWindow::slotLayoutWide);
552 m_actionLayoutOneAtTime = new QAction(tr("&One At Time"), layoutGroup);
553 m_actionLayoutOneAtTime->setCheckable(true);
554 connect(m_actionLayoutOneAtTime, &QAction::triggered, this, &MainWindow::slotLayoutOneAtTime);
557 m_actionShowOnlySubscribed = new QAction(tr("Show Only S&ubscribed Folders"), this);
558 m_actionShowOnlySubscribed->setCheckable(true);
559 m_actionShowOnlySubscribed->setEnabled(false);
560 connect(m_actionShowOnlySubscribed, &QAction::toggled, this, &MainWindow::slotShowOnlySubscribed);
561 m_actionSubscribeMailbox = new QAction(tr("Su&bscribed"), this);
562 m_actionSubscribeMailbox->setCheckable(true);
563 m_actionSubscribeMailbox->setEnabled(false);
564 connect(m_actionSubscribeMailbox, &QAction::triggered, this, &MainWindow::slotSubscribeCurrentMailbox);
566 aboutTrojita = new QAction(trUtf8("&About Trojitá..."), this);
567 connect(aboutTrojita, &QAction::triggered, this, &MainWindow::slotShowAboutTrojita);
569 donateToTrojita = new QAction(tr("&Donate to the project"), this);
570 connect(donateToTrojita, &QAction::triggered, this, &MainWindow::slotDonateToTrojita);
572 connectModelActions();
574 m_composeMenu = new QMenu(tr("Compose Mail"), this);
575 m_composeMenu->addAction(composeMail);
576 m_composeMenu->addAction(m_editDraft);
577 m_composeButton = new QToolButton(this);
578 m_composeButton->setPopupMode(QToolButton::MenuButtonPopup);
579 m_composeButton->setMenu(m_composeMenu);
580 m_composeButton->setDefaultAction(composeMail);
582 m_replyButton = new QToolButton(this);
583 m_replyButton->setPopupMode(QToolButton::MenuButtonPopup);
584 m_replyMenu = new QMenu(m_replyButton);
585 m_replyMenu->addAction(m_replyPrivate);
586 m_replyMenu->addAction(m_replyAllButMe);
587 m_replyMenu->addAction(m_replyAll);
588 m_replyMenu->addAction(m_replyList);
589 m_replyButton->setMenu(m_replyMenu);
590 m_replyButton->setDefaultAction(m_replyPrivate);
592 m_mainToolbar->addWidget(m_composeButton);
593 m_mainToolbar->addWidget(m_replyButton);
594 m_mainToolbar->addAction(m_forwardAsAttachment);
595 m_mainToolbar->addAction(expunge);
596 m_mainToolbar->addSeparator();
597 m_mainToolbar->addAction(markAsRead);
598 m_mainToolbar->addAction(markAsDeleted);
599 m_mainToolbar->addAction(markAsFlagged);
600 m_mainToolbar->addAction(markAsJunk);
601 m_mainToolbar->addAction(markAsNotJunk);
602 m_mainToolbar->addAction(moveToArchive);
604 // Push the status indicators all the way to the other side of the toolbar -- either to the far right, or far bottom.
605 QWidget *toolbarSpacer = new QWidget(m_mainToolbar);
606 toolbarSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
607 m_mainToolbar->addWidget(toolbarSpacer);
609 m_mainToolbar->addSeparator();
610 m_mainToolbar->addWidget(busyParsersIndicator);
612 networkIndicator = new QToolButton(this);
613 // This is deliberate; we want to show this button in the same style as the other ones in the toolbar
614 networkIndicator->setPopupMode(QToolButton::MenuButtonPopup);
615 m_mainToolbar->addWidget(networkIndicator);
617 m_menuFromToolBar = new QToolButton(this);
618 m_menuFromToolBar->setIcon(UiUtils::loadIcon(QStringLiteral("menu_new")));
619 m_menuFromToolBar->setText(QChar(0x205d)); // Unicode 'TRICOLON'
620 m_menuFromToolBar->setPopupMode(QToolButton::MenuButtonPopup);
621 connect(m_menuFromToolBar, &QAbstractButton::clicked, m_menuFromToolBar, &QToolButton::showMenu);
622 m_mainToolbar->addWidget(m_menuFromToolBar);
623 connect(showMenuBar, &QAction::toggled, [this](const bool menuBarVisible) {
624 // https://bugreports.qt.io/browse/QTBUG-35768 , we have to work on the QAction, not QToolButton
625 m_mainToolbar->actions().last()->setVisible(!menuBarVisible);
627 m_mainToolbar->actions().last()->setVisible(false); // initial state to complement the default of the QMenuBar's visibility
629 busyParsersIndicator->setFixedSize(m_mainToolbar->iconSize());
632 // Custom widgets which are added into a QToolBar are by default aligned to the left, while QActions are justified.
633 // That sucks, because some of our widgets use multiple actions with an expanding arrow at right.
634 // Make sure everything is aligned to the left, so that the actual buttons are aligned properly and the extra arrows
635 // are, well, at right.
636 // I have no idea how this works on RTL layouts.
637 QLayout *lay = m_mainToolbar->layout();
638 for (int i = 0; i < lay->count(); ++i) {
639 QLayoutItem *it = lay->itemAt(i);
640 if (it->widget() == toolbarSpacer) {
641 // Don't align this one, otherwise it won't push stuff when in horizontal direction
642 continue;
644 if (it->widget() == busyParsersIndicator) {
645 // It looks much better when centered
646 it->setAlignment(Qt::AlignJustify);
647 continue;
649 it->setAlignment(Qt::AlignLeft);
653 updateMessageFlags();
656 void MainWindow::connectModelActions()
658 connect(reloadAllMailboxes, &QAction::triggered, imapModel(), &Imap::Mailbox::Model::reloadMailboxList);
659 connect(netOffline, &QAction::triggered,
660 qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()), &Imap::Mailbox::NetworkWatcher::setNetworkOffline);
661 connect(netExpensive, &QAction::triggered,
662 qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()), &Imap::Mailbox::NetworkWatcher::setNetworkExpensive);
663 connect(netOnline, &QAction::triggered,
664 qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()), &Imap::Mailbox::NetworkWatcher::setNetworkOnline);
665 netExpensive->setEnabled(imapAccess()->isConfigured());
666 netOnline->setEnabled(imapAccess()->isConfigured());
669 void MainWindow::createMenus()
671 #define ADD_ACTION(MENU, ACTION) \
672 MENU->addAction(ACTION); \
673 addAction(ACTION);
675 QMenu *imapMenu = menuBar()->addMenu(tr("&IMAP"));
676 imapMenu->addMenu(m_composeMenu);
677 ADD_ACTION(imapMenu, m_actionContactEditor);
678 ADD_ACTION(imapMenu, m_replyGuess);
679 ADD_ACTION(imapMenu, m_replyPrivate);
680 ADD_ACTION(imapMenu, m_replyAll);
681 ADD_ACTION(imapMenu, m_replyAllButMe);
682 ADD_ACTION(imapMenu, m_replyList);
683 imapMenu->addSeparator();
684 ADD_ACTION(imapMenu, m_forwardAsAttachment);
685 ADD_ACTION(imapMenu, m_bounce);
686 imapMenu->addSeparator();
687 ADD_ACTION(imapMenu, expunge);
688 imapMenu->addSeparator()->setText(tr("Network Access"));
689 QMenu *netPolicyMenu = imapMenu->addMenu(tr("&Network Access"));
690 ADD_ACTION(netPolicyMenu, netOffline);
691 ADD_ACTION(netPolicyMenu, netExpensive);
692 ADD_ACTION(netPolicyMenu, netOnline);
693 QMenu *debugMenu = imapMenu->addMenu(tr("&Debugging"));
694 ADD_ACTION(debugMenu, showFullView);
695 ADD_ACTION(debugMenu, showTaskView);
696 ADD_ACTION(debugMenu, showMimeView);
697 ADD_ACTION(debugMenu, showImapLogger);
698 ADD_ACTION(debugMenu, logPersistent);
699 ADD_ACTION(debugMenu, showImapCapabilities);
700 imapMenu->addSeparator();
701 ADD_ACTION(imapMenu, configSettings);
702 ADD_ACTION(imapMenu, ShortcutHandler::instance()->shortcutConfigAction());
703 imapMenu->addSeparator();
704 ADD_ACTION(imapMenu, exitAction);
706 QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
707 ADD_ACTION(viewMenu, showMenuBar);
708 ADD_ACTION(viewMenu, showToolBar);
709 QMenu *layoutMenu = viewMenu->addMenu(tr("&Layout"));
710 ADD_ACTION(layoutMenu, m_actionLayoutCompact);
711 ADD_ACTION(layoutMenu, m_actionLayoutWide);
712 ADD_ACTION(layoutMenu, m_actionLayoutOneAtTime);
713 viewMenu->addSeparator();
714 ADD_ACTION(viewMenu, m_previousMessage);
715 ADD_ACTION(viewMenu, m_nextMessage);
716 viewMenu->addSeparator();
717 QMenu *sortMenu = viewMenu->addMenu(tr("S&orting"));
718 ADD_ACTION(sortMenu, m_actionSortNone);
719 ADD_ACTION(sortMenu, m_actionSortThreading);
720 ADD_ACTION(sortMenu, m_actionSortByArrival);
721 ADD_ACTION(sortMenu, m_actionSortByCc);
722 ADD_ACTION(sortMenu, m_actionSortByDate);
723 ADD_ACTION(sortMenu, m_actionSortByFrom);
724 ADD_ACTION(sortMenu, m_actionSortBySize);
725 ADD_ACTION(sortMenu, m_actionSortBySubject);
726 ADD_ACTION(sortMenu, m_actionSortByTo);
727 sortMenu->addSeparator();
728 ADD_ACTION(sortMenu, m_actionSortAscending);
729 ADD_ACTION(sortMenu, m_actionSortDescending);
731 ADD_ACTION(viewMenu, actionThreadMsgList);
732 ADD_ACTION(viewMenu, actionHideRead);
733 ADD_ACTION(viewMenu, m_actionShowOnlySubscribed);
735 QMenu *mailboxMenu = menuBar()->addMenu(tr("&Mailbox"));
736 ADD_ACTION(mailboxMenu, resyncMbox);
737 mailboxMenu->addSeparator();
738 ADD_ACTION(mailboxMenu, reloadAllMailboxes);
740 QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
741 ADD_ACTION(helpMenu, donateToTrojita);
742 helpMenu->addSeparator();
743 ADD_ACTION(helpMenu, aboutTrojita);
745 QMenu *mainMenuBehindToolBar = new QMenu(this);
746 m_menuFromToolBar->setMenu(mainMenuBehindToolBar);
747 m_menuFromToolBar->menu()->addMenu(imapMenu);
748 m_menuFromToolBar->menu()->addMenu(viewMenu);
749 m_menuFromToolBar->menu()->addMenu(mailboxMenu);
750 m_menuFromToolBar->menu()->addMenu(helpMenu);
751 m_menuFromToolBar->menu()->addSeparator();
752 m_menuFromToolBar->menu()->addAction(showMenuBar);
754 networkIndicator->setMenu(netPolicyMenu);
755 m_netToolbarDefaultAction = new QAction(this);
756 networkIndicator->setDefaultAction(m_netToolbarDefaultAction);
757 connect(m_netToolbarDefaultAction, &QAction::triggered, networkIndicator, &QToolButton::showMenu);
758 connect(netOffline, &QAction::toggled, this, &MainWindow::updateNetworkIndication);
759 connect(netExpensive, &QAction::toggled, this, &MainWindow::updateNetworkIndication);
760 connect(netOnline, &QAction::toggled, this, &MainWindow::updateNetworkIndication);
762 #undef ADD_ACTION
765 void MainWindow::createWidgets()
767 // The state of the GUI is only saved after a certain time has passed. This is just an optimization to make sure
768 // we do not hit the disk continually when e.g. resizing some random widget.
769 m_delayedStateSaving = new QTimer(this);
770 m_delayedStateSaving->setInterval(1000);
771 m_delayedStateSaving->setSingleShot(true);
772 connect(m_delayedStateSaving, &QTimer::timeout, this, &MainWindow::saveSizesAndState);
774 mboxTree = new MailBoxTreeView();
775 mboxTree->setDesiredExpansion(m_settings->value(Common::SettingsNames::guiExpandedMailboxes).toStringList());
776 connect(mboxTree, &QWidget::customContextMenuRequested, this, &MainWindow::showContextMenuMboxTree);
777 connect(mboxTree, &MailBoxTreeView::mailboxExpansionChanged, this, [this](const QStringList &mailboxNames) {
778 m_settings->setValue(Common::SettingsNames::guiExpandedMailboxes, mailboxNames);
781 msgListWidget = new MessageListWidget(nullptr, m_favoriteTags);
782 msgListWidget->tree->setContextMenuPolicy(Qt::CustomContextMenu);
783 msgListWidget->tree->setAlternatingRowColors(true);
784 msgListWidget->setRawSearchEnabled(m_settings->value(Common::SettingsNames::guiAllowRawSearch).toBool());
785 connect (msgListWidget, &MessageListWidget::rawSearchSettingChanged, this, &MainWindow::saveRawStateSetting);
787 connect(msgListWidget->tree, &QWidget::customContextMenuRequested, this, &MainWindow::showContextMenuMsgListTree);
788 connect(msgListWidget->tree, &QAbstractItemView::activated, this, &MainWindow::msgListClicked);
789 connect(msgListWidget->tree, &QAbstractItemView::clicked, this, &MainWindow::msgListClicked);
790 connect(msgListWidget->tree, &QAbstractItemView::doubleClicked, this, &MainWindow::openCompleteMessageWidget);
791 connect(msgListWidget, &MessageListWidget::requestingSearch, this, &MainWindow::slotSearchRequested);
792 connect(msgListWidget->tree->header(), &QHeaderView::sectionMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
793 connect(msgListWidget->tree->header(), &QHeaderView::sectionResized, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
795 msgListWidget->tree->installEventFilter(this);
797 m_messageWidget = new CompleteMessageWidget(this, m_settings, m_pluginManager, m_favoriteTags);
798 connect(m_messageWidget->messageView, &MessageView::messageChanged, this, &MainWindow::scrollMessageUp);
799 connect(m_messageWidget->messageView, &MessageView::messageChanged, this, &MainWindow::slotUpdateMessageActions);
800 #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
801 connect(m_messageWidget->messageView, &MessageView::linkHovered, [](const QString &url) {
802 if (url.isEmpty()) {
803 QToolTip::hideText();
804 } else {
805 // indirection due to https://bugs.kde.org/show_bug.cgi?id=363783
806 QTimer::singleShot(250, [url]() {
807 QToolTip::showText(QCursor::pos(), QObject::tr("Link target: %1").arg(UiUtils::Formatting::htmlEscaped(url)));
811 #endif
812 connect(m_messageWidget->messageView, &MessageView::transferError, this, &MainWindow::slotDownloadTransferError);
813 // Do not try to get onto the homepage when we are on EXPENSIVE connection
814 if (m_settings->value(Common::SettingsNames::appLoadHomepage, QVariant(true)).toBool() &&
815 m_imapAccess->preferredNetworkPolicy() == Imap::Mailbox::NETWORK_ONLINE) {
816 m_messageWidget->messageView->setHomepageUrl(QUrl(QStringLiteral("http://welcome.trojita.flaska.net/%1").arg(Common::Application::version)));
819 allDock = new QDockWidget(tr("Everything"), this);
820 allDock->setObjectName(QStringLiteral("allDock"));
821 allTree = new QTreeView(allDock);
822 allDock->hide();
823 allTree->setUniformRowHeights(true);
824 allTree->setHeaderHidden(true);
825 allDock->setWidget(allTree);
826 addDockWidget(Qt::LeftDockWidgetArea, allDock);
827 taskDock = new QDockWidget(tr("IMAP Tasks"), this);
828 taskDock->setObjectName(QStringLiteral("taskDock"));
829 taskTree = new QTreeView(taskDock);
830 taskDock->hide();
831 taskTree->setHeaderHidden(true);
832 taskDock->setWidget(taskTree);
833 addDockWidget(Qt::LeftDockWidgetArea, taskDock);
834 mailMimeDock = new QDockWidget(tr("MIME Tree"), this);
835 mailMimeDock->setObjectName(QStringLiteral("mailMimeDock"));
836 mailMimeTree = new QTreeView(mailMimeDock);
837 mailMimeDock->hide();
838 mailMimeTree->setUniformRowHeights(true);
839 mailMimeTree->setHeaderHidden(true);
840 mailMimeDock->setWidget(mailMimeTree);
841 addDockWidget(Qt::RightDockWidgetArea, mailMimeDock);
842 connect(m_messageWidget->messageView, &MessageView::messageModelChanged, this, &MainWindow::slotMessageModelChanged);
844 imapLoggerDock = new QDockWidget(tr("IMAP Protocol"), this);
845 imapLoggerDock->setObjectName(QStringLiteral("imapLoggerDock"));
846 imapLogger = new ProtocolLoggerWidget(imapLoggerDock);
847 imapLoggerDock->hide();
848 imapLoggerDock->setWidget(imapLogger);
849 addDockWidget(Qt::BottomDockWidgetArea, imapLoggerDock);
851 busyParsersIndicator = new TaskProgressIndicator(this);
854 void MainWindow::setupModels()
856 m_imapAccess->reloadConfiguration();
857 m_imapAccess->doConnect();
859 m_messageWidget->messageView->setNetworkWatcher(qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()));
861 auto realThreadingModel = qobject_cast<Imap::Mailbox::ThreadingMsgListModel*>(m_imapAccess->threadingMsgListModel());
862 Q_ASSERT(realThreadingModel);
863 auto realMsgListModel = qobject_cast<Imap::Mailbox::MsgListModel*>(m_imapAccess->msgListModel());
864 Q_ASSERT(realMsgListModel);
866 prettyMboxModel = new Imap::Mailbox::PrettyMailboxModel(this, qobject_cast<QAbstractItemModel *>(m_imapAccess->mailboxModel()));
867 prettyMboxModel->setObjectName(QStringLiteral("prettyMboxModel"));
868 connect(realThreadingModel, &Imap::Mailbox::ThreadingMsgListModel::sortingFailed,
869 msgListWidget, &MessageListWidget::slotSortingFailed);
870 prettyMsgListModel = new Imap::Mailbox::PrettyMsgListModel(this);
871 prettyMsgListModel->setSourceModel(m_imapAccess->threadingMsgListModel());
872 prettyMsgListModel->setObjectName(QStringLiteral("prettyMsgListModel"));
874 connect(mboxTree, &MailBoxTreeView::clicked,
875 realMsgListModel,
876 static_cast<void (Imap::Mailbox::MsgListModel::*)(const QModelIndex &)>(&Imap::Mailbox::MsgListModel::setMailbox));
877 connect(mboxTree, &MailBoxTreeView::activated,
878 realMsgListModel,
879 static_cast<void (Imap::Mailbox::MsgListModel::*)(const QModelIndex &)>(&Imap::Mailbox::MsgListModel::setMailbox));
880 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::dataChanged, this, &MainWindow::updateMessageFlags);
881 connect(qobject_cast<Imap::Mailbox::MsgListModel*>(m_imapAccess->msgListModel()), &Imap::Mailbox::MsgListModel::messagesAvailable,
882 this, &MainWindow::slotScrollToUnseenMessage);
883 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::rowsInserted, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
884 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::rowsRemoved, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
885 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::rowsRemoved, this, &MainWindow::updateMessageFlags);
886 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::layoutChanged, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
887 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::layoutChanged, this, &MainWindow::updateMessageFlags);
888 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::modelReset, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
889 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::modelReset, this, &MainWindow::updateMessageFlags);
890 connect(realMsgListModel, &Imap::Mailbox::MsgListModel::mailboxChanged, this, &MainWindow::slotMailboxChanged);
892 connect(imapModel(), &Imap::Mailbox::Model::alertReceived, this, &MainWindow::alertReceived);
893 connect(imapModel(), &Imap::Mailbox::Model::imapError, this, &MainWindow::imapError);
894 connect(imapModel(), &Imap::Mailbox::Model::networkError, this, &MainWindow::networkError);
895 connect(imapModel(), &Imap::Mailbox::Model::authRequested, this, &MainWindow::authenticationRequested, Qt::QueuedConnection);
896 connect(imapModel(), &Imap::Mailbox::Model::authAttemptFailed, this, [this]() {
897 m_ignoreStoredPassword = true;
900 connect(imapModel(), &Imap::Mailbox::Model::networkPolicyOffline, this, &MainWindow::networkPolicyOffline);
901 connect(imapModel(), &Imap::Mailbox::Model::networkPolicyExpensive, this, &MainWindow::networkPolicyExpensive);
902 connect(imapModel(), &Imap::Mailbox::Model::networkPolicyOnline, this, &MainWindow::networkPolicyOnline);
903 connect(imapModel(), &Imap::Mailbox::Model::connectionStateChanged, this, [this](uint, const Imap::ConnectionState state) {
904 if (state == Imap::CONN_STATE_AUTHENTICATED) {
905 m_ignoreStoredPassword = false;
908 connect(imapModel(), &Imap::Mailbox::Model::connectionStateChanged, this, &MainWindow::showConnectionStatus);
910 connect(imapModel(), &Imap::Mailbox::Model::mailboxDeletionFailed, this, &MainWindow::slotMailboxDeleteFailed);
911 connect(imapModel(), &Imap::Mailbox::Model::mailboxCreationFailed, this, &MainWindow::slotMailboxCreateFailed);
912 connect(imapModel(), &Imap::Mailbox::Model::mailboxSyncFailed, this, &MainWindow::slotMailboxSyncFailed);
914 connect(imapModel(), &Imap::Mailbox::Model::logged, imapLogger, &ProtocolLoggerWidget::slotImapLogged);
915 connect(imapModel(), &Imap::Mailbox::Model::connectionStateChanged, imapLogger, &ProtocolLoggerWidget::onConnectionClosed);
917 auto nw = qobject_cast<Imap::Mailbox::NetworkWatcher *>(m_imapAccess->networkWatcher());
918 Q_ASSERT(nw);
919 connect(nw, &Imap::Mailbox::NetworkWatcher::reconnectAttemptScheduled,
920 this, [this](const int timeout) {
921 showStatusMessage(tr("Attempting to reconnect in %n seconds..", 0, timeout/1000));
923 connect(nw, &Imap::Mailbox::NetworkWatcher::resetReconnectState, this, &MainWindow::slotResetReconnectState);
925 connect(imapModel(), &Imap::Mailbox::Model::mailboxFirstUnseenMessage, this, &MainWindow::slotScrollToUnseenMessage);
927 connect(imapModel(), &Imap::Mailbox::Model::capabilitiesUpdated, this, &MainWindow::slotCapabilitiesUpdated);
929 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::modelReset, this, &MainWindow::slotUpdateWindowTitle);
930 connect(imapModel(), &Imap::Mailbox::Model::messageCountPossiblyChanged, this, &MainWindow::slotUpdateWindowTitle);
932 connect(prettyMsgListModel, &Imap::Mailbox::PrettyMsgListModel::sortingPreferenceChanged, this, &MainWindow::slotSortingConfirmed);
934 //Imap::Mailbox::ModelWatcher* w = new Imap::Mailbox::ModelWatcher( this );
935 //w->setModel( imapModel() );
937 //ModelTest* tester = new ModelTest( prettyMboxModel, this ); // when testing, test just one model at time
939 mboxTree->setModel(prettyMboxModel);
940 msgListWidget->tree->setModel(prettyMsgListModel);
941 connect(msgListWidget->tree->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::updateMessageFlags);
943 allTree->setModel(imapModel());
944 taskTree->setModel(imapModel()->taskModel());
945 connect(imapModel()->taskModel(), &QAbstractItemModel::layoutChanged, taskTree, &QTreeView::expandAll);
946 connect(imapModel()->taskModel(), &QAbstractItemModel::modelReset, taskTree, &QTreeView::expandAll);
947 connect(imapModel()->taskModel(), &QAbstractItemModel::rowsInserted, taskTree, &QTreeView::expandAll);
948 connect(imapModel()->taskModel(), &QAbstractItemModel::rowsRemoved, taskTree, &QTreeView::expandAll);
949 connect(imapModel()->taskModel(), &QAbstractItemModel::rowsMoved, taskTree, &QTreeView::expandAll);
951 busyParsersIndicator->setImapModel(imapModel());
953 auto accountIconName = m_settings->value(Common::SettingsNames::imapAccountIcon).toString();
954 if (accountIconName.isEmpty()) {
955 qApp->setWindowIcon(UiUtils::loadIcon(QStringLiteral("trojita")));
956 } else if (accountIconName.contains(QDir::separator())) {
957 // Absolute paths are OK for users, but unsupported by our icon loader
958 qApp->setWindowIcon(QIcon(accountIconName));
959 } else {
960 qApp->setWindowIcon(UiUtils::loadIcon(accountIconName));
964 void MainWindow::createSysTray()
966 if (m_trayIcon)
967 return;
969 qApp->setQuitOnLastWindowClosed(false);
971 m_trayIcon = new QSystemTrayIcon(this);
972 handleTrayIconChange();
974 QAction* quitAction = new QAction(tr("&Quit"), m_trayIcon);
975 connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
977 QMenu *trayIconMenu = new QMenu(this);
978 trayIconMenu->addAction(quitAction);
979 m_trayIcon->setContextMenu(trayIconMenu);
981 // QMenu cannot be a child of QSystemTrayIcon, and we don't want the QMenu in MainWindow scope.
982 connect(m_trayIcon, &QObject::destroyed, trayIconMenu, &QObject::deleteLater);
984 connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::slotIconActivated);
985 connect(imapModel(), &Imap::Mailbox::Model::messageCountPossiblyChanged, this, &MainWindow::handleTrayIconChange);
986 m_trayIcon->setVisible(true);
987 m_trayIcon->show();
990 void MainWindow::removeSysTray()
992 delete m_trayIcon;
993 m_trayIcon = 0;
995 qApp->setQuitOnLastWindowClosed(true);
998 void MainWindow::slotToggleSysTray()
1000 bool showSystray = m_settings->value(Common::SettingsNames::guiShowSystray, QVariant(true)).toBool();
1001 if (showSystray && !m_trayIcon && QSystemTrayIcon::isSystemTrayAvailable()) {
1002 createSysTray();
1003 } else if (!showSystray && m_trayIcon) {
1004 removeSysTray();
1008 void MainWindow::handleTrayIconChange()
1010 if (!m_trayIcon)
1011 return;
1013 const bool isOffline = qobject_cast<Imap::Mailbox::NetworkWatcher *>(m_imapAccess->networkWatcher())->effectiveNetworkPolicy()
1014 == Imap::Mailbox::NETWORK_OFFLINE;
1015 auto pixmap = qApp->windowIcon()
1016 .pixmap(QSize(32, 32), isOffline ? QIcon::Disabled : QIcon::Normal);
1017 QString tooltip;
1018 auto profileName = QString::fromUtf8(qgetenv("TROJITA_PROFILE"));
1019 if (profileName.isEmpty()) {
1020 tooltip = QStringLiteral("Trojitá");
1021 } else {
1022 tooltip = QStringLiteral("Trojitá [%1]").arg(profileName);
1025 uint unreadCount = 0;
1026 bool numbersValid = false;
1028 auto watchingMode = settings()->value(Common::SettingsNames::watchedFoldersKey).toString();
1029 if (watchingMode == Common::SettingsNames::watchAll || watchingMode == Common::SettingsNames::watchSubscribed) {
1030 bool subscribedOnly = watchingMode == Common::SettingsNames::watchSubscribed;
1031 unreadCount = std::accumulate(UiUtils::QaimDfsIterator(m_imapAccess->mailboxModel()->index(0, 0)),
1032 UiUtils::QaimDfsIterator(), 0, [subscribedOnly](const uint acc, const QModelIndex &idx) {
1034 if (subscribedOnly && !idx.data(Imap::Mailbox::RoleMailboxIsSubscribed).toBool())
1035 return acc;
1037 auto x = idx.data(Imap::Mailbox::RoleUnreadMessageCount).toInt();
1038 if (x > 0) {
1039 return acc + x;
1040 } else {
1041 return acc;
1044 // only show stuff if there are some mailboxes, and if there are such messages
1045 numbersValid = m_imapAccess->mailboxModel()->hasChildren() && unreadCount > 0;
1047 } else {
1048 // just for the INBOX
1049 QModelIndex mailbox = imapModel()->index(1, 0, QModelIndex());
1050 if (mailbox.isValid() && mailbox.data(Imap::Mailbox::RoleMailboxName).toString() == QLatin1String("INBOX")
1051 && mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt() > 0) {
1052 unreadCount = mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt();
1053 numbersValid = true;
1057 if (numbersValid) {
1058 QFont f;
1059 f.setPixelSize(pixmap.height() * 0.59);
1060 f.setWeight(QFont::Bold);
1062 QString text = QString::number(unreadCount);
1063 QFontMetrics fm(f);
1064 if (unreadCount > 666) {
1065 // You just have too many messages.
1066 text = QStringLiteral("🐮");
1067 fm = QFontMetrics(f);
1068 } else if (fm.width(text) > pixmap.width()) {
1069 f.setPixelSize(f.pixelSize() * pixmap.width() / fm.width(text));
1070 fm = QFontMetrics(f);
1073 QRect boundingRect = fm.tightBoundingRect(text);
1074 boundingRect.setWidth(boundingRect.width() + 2);
1075 boundingRect.setHeight(boundingRect.height() + 2);
1076 boundingRect.moveCenter(QPoint(pixmap.width() / 2, pixmap.height() / 2));
1077 boundingRect = boundingRect.intersected(pixmap.rect());
1079 QPainterPath path;
1080 path.addText(boundingRect.bottomLeft(), f, text);
1082 QPainter painter(&pixmap);
1083 painter.setRenderHint(QPainter::Antialiasing);
1084 painter.setPen(QColor(255,255,255, 180));
1085 painter.setBrush(isOffline ? Qt::red : Qt::black);
1086 painter.drawPath(path);
1088 //: This is a tooltip for the tray icon. It will be prefixed by something like "Trojita" or "Trojita [work]"
1089 tooltip += trUtf8(" - %n unread message(s)", 0, unreadCount);
1090 } else if (isOffline) {
1091 //: A tooltip suffix when offline. The prefix is something like "Trojita" or "Trojita [work]"
1092 tooltip += tr(" - offline");
1094 m_trayIcon->setToolTip(tooltip);
1095 m_trayIcon->setIcon(QIcon(pixmap));
1098 void MainWindow::closeEvent(QCloseEvent *event)
1100 if (m_trayIcon && m_trayIcon->isVisible()) {
1101 Util::askForSomethingUnlessTold(trUtf8("Trojitá"),
1102 tr("The application will continue in systray. This can be disabled within the settings."),
1103 Common::SettingsNames::guiOnSystrayClose, QMessageBox::Ok, this, m_settings);
1104 hide();
1105 event->ignore();
1109 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1111 if (msgListWidget && o == msgListWidget->tree && m_messageWidget->messageView) {
1112 if (e->type() == QEvent::KeyPress) {
1113 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
1114 if (keyEvent->key() == Qt::Key_Space || keyEvent->key() == Qt::Key_Backspace) {
1115 QCoreApplication::sendEvent(m_messageWidget, keyEvent);
1116 return true;
1118 return false;
1120 return false;
1122 if (msgListWidget && msgListWidget->tree && o == msgListWidget->tree->header()->viewport()) {
1123 // installed if sorting is not really possible.
1124 QWidget *header = static_cast<QWidget*>(o);
1125 QMouseEvent *mouse = static_cast<QMouseEvent*>(e);
1126 if (e->type() == QEvent::MouseButtonPress) {
1127 if (mouse->button() == Qt::LeftButton && header->cursor().shape() == Qt::ArrowCursor) {
1128 m_headerDragStart = mouse->pos();
1130 return false;
1132 if (e->type() == QEvent::MouseButtonRelease) {
1133 if (mouse->button() == Qt::LeftButton && header->cursor().shape() == Qt::ArrowCursor &&
1134 (m_headerDragStart - mouse->pos()).manhattanLength() < QApplication::startDragDistance()) {
1135 m_actionSortDescending->toggle();
1136 Qt::SortOrder order = m_actionSortDescending->isChecked() ? Qt::DescendingOrder : Qt::AscendingOrder;
1137 msgListWidget->tree->header()->setSortIndicator(-1, order);
1138 return true; // prevent regular click
1142 return false;
1145 void MainWindow::slotIconActivated(const QSystemTrayIcon::ActivationReason reason)
1147 if (reason == QSystemTrayIcon::Trigger) {
1148 setVisible(!isVisible());
1149 if (isVisible())
1150 showMainWindow();
1154 void MainWindow::showMainWindow()
1156 setVisible(true);
1157 activateWindow();
1158 raise();
1161 void MainWindow::msgListClicked(const QModelIndex &index)
1163 Q_ASSERT(index.isValid());
1165 if (qApp->keyboardModifiers() & Qt::ShiftModifier || qApp->keyboardModifiers() & Qt::ControlModifier)
1166 return;
1168 if (! index.data(Imap::Mailbox::RoleMessageUid).isValid())
1169 return;
1171 // Because it's quite possible that we have switched into another mailbox, make sure that we're in the "current" one so that
1172 // user will be notified about new arrivals, etc.
1173 QModelIndex translated = Imap::deproxifiedIndex(index);
1174 imapModel()->switchToMailbox(translated.parent().parent());
1176 if (index.column() == Imap::Mailbox::MsgListModel::SEEN) {
1177 if (!translated.data(Imap::Mailbox::RoleIsFetched).toBool())
1178 return;
1179 Imap::Mailbox::FlagsOperation flagOp = translated.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool() ?
1180 Imap::Mailbox::FLAG_REMOVE : Imap::Mailbox::FLAG_ADD;
1181 imapModel()->markMessagesRead(QModelIndexList() << translated, flagOp);
1183 if (translated == m_messageWidget->messageView->currentMessage()) {
1184 m_messageWidget->messageView->stopAutoMarkAsRead();
1186 } else if (index.column() == Imap::Mailbox::MsgListModel::FLAGGED) {
1187 if (!translated.data(Imap::Mailbox::RoleIsFetched).toBool())
1188 return;
1190 Imap::Mailbox::FlagsOperation flagOp = translated.data(Imap::Mailbox::RoleMessageIsMarkedFlagged).toBool() ?
1191 Imap::Mailbox::FLAG_REMOVE : Imap::Mailbox::FLAG_ADD;
1192 imapModel()->setMessageFlags(QModelIndexList() << translated, Imap::Mailbox::FlagNames::flagged, flagOp);
1193 } else {
1194 if ((m_messageWidget->isVisible() && !m_messageWidget->size().isEmpty()) || m_layoutMode == LAYOUT_ONE_AT_TIME) {
1195 // isVisible() won't work, the splitter manipulates width, not the visibility state
1196 m_messageWidget->messageView->setMessage(index);
1198 msgListWidget->tree->setCurrentIndex(index);
1202 void MainWindow::openCompleteMessageWidget()
1204 const QModelIndex index = msgListWidget->tree->currentIndex();
1206 if (! index.data(Imap::Mailbox::RoleMessageUid).isValid())
1207 return;
1209 CompleteMessageWidget *widget = new CompleteMessageWidget(0, m_settings, m_pluginManager, m_favoriteTags);
1210 widget->messageView->setMessage(index);
1211 widget->messageView->setNetworkWatcher(qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()));
1212 widget->setFocusPolicy(Qt::StrongFocus);
1213 widget->setWindowTitle(index.data(Imap::Mailbox::RoleMessageSubject).toString());
1214 widget->setAttribute(Qt::WA_DeleteOnClose);
1215 QAction *closeAction = ShortcutHandler::instance()->createAction(QStringLiteral("action_messagewindow_close"), widget, SLOT(close()), widget);
1216 widget->addAction(closeAction);
1217 widget->show();
1220 void MainWindow::showContextMenuMboxTree(const QPoint &position)
1222 QList<QAction *> actionList;
1223 if (mboxTree->indexAt(position).isValid()) {
1224 actionList.append(createChildMailbox);
1225 actionList.append(deleteCurrentMailbox);
1226 actionList.append(m_actionMarkMailboxAsRead);
1227 actionList.append(resyncMbox);
1228 actionList.append(reloadMboxList);
1230 actionList.append(m_actionSubscribeMailbox);
1231 m_actionSubscribeMailbox->setChecked(mboxTree->indexAt(position).data(Imap::Mailbox::RoleMailboxIsSubscribed).toBool());
1233 #ifdef XTUPLE_CONNECT
1234 actionList.append(xtIncludeMailboxInSync);
1235 xtIncludeMailboxInSync->setChecked(
1236 m_settings->value(Common::SettingsNames::xtSyncMailboxList).toStringList().contains(
1237 mboxTree->indexAt(position).data(Imap::Mailbox::RoleMailboxName).toString()));
1238 #endif
1239 } else {
1240 actionList.append(createTopMailbox);
1242 actionList.append(reloadAllMailboxes);
1243 actionList.append(m_actionShowOnlySubscribed);
1244 QMenu::exec(actionList, mboxTree->mapToGlobal(position));
1247 void MainWindow::showContextMenuMsgListTree(const QPoint &position)
1249 QList<QAction *> actionList;
1250 QModelIndex index = msgListWidget->tree->indexAt(position);
1251 if (index.isValid()) {
1252 updateMessageFlagsOf(index);
1253 actionList.append(markAsRead);
1254 actionList.append(markAsDeleted);
1255 actionList.append(markAsFlagged);
1256 actionList.append(markAsJunk);
1257 actionList.append(markAsNotJunk);
1258 actionList.append(moveToArchive);
1259 actionList.append(m_actionMarkMailboxAsRead);
1260 actionList.append(saveWholeMessage);
1261 actionList.append(viewMsgSource);
1262 actionList.append(viewMsgHeaders);
1263 auto appendTagIfExists = [this,&actionList](const int row, QAction *tag) {
1264 if (m_favoriteTags->rowCount() > row - 1)
1265 actionList.append(tag);
1267 appendTagIfExists(1, tag1);
1268 appendTagIfExists(2, tag2);
1269 appendTagIfExists(3, tag3);
1270 appendTagIfExists(4, tag4);
1271 appendTagIfExists(5, tag5);
1273 if (! actionList.isEmpty())
1274 QMenu::exec(actionList, msgListWidget->tree->mapToGlobal(position));
1277 /** @short Ask for an updated list of mailboxes situated below the selected one
1280 void MainWindow::slotReloadMboxList()
1282 Q_FOREACH(const QModelIndex &item, mboxTree->selectionModel()->selectedIndexes()) {
1283 Q_ASSERT(item.isValid());
1284 if (item.column() != 0)
1285 continue;
1286 Imap::Mailbox::TreeItemMailbox *mbox = dynamic_cast<Imap::Mailbox::TreeItemMailbox *>(
1287 Imap::Mailbox::Model::realTreeItem(item)
1289 Q_ASSERT(mbox);
1290 mbox->rescanForChildMailboxes(imapModel());
1294 /** @short Request a check for new messages in selected mailbox */
1295 void MainWindow::slotResyncMbox()
1297 if (! imapModel()->isNetworkAvailable())
1298 return;
1300 Q_FOREACH(const QModelIndex &item, mboxTree->selectionModel()->selectedIndexes()) {
1301 Q_ASSERT(item.isValid());
1302 if (item.column() != 0)
1303 continue;
1304 imapModel()->resyncMailbox(item);
1308 void MainWindow::alertReceived(const QString &message)
1310 //: "ALERT" is a special warning which we're required to show to the user
1311 Gui::Util::messageBoxWarning(this, tr("IMAP Alert"), message);
1314 void MainWindow::imapError(const QString &message)
1316 Gui::Util::messageBoxCritical(this, tr("IMAP Protocol Error"), message);
1317 // Show the IMAP logger -- maybe some user will take that as a hint that they shall include it in the bug report.
1318 // </joke>
1319 showImapLogger->setChecked(true);
1322 void MainWindow::networkError(const QString &message)
1324 const QString title = tr("Network Error");
1325 if (!m_networkErrorMessageBox) {
1326 m_networkErrorMessageBox = new QMessageBox(QMessageBox::Critical, title,
1327 QString(), QMessageBox::Ok, this);
1329 // User must be informed about a new (but not recurring) error
1330 if (message != m_networkErrorMessageBox->text()) {
1331 m_networkErrorMessageBox->setText(message);
1332 if (qApp->applicationState() == Qt::ApplicationActive) {
1333 m_networkErrorMessageBox->setProperty(netErrorUnseen, false);
1334 m_networkErrorMessageBox->show();
1335 } else {
1336 m_networkErrorMessageBox->setProperty(netErrorUnseen, true);
1337 if (m_trayIcon && m_trayIcon->isVisible())
1338 m_trayIcon->showMessage(title, message, QSystemTrayIcon::Warning, 3333);
1343 void MainWindow::cacheError(const QString &message)
1345 Gui::Util::messageBoxCritical(this, tr("IMAP Cache Error"),
1346 tr("The caching subsystem managing a cache of the data already "
1347 "downloaded from the IMAP server is having troubles. "
1348 "All caching will be disabled.\n\n%1").arg(message));
1351 void MainWindow::networkPolicyOffline()
1353 netExpensive->setChecked(false);
1354 netOnline->setChecked(false);
1355 netOffline->setChecked(true);
1356 updateActionsOnlineOffline(false);
1357 showStatusMessage(tr("Offline"));
1358 handleTrayIconChange();
1361 void MainWindow::networkPolicyExpensive()
1363 netOffline->setChecked(false);
1364 netOnline->setChecked(false);
1365 netExpensive->setChecked(true);
1366 updateActionsOnlineOffline(true);
1367 handleTrayIconChange();
1370 void MainWindow::networkPolicyOnline()
1372 netOffline->setChecked(false);
1373 netExpensive->setChecked(false);
1374 netOnline->setChecked(true);
1375 updateActionsOnlineOffline(true);
1376 handleTrayIconChange();
1379 /** @short Deletes a network error message box instance upon resetting of reconnect state */
1380 void MainWindow::slotResetReconnectState()
1382 if (m_networkErrorMessageBox) {
1383 delete m_networkErrorMessageBox;
1384 m_networkErrorMessageBox = 0;
1388 void MainWindow::slotShowSettings()
1390 SettingsDialog *dialog = new SettingsDialog(this, m_senderIdentities, m_favoriteTags, m_settings);
1391 if (dialog->exec() == QDialog::Accepted) {
1392 // FIXME: wipe cache in case we're moving between servers
1393 nukeModels();
1394 setupModels();
1395 connectModelActions();
1396 // The systray is still connected to the old model -- got to make sure it's getting updated
1397 removeSysTray();
1398 slotToggleSysTray();
1400 QString method = m_settings->value(Common::SettingsNames::imapMethodKey).toString();
1401 if (method != Common::SettingsNames::methodTCP && method != Common::SettingsNames::methodSSL &&
1402 method != Common::SettingsNames::methodProcess ) {
1403 Gui::Util::messageBoxCritical(this, tr("No Configuration"),
1404 trUtf8("No IMAP account is configured. Trojitá cannot do much without one."));
1406 applySizesAndState();
1409 void MainWindow::authenticationRequested()
1411 Plugins::PasswordPlugin *password = pluginManager()->password();
1412 if (password) {
1413 // FIXME: use another account-id at some point in future
1414 // Currently the accountName will be empty unless Trojita has been
1415 // called with a profile, and then the profile will be used as the
1416 // accountName.
1417 QString accountName = m_imapAccess->accountName();
1418 if (accountName.isEmpty())
1419 accountName = QStringLiteral("account-0");
1420 Plugins::PasswordJob *job = password->requestPassword(accountName, QStringLiteral("imap"));
1421 if (job) {
1422 connect(job, &Plugins::PasswordJob::passwordAvailable, this, [this](const QString &password) {
1423 authenticationContinue(password);
1425 connect(job, &Plugins::PasswordJob::error, this, [this](const Plugins::PasswordJob::Error error, const QString &message) {
1426 if (error == Plugins::PasswordJob::Error::NoSuchPassword) {
1427 authenticationContinue(QString());
1428 } else {
1429 authenticationContinue(QString(), tr("Failed to retrieve password from the store: %1").arg(message));
1432 job->setAutoDelete(true);
1433 job->start();
1434 return;
1438 authenticationContinue(QString());
1442 void MainWindow::authenticationContinue(const QString &password, const QString &errorMessage)
1444 const QString &user = m_settings->value(Common::SettingsNames::imapUserKey).toString();
1445 QString pass = password;
1446 if (m_ignoreStoredPassword || pass.isEmpty()) {
1447 auto dialog = PasswordDialog::getPassword(this, tr("Authentication Required"),
1448 tr("<p>Please provide IMAP password for user <b>%1</b> on <b>%2</b>:</p>").arg(
1449 user.toHtmlEscaped(),
1450 m_settings->value(Common::SettingsNames::imapHostKey).toString().toHtmlEscaped()
1452 errorMessage + (errorMessage.isEmpty() ? QString() : QStringLiteral("\n\n"))
1453 + imapModel()->imapAuthError());
1454 connect(dialog, &PasswordDialog::gotPassword, imapModel(), &Imap::Mailbox::Model::setImapPassword);
1455 connect(dialog, &PasswordDialog::rejected, imapModel(), &Imap::Mailbox::Model::unsetImapPassword);
1456 } else {
1457 imapModel()->setImapPassword(pass);
1461 void MainWindow::checkSslPolicy()
1463 m_imapAccess->setSslPolicy(QMessageBox(static_cast<QMessageBox::Icon>(m_imapAccess->sslInfoIcon()),
1464 m_imapAccess->sslInfoTitle(), m_imapAccess->sslInfoMessage(),
1465 QMessageBox::Yes | QMessageBox::No, this).exec() == QMessageBox::Yes);
1468 void MainWindow::nukeModels()
1470 m_messageWidget->messageView->setEmpty();
1471 mboxTree->setModel(0);
1472 msgListWidget->tree->setModel(0);
1473 allTree->setModel(0);
1474 taskTree->setModel(0);
1475 delete prettyMsgListModel;
1476 prettyMsgListModel = 0;
1477 delete prettyMboxModel;
1478 prettyMboxModel = 0;
1481 void MainWindow::recoverDrafts()
1483 QDir draftPath(Common::writablePath(Common::LOCATION_CACHE) + QLatin1String("Drafts/"));
1484 QStringList drafts(draftPath.entryList(QStringList() << QStringLiteral("*.draft")));
1485 Q_FOREACH(const QString &draft, drafts) {
1486 ComposeWidget *w = ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createDraft(this, draftPath.filePath(draft)), this);
1487 // No need to further try creating widgets for drafts if a nullptr is being returned by ComposeWidget::warnIfMsaNotConfigured
1488 if (!w)
1489 break;
1493 void MainWindow::slotComposeMail()
1495 ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createBlank(this), this);
1498 void MainWindow::slotEditDraft()
1500 QString path(Common::writablePath(Common::LOCATION_DATA) + tr("Drafts"));
1501 QDir().mkpath(path);
1502 path = QFileDialog::getOpenFileName(this, tr("Edit draft"), path, tr("Drafts") + QLatin1String(" (*.draft)"));
1503 if (!path.isNull()) {
1504 ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createDraft(this, path), this);
1508 QModelIndexList MainWindow::translatedSelection() const
1510 QModelIndexList translatedIndexes;
1511 QModelIndexList selected = msgListWidget->tree->selectionModel()->selectedIndexes();
1512 const int originalItems = selected.length(); // only check collapsed/expanded status on original selection
1513 for (int i = 0; i < selected.length(); ++i) {
1514 const QModelIndex item = selected[i];
1515 if (item.column() != 0 || !item.data(Imap::Mailbox::RoleMessageUid).isValid())
1516 continue;
1517 translatedIndexes << Imap::deproxifiedIndex(item);
1518 // Now see if this is a collapsed thread and include all the collapsed items as needed
1519 // Also note that this is recursive - each child found is run through this same item loop for validity/child checks as well
1520 if (i >= originalItems || !msgListWidget->tree->isExpanded(item)) {
1521 for (int j = 0; j < item.model()->rowCount(item); ++j) {
1522 selected << item.child(j, 0); // Make sure this is run through the main loop as well - don't add it directly
1526 return translatedIndexes;
1529 void MainWindow::handleMarkAsRead(bool value)
1531 const QModelIndexList translatedIndexes = translatedSelection();
1532 if (translatedIndexes.isEmpty()) {
1533 qDebug() << "Model::handleMarkAsRead: no valid messages";
1534 } else {
1535 imapModel()->markMessagesRead(translatedIndexes, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1536 if (translatedIndexes.contains(m_messageWidget->messageView->currentMessage())) {
1537 m_messageWidget->messageView->stopAutoMarkAsRead();
1542 void MainWindow::slotNextUnread()
1544 QModelIndex current = msgListWidget->tree->currentIndex();
1546 UiUtils::gotoNext(msgListWidget->tree->model(), current,
1547 [](const QModelIndex &idx) { return !idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool(); },
1548 [this](const QModelIndex &idx) {
1549 Q_ASSERT(!idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool());
1550 m_messageWidget->messageView->setMessage(idx);
1551 msgListWidget->tree->setCurrentIndex(idx);
1553 []() {
1554 // nothing to do
1558 void MainWindow::slotPreviousUnread()
1560 QModelIndex current = msgListWidget->tree->currentIndex();
1562 UiUtils::gotoPrevious(msgListWidget->tree->model(), current,
1563 [](const QModelIndex &idx) { return !idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool(); },
1564 [this](const QModelIndex &idx) {
1565 Q_ASSERT(!idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool());
1566 m_messageWidget->messageView->setMessage(idx);
1567 msgListWidget->tree->setCurrentIndex(idx);
1569 []() {
1570 // nothing to do
1574 void MainWindow::handleTag(const bool checked, const int index)
1576 const QModelIndexList &translatedIndexes = translatedSelection();
1577 if (translatedIndexes.isEmpty()) {
1578 qDebug() << "Model::handleTag: no valid messages";
1579 } else {
1580 const auto &tagName = m_favoriteTags->tagNameByIndex(index);
1581 if (!tagName.isEmpty())
1582 imapModel()->setMessageFlags(translatedIndexes, tagName, checked ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1586 void MainWindow::handleMarkAsDeleted(bool value)
1588 const QModelIndexList translatedIndexes = translatedSelection();
1589 if (translatedIndexes.isEmpty()) {
1590 qDebug() << "Model::handleMarkAsDeleted: no valid messages";
1591 } else {
1592 imapModel()->markMessagesDeleted(translatedIndexes, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1596 void MainWindow::handleMarkAsFlagged(const bool value)
1598 const QModelIndexList translatedIndexes = translatedSelection();
1599 if (translatedIndexes.isEmpty()) {
1600 qDebug() << "Model::handleMarkAsFlagged: no valid messages";
1601 } else {
1602 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::flagged, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1606 void MainWindow::handleMarkAsJunk(const bool value)
1608 const QModelIndexList translatedIndexes = translatedSelection();
1609 if (translatedIndexes.isEmpty()) {
1610 qDebug() << "Model::handleMarkAsJunk: no valid messages";
1611 } else {
1612 if (value) {
1613 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::notjunk, Imap::Mailbox::FLAG_REMOVE);
1615 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::junk, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1619 void MainWindow::handleMarkAsNotJunk(const bool value)
1621 const QModelIndexList translatedIndexes = translatedSelection();
1622 if (translatedIndexes.isEmpty()) {
1623 qDebug() << "Model::handleMarkAsNotJunk: no valid messages";
1624 } else {
1625 if (value) {
1626 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::junk, Imap::Mailbox::FLAG_REMOVE);
1628 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::notjunk, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1632 void MainWindow::slotMoveToArchiveFailed(const QString &error)
1634 // XXX disable busy cursor
1635 QMessageBox::critical(this, tr("Failed to archive"), error);
1638 void MainWindow::handleMoveToArchive()
1640 const QModelIndexList translatedIndexes = translatedSelection();
1641 if (translatedIndexes.isEmpty()) {
1642 qDebug() << "Model::handleMoveToArchive: no valid messages";
1643 } else {
1644 auto archiveFolderName = m_settings->value(Common::SettingsNames::imapArchiveFolderName).toString();
1645 auto copyMoveMessagesTask = imapModel()->copyMoveMessages(
1646 archiveFolderName.isEmpty() ? Common::SettingsNames::imapDefaultArchiveFolderName : archiveFolderName,
1647 translatedIndexes, Imap::Mailbox::CopyMoveOperation::MOVE);
1648 connect(copyMoveMessagesTask, &Imap::Mailbox::ImapTask::failed, this, &MainWindow::slotMoveToArchiveFailed);
1653 void MainWindow::slotExpunge()
1655 imapModel()->expungeMailbox(qobject_cast<Imap::Mailbox::MsgListModel *>(m_imapAccess->msgListModel())->currentMailbox());
1658 void MainWindow::slotMarkCurrentMailboxRead()
1660 imapModel()->markMailboxAsRead(mboxTree->currentIndex());
1663 void MainWindow::slotCreateMailboxBelowCurrent()
1665 createMailboxBelow(mboxTree->currentIndex());
1668 void MainWindow::slotCreateTopMailbox()
1670 createMailboxBelow(QModelIndex());
1673 void MainWindow::createMailboxBelow(const QModelIndex &index)
1675 Imap::Mailbox::TreeItemMailbox *mboxPtr = index.isValid() ?
1676 dynamic_cast<Imap::Mailbox::TreeItemMailbox *>(
1677 Imap::Mailbox::Model::realTreeItem(index)) :
1680 Ui::CreateMailboxDialog ui;
1681 QDialog *dialog = new QDialog(this);
1682 ui.setupUi(dialog);
1684 dialog->setWindowTitle(mboxPtr ?
1685 tr("Create a Subfolder of %1").arg(mboxPtr->mailbox()) :
1686 tr("Create a Top-level Mailbox"));
1688 if (dialog->exec() == QDialog::Accepted) {
1689 QStringList parts;
1690 if (mboxPtr)
1691 parts << mboxPtr->mailbox();
1692 parts << ui.mailboxName->text();
1693 if (ui.otherMailboxes->isChecked())
1694 parts << QString();
1695 QString targetName = parts.join(mboxPtr ? mboxPtr->separator() : QString()); // FIXME: top-level separator
1696 imapModel()->createMailbox(targetName,
1697 ui.subscribe->isChecked() ?
1698 Imap::Mailbox::AutoSubscription::SUBSCRIBE :
1699 Imap::Mailbox::AutoSubscription::NO_EXPLICIT_SUBSCRIPTION
1704 void MainWindow::slotDeleteCurrentMailbox()
1706 if (! mboxTree->currentIndex().isValid())
1707 return;
1709 QModelIndex mailbox = Imap::deproxifiedIndex(mboxTree->currentIndex());
1710 Q_ASSERT(mailbox.isValid());
1711 QString name = mailbox.data(Imap::Mailbox::RoleMailboxName).toString();
1713 if (QMessageBox::question(this, tr("Delete Mailbox"),
1714 tr("Are you sure to delete mailbox %1?").arg(name),
1715 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
1716 imapModel()->deleteMailbox(name);
1720 void MainWindow::updateMessageFlags()
1722 updateMessageFlagsOf(QModelIndex());
1725 void MainWindow::updateMessageFlagsOf(const QModelIndex &index)
1727 QModelIndexList indexes = index.isValid() ? QModelIndexList() << index : translatedSelection();
1728 const bool isValid = !indexes.isEmpty() &&
1729 // either we operate on the -already valided- selection or the index must be valid
1730 (!index.isValid() || index.data(Imap::Mailbox::RoleMessageUid).toUInt() > 0);
1731 const bool okToModify = imapModel()->isNetworkAvailable() && isValid;
1733 markAsRead->setEnabled(okToModify);
1734 markAsDeleted->setEnabled(okToModify);
1735 markAsFlagged->setEnabled(okToModify);
1736 markAsJunk->setEnabled(okToModify);
1737 markAsNotJunk->setEnabled(okToModify);
1739 // There's no point in moving from Archive to, well, Archive
1740 auto archiveFolderName = m_settings->value(Common::SettingsNames::imapArchiveFolderName).toString();
1741 if (archiveFolderName.isEmpty()) {
1742 archiveFolderName = Common::SettingsNames::imapDefaultArchiveFolderName;
1744 moveToArchive->setEnabled(okToModify &&
1745 std::any_of(indexes.cbegin(), indexes.cend(),
1746 [archiveFolderName](const QModelIndex &i) {
1747 return i.data(Imap::Mailbox::RoleMailboxName) != archiveFolderName;
1748 }));
1750 tag1->setEnabled(okToModify);
1751 tag2->setEnabled(okToModify);
1752 tag3->setEnabled(okToModify);
1753 tag4->setEnabled(okToModify);
1754 tag5->setEnabled(okToModify);
1756 bool isRead = isValid,
1757 isDeleted = isValid,
1758 isFlagged = isValid,
1759 isJunk = isValid,
1760 isNotJunk = isValid,
1761 hasTag1 = isValid,
1762 hasTag2 = isValid,
1763 hasTag3 = isValid,
1764 hasTag4 = isValid,
1765 hasTag5 = isValid;
1766 auto updateTag = [=](const QModelIndex &i, bool &hasTag, int index) {
1767 if (hasTag && !m_favoriteTags->tagNameByIndex(index).isEmpty() &&
1768 !i.data(Imap::Mailbox::RoleMessageFlags).toStringList().contains(m_favoriteTags->tagNameByIndex(index)))
1770 hasTag = false;
1773 Q_FOREACH (const QModelIndex &i, indexes) {
1774 #define UPDATE_STATE(PROP) \
1775 if (is##PROP && !i.data(Imap::Mailbox::RoleMessageIsMarked##PROP).toBool()) \
1776 is##PROP = false;
1777 UPDATE_STATE(Read)
1778 UPDATE_STATE(Deleted)
1779 UPDATE_STATE(Flagged)
1780 UPDATE_STATE(Junk)
1781 UPDATE_STATE(NotJunk)
1782 #undef UPDATE_STATE
1783 updateTag(i, hasTag1, 0);
1784 updateTag(i, hasTag2, 1);
1785 updateTag(i, hasTag3, 2);
1786 updateTag(i, hasTag4, 3);
1787 updateTag(i, hasTag5, 4);
1789 markAsRead->setChecked(isRead);
1790 markAsDeleted->setChecked(isDeleted);
1791 markAsFlagged->setChecked(isFlagged);
1792 markAsJunk->setChecked(isJunk && !isNotJunk);
1793 markAsNotJunk->setChecked(isNotJunk && !isJunk);
1795 tag1->setChecked(hasTag1);
1796 tag2->setChecked(hasTag2);
1797 tag3->setChecked(hasTag3);
1798 tag4->setChecked(hasTag4);
1799 tag5->setChecked(hasTag5);
1802 void MainWindow::updateActionsOnlineOffline(bool online)
1804 reloadMboxList->setEnabled(online);
1805 resyncMbox->setEnabled(online);
1806 expunge->setEnabled(online);
1807 createChildMailbox->setEnabled(online);
1808 createTopMailbox->setEnabled(online);
1809 deleteCurrentMailbox->setEnabled(online);
1810 m_actionMarkMailboxAsRead->setEnabled(online);
1811 updateMessageFlags();
1812 showImapCapabilities->setEnabled(online);
1813 if (!online) {
1814 m_replyGuess->setEnabled(false);
1815 m_replyPrivate->setEnabled(false);
1816 m_replyAll->setEnabled(false);
1817 m_replyAllButMe->setEnabled(false);
1818 m_replyList->setEnabled(false);
1819 m_forwardAsAttachment->setEnabled(false);
1820 m_bounce->setEnabled(false);
1824 void MainWindow::slotUpdateMessageActions()
1826 Composer::RecipientList dummy;
1827 m_replyPrivate->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_PRIVATE, senderIdentitiesModel(),
1828 m_messageWidget->messageView->currentMessage(), dummy));
1829 m_replyAllButMe->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_ALL_BUT_ME, senderIdentitiesModel(),
1830 m_messageWidget->messageView->currentMessage(), dummy));
1831 m_replyAll->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_ALL, senderIdentitiesModel(),
1832 m_messageWidget->messageView->currentMessage(), dummy));
1833 m_replyList->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_LIST, senderIdentitiesModel(),
1834 m_messageWidget->messageView->currentMessage(), dummy));
1835 m_replyGuess->setEnabled(m_replyPrivate->isEnabled() || m_replyAllButMe->isEnabled()
1836 || m_replyAll->isEnabled() || m_replyList->isEnabled());
1838 // Check the default reply mode
1839 // I suspect this is not going to work for everybody. Suggestions welcome...
1840 if (m_replyList->isEnabled()) {
1841 m_replyButton->setDefaultAction(m_replyList);
1842 } else if (m_replyAllButMe->isEnabled()) {
1843 m_replyButton->setDefaultAction(m_replyAllButMe);
1844 } else {
1845 m_replyButton->setDefaultAction(m_replyPrivate);
1848 m_forwardAsAttachment->setEnabled(m_messageWidget->messageView->currentMessage().isValid());
1849 m_bounce->setEnabled(m_messageWidget->messageView->currentMessage().isValid());
1852 void MainWindow::scrollMessageUp()
1854 m_messageWidget->area->ensureVisible(0, 0, 0, 0);
1857 void MainWindow::slotReplyTo()
1859 m_messageWidget->messageView->reply(this, Composer::REPLY_PRIVATE);
1862 void MainWindow::slotReplyAll()
1864 m_messageWidget->messageView->reply(this, Composer::REPLY_ALL);
1867 void MainWindow::slotReplyAllButMe()
1869 m_messageWidget->messageView->reply(this, Composer::REPLY_ALL_BUT_ME);
1872 void MainWindow::slotReplyList()
1874 m_messageWidget->messageView->reply(this, Composer::REPLY_LIST);
1877 void MainWindow::slotReplyGuess()
1879 if (m_replyButton->defaultAction() == m_replyAllButMe) {
1880 slotReplyAllButMe();
1881 } else if (m_replyButton->defaultAction() == m_replyAll) {
1882 slotReplyAll();
1883 } else if (m_replyButton->defaultAction() == m_replyList) {
1884 slotReplyList();
1885 } else {
1886 slotReplyTo();
1890 void MainWindow::slotForwardAsAttachment()
1892 m_messageWidget->messageView->forward(this, Composer::ForwardMode::FORWARD_AS_ATTACHMENT);
1895 void MainWindow::slotBounce()
1897 QModelIndex index;
1898 Imap::Mailbox::Model::realTreeItem(msgListWidget->tree->currentIndex(), nullptr, &index);
1899 if (!index.isValid())
1900 return;
1902 auto recipients = QList<QPair<Composer::RecipientKind,QString>>();
1903 for (const auto &kind: {Imap::Mailbox::RoleMessageTo, Imap::Mailbox::RoleMessageCc, Imap::Mailbox::RoleMessageBcc}) {
1904 for (const auto &oneAddr : index.data(kind).toList()) {
1905 Q_ASSERT(oneAddr.type() == QVariant::StringList);
1906 QStringList item = oneAddr.toStringList();
1907 Q_ASSERT(item.size() == 4);
1908 Imap::Message::MailAddress a(item[0], item[1], item[2], item[3]);
1909 Composer::RecipientKind translatedKind = Composer::RecipientKind::ADDRESS_TO;
1910 switch (kind) {
1911 case Imap::Mailbox::RoleMessageTo:
1912 translatedKind = Composer::RecipientKind::ADDRESS_RESENT_TO;
1913 break;
1914 case Imap::Mailbox::RoleMessageCc:
1915 translatedKind = Composer::RecipientKind::ADDRESS_RESENT_CC;
1916 break;
1917 case Imap::Mailbox::RoleMessageBcc:
1918 translatedKind = Composer::RecipientKind::ADDRESS_RESENT_BCC;
1919 break;
1920 default:
1921 Q_ASSERT(false);
1922 break;
1924 recipients.push_back({translatedKind, a.asPrettyString()});
1928 ComposeWidget::warnIfMsaNotConfigured(
1929 ComposeWidget::createFromReadOnly(this, index, recipients),
1930 this);
1934 void MainWindow::slotComposeMailUrl(const QUrl &url)
1936 ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createFromUrl(this, url), this);
1939 void MainWindow::slotManageContact(const QUrl &url)
1941 Imap::Message::MailAddress addr;
1942 if (!Imap::Message::MailAddress::fromUrl(addr, url, QStringLiteral("x-trojita-manage-contact")))
1943 return;
1945 Plugins::AddressbookPlugin *addressbook = pluginManager()->addressbook();
1946 if (!addressbook)
1947 return;
1949 addressbook->openContactWindow(addr.mailbox + QLatin1Char('@') + addr.host, addr.name);
1952 void MainWindow::invokeContactEditor()
1954 Plugins::AddressbookPlugin *addressbook = pluginManager()->addressbook();
1955 if (!addressbook)
1956 return;
1958 addressbook->openAddressbookWindow();
1961 /** @short Create an MSAFactory as per the settings */
1962 MSA::MSAFactory *MainWindow::msaFactory()
1964 using namespace Common;
1965 QString method = m_settings->value(SettingsNames::msaMethodKey).toString();
1966 MSA::MSAFactory *msaFactory = 0;
1967 if (method == SettingsNames::methodSMTP || method == SettingsNames::methodSSMTP) {
1968 msaFactory = new MSA::SMTPFactory(m_settings->value(SettingsNames::smtpHostKey).toString(),
1969 m_settings->value(SettingsNames::smtpPortKey).toInt(),
1970 (method == SettingsNames::methodSSMTP),
1971 (method == SettingsNames::methodSMTP)
1972 && m_settings->value(SettingsNames::smtpStartTlsKey).toBool(),
1973 m_settings->value(SettingsNames::smtpAuthKey).toBool(),
1974 m_settings->value(SettingsNames::smtpAuthReuseImapCredsKey, false).toBool() ?
1975 m_settings->value(SettingsNames::imapUserKey).toString() :
1976 m_settings->value(SettingsNames::smtpUserKey).toString());
1977 } else if (method == SettingsNames::methodSENDMAIL) {
1978 QStringList args = m_settings->value(SettingsNames::sendmailKey, SettingsNames::sendmailDefaultCmd).toString().split(QLatin1Char(' '));
1979 if (args.isEmpty()) {
1980 return 0;
1982 QString appName = args.takeFirst();
1983 msaFactory = new MSA::SendmailFactory(appName, args);
1984 } else if (method == SettingsNames::methodImapSendmail) {
1985 if (!imapModel()->capabilities().contains(QStringLiteral("X-DRAFT-I01-SENDMAIL"))) {
1986 return 0;
1988 msaFactory = new MSA::ImapSubmitFactory(qobject_cast<Imap::Mailbox::Model*>(imapAccess()->imapModel()));
1989 } else {
1990 return 0;
1992 return msaFactory;
1995 void MainWindow::slotMailboxDeleteFailed(const QString &mailbox, const QString &msg)
1997 Gui::Util::messageBoxWarning(this, tr("Can't delete mailbox"),
1998 tr("Deleting mailbox \"%1\" failed with the following message:\n%2").arg(mailbox, msg));
2001 void MainWindow::slotMailboxCreateFailed(const QString &mailbox, const QString &msg)
2003 Gui::Util::messageBoxWarning(this, tr("Can't create mailbox"),
2004 tr("Creating mailbox \"%1\" failed with the following message:\n%2").arg(mailbox, msg));
2007 void MainWindow::slotMailboxSyncFailed(const QString &mailbox, const QString &msg)
2009 Gui::Util::messageBoxWarning(this, tr("Can't open mailbox"),
2010 tr("Opening mailbox \"%1\" failed with the following message:\n%2").arg(mailbox, msg));
2013 void MainWindow::slotMailboxChanged(const QModelIndex &mailbox)
2015 using namespace Imap::Mailbox;
2016 QString mailboxName = mailbox.data(RoleMailboxName).toString();
2017 bool isSentMailbox = mailbox.isValid() && !mailboxName.isEmpty() &&
2018 m_settings->value(Common::SettingsNames::composerSaveToImapKey).toBool() &&
2019 mailboxName == m_settings->value(Common::SettingsNames::composerImapSentKey).toString();
2020 QTreeView *tree = msgListWidget->tree;
2022 // Automatically trigger visibility of the TO and FROM columns
2023 if (isSentMailbox) {
2024 if (tree->isColumnHidden(MsgListModel::TO) && !tree->isColumnHidden(MsgListModel::FROM)) {
2025 tree->hideColumn(MsgListModel::FROM);
2026 tree->showColumn(MsgListModel::TO);
2028 } else {
2029 if (tree->isColumnHidden(MsgListModel::FROM) && !tree->isColumnHidden(MsgListModel::TO)) {
2030 tree->hideColumn(MsgListModel::TO);
2031 tree->showColumn(MsgListModel::FROM);
2035 updateMessageFlags();
2036 slotScrollToUnseenMessage();
2039 void MainWindow::showConnectionStatus(uint parserId, Imap::ConnectionState state)
2041 Q_UNUSED(parserId);
2042 static Imap::ConnectionState previousState = Imap::ConnectionState::CONN_STATE_NONE;
2043 QString message = connectionStateToString(state);
2045 if (state == Imap::ConnectionState::CONN_STATE_SELECTED && previousState >= Imap::ConnectionState::CONN_STATE_SELECTED) {
2046 // prevent excessive popups when we "reset the state" to something which is shown quite often
2047 showStatusMessage(QString());
2048 } else {
2049 showStatusMessage(message);
2051 previousState = state;
2054 void MainWindow::slotShowLinkTarget(const QString &link)
2056 if (link.isEmpty()) {
2057 QToolTip::hideText();
2058 } else {
2059 QToolTip::showText(QCursor::pos(), tr("Link target: %1").arg(UiUtils::Formatting::htmlEscaped(link)));
2063 void MainWindow::slotShowAboutTrojita()
2065 Ui::AboutDialog ui;
2066 QDialog *widget = new QDialog(this);
2067 widget->setAttribute(Qt::WA_DeleteOnClose);
2068 ui.setupUi(widget);
2069 ui.versionLabel->setText(Common::Application::version);
2070 ui.qtVersion->setText(QStringLiteral("<a href=\"about-qt\">Qt " QT_VERSION_STR "</a>"));
2071 connect(ui.qtVersion, &QLabel::linkActivated, qApp, &QApplication::aboutQt);
2073 std::vector<std::pair<QString, bool>> features;
2074 features.emplace_back(tr("Plugins"),
2075 #ifdef WITH_SHARED_PLUGINS
2076 true
2077 #else
2078 false
2079 #endif
2081 features.emplace_back(tr("Encrypted and signed messages"),
2082 #ifdef TROJITA_HAVE_CRYPTO_MESSAGES
2083 true
2084 #else
2085 false
2086 #endif
2088 features.emplace_back(tr("IMAP compression"),
2089 #ifdef TROJITA_HAVE_ZLIB
2090 true
2091 #else
2092 false
2093 #endif
2096 QString featuresText = QStringLiteral("<ul>");
2097 for (const auto x: features) {
2098 featuresText += x.second ?
2099 tr("<li>%1: supported</li>").arg(x.first)
2100 : tr("<li>%1: <strong>disabled</strong></li>").arg(x.first);
2102 featuresText += QStringLiteral("</ul>");
2103 ui.descriptionLabel->setText(ui.descriptionLabel->text() + featuresText);
2105 QStringList copyright;
2107 // Find the names of the authors and remove date codes from there
2108 QFile license(QStringLiteral(":/LICENSE"));
2109 license.open(QFile::ReadOnly);
2110 const QString prefix(QStringLiteral("Copyright (C) "));
2111 Q_FOREACH(const QString &line, QString::fromUtf8(license.readAll()).split(QLatin1Char('\n'))) {
2112 if (line.startsWith(prefix)) {
2113 const int pos = prefix.size();
2114 copyright << QChar(0xa9 /* COPYRIGHT SIGN */) + QLatin1Char(' ') +
2115 line.mid(pos).replace(QRegExp(QLatin1String("(\\d) - (\\d)")),
2116 QLatin1String("\\1") + QChar(0x2014 /* EM DASH */) + QLatin1String("\\2"));
2120 ui.credits->setTextFormat(Qt::PlainText);
2121 ui.credits->setText(copyright.join(QStringLiteral("\n")));
2122 widget->show();
2125 void MainWindow::slotDonateToTrojita()
2127 QDesktopServices::openUrl(QStringLiteral("https://sourceforge.net/p/trojita/donate/"));
2130 void MainWindow::slotSaveCurrentMessageBody()
2132 Q_FOREACH(const QModelIndex &item, msgListWidget->tree->selectionModel()->selectedIndexes()) {
2133 Q_ASSERT(item.isValid());
2134 if (item.column() != 0)
2135 continue;
2136 if (! item.data(Imap::Mailbox::RoleMessageUid).isValid())
2137 continue;
2139 QModelIndex messageIndex = Imap::deproxifiedIndex(item);
2141 Imap::Network::MsgPartNetAccessManager *netAccess = new Imap::Network::MsgPartNetAccessManager(this);
2142 netAccess->setModelMessage(messageIndex);
2143 Imap::Network::FileDownloadManager *fileDownloadManager =
2144 new Imap::Network::FileDownloadManager(this, netAccess, messageIndex);
2145 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::succeeded, fileDownloadManager, &QObject::deleteLater);
2146 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::transferError, fileDownloadManager, &QObject::deleteLater);
2147 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::fileNameRequested,
2148 this, &MainWindow::slotDownloadMessageFileNameRequested);
2149 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::transferError,
2150 this, &MainWindow::slotDownloadTransferError);
2151 connect(fileDownloadManager, &QObject::destroyed, netAccess, &QObject::deleteLater);
2152 fileDownloadManager->downloadMessage();
2156 void MainWindow::slotDownloadTransferError(const QString &errorString)
2158 Gui::Util::messageBoxCritical(this, tr("Can't save into file"),
2159 tr("Unable to save into file. Error:\n%1").arg(errorString));
2162 void MainWindow::slotDownloadMessageFileNameRequested(QString *fileName)
2164 *fileName = QFileDialog::getSaveFileName(this, tr("Save Message"), *fileName, QString(), 0,
2165 QFileDialog::HideNameFilterDetails);
2168 void MainWindow::slotViewMsgSource()
2170 Q_FOREACH(const QModelIndex &item, msgListWidget->tree->selectionModel()->selectedIndexes()) {
2171 Q_ASSERT(item.isValid());
2172 if (item.column() != 0)
2173 continue;
2174 if (! item.data(Imap::Mailbox::RoleMessageUid).isValid())
2175 continue;
2176 auto w = messageSourceWidget(item);
2177 //: Translators: %1 is the UID of a message (a number) and %2 is the name of a mailbox.
2178 w->setWindowTitle(tr("Message source of UID %1 in %2").arg(
2179 QString::number(item.data(Imap::Mailbox::RoleMessageUid).toUInt()),
2180 Imap::deproxifiedIndex(item).parent().parent().data(Imap::Mailbox::RoleMailboxName).toString()
2182 w->show();
2186 QWidget *MainWindow::messageSourceWidget(const QModelIndex &message)
2188 QModelIndex messageIndex = Imap::deproxifiedIndex(message);
2189 MessageSourceWidget *sourceWidget = new MessageSourceWidget(0, messageIndex);
2190 sourceWidget->setAttribute(Qt::WA_DeleteOnClose);
2191 QAction *close = new QAction(UiUtils::loadIcon(QStringLiteral("window-close")), tr("Close"), sourceWidget);
2192 sourceWidget->addAction(close);
2193 close->setShortcut(tr("Ctrl+W"));
2194 connect(close, &QAction::triggered, sourceWidget, &QWidget::close);
2195 return sourceWidget;
2198 void MainWindow::slotViewMsgHeaders()
2200 Q_FOREACH(const QModelIndex &item, msgListWidget->tree->selectionModel()->selectedIndexes()) {
2201 Q_ASSERT(item.isValid());
2202 if (item.column() != 0)
2203 continue;
2204 if (! item.data(Imap::Mailbox::RoleMessageUid).isValid())
2205 continue;
2206 QModelIndex messageIndex = Imap::deproxifiedIndex(item);
2208 auto widget = new MessageHeadersWidget(nullptr, messageIndex);
2209 widget->setAttribute(Qt::WA_DeleteOnClose);
2210 QAction *close = new QAction(UiUtils::loadIcon(QStringLiteral("window-close")), tr("Close"), widget);
2211 widget->addAction(close);
2212 close->setShortcut(tr("Ctrl+W"));
2213 connect(close, &QAction::triggered, widget, &QWidget::close);
2214 widget->show();
2218 #ifdef XTUPLE_CONNECT
2219 void MainWindow::slotXtSyncCurrentMailbox()
2221 QModelIndex index = mboxTree->currentIndex();
2222 if (! index.isValid())
2223 return;
2225 QString mailbox = index.data(Imap::Mailbox::RoleMailboxName).toString();
2226 QSettings s;
2227 QStringList mailboxes = s.value(Common::SettingsNames::xtSyncMailboxList).toStringList();
2228 if (xtIncludeMailboxInSync->isChecked()) {
2229 if (! mailboxes.contains(mailbox)) {
2230 mailboxes.append(mailbox);
2232 } else {
2233 mailboxes.removeAll(mailbox);
2235 s.setValue(Common::SettingsNames::xtSyncMailboxList, mailboxes);
2236 QSettings(QSettings::UserScope, QString::fromAscii("xTuple.com"), QString::fromAscii("xTuple")).setValue(Common::SettingsNames::xtSyncMailboxList, mailboxes);
2237 prettyMboxModel->xtConnectStatusChanged(index);
2239 #endif
2241 void MainWindow::slotSubscribeCurrentMailbox()
2243 QModelIndex index = mboxTree->currentIndex();
2244 if (! index.isValid())
2245 return;
2247 QString mailbox = index.data(Imap::Mailbox::RoleMailboxName).toString();
2248 if (m_actionSubscribeMailbox->isChecked()) {
2249 imapModel()->subscribeMailbox(mailbox);
2250 } else {
2251 imapModel()->unsubscribeMailbox(mailbox);
2255 void MainWindow::slotShowOnlySubscribed()
2257 if (m_actionShowOnlySubscribed->isEnabled()) {
2258 m_settings->setValue(Common::SettingsNames::guiMailboxListShowOnlySubscribed, m_actionShowOnlySubscribed->isChecked());
2259 prettyMboxModel->setShowOnlySubscribed(m_actionShowOnlySubscribed->isChecked());
2263 void MainWindow::slotScrollToUnseenMessage()
2265 // Now this is much, much more reliable than messing around with finding out an "interesting message"...
2266 if (!m_actionSortNone->isChecked() && !m_actionSortThreading->isChecked()) {
2267 // we're using some funky sorting, better don't scroll anywhere
2269 if (m_actionSortDescending->isChecked()) {
2270 msgListWidget->tree->scrollToTop();
2271 } else {
2272 msgListWidget->tree->scrollToBottom();
2276 void MainWindow::slotScrollToCurrent()
2278 // TODO: begs for lambda
2279 if (QScrollBar *vs = msgListWidget->tree->verticalScrollBar()) {
2280 vs->setValue(vs->maximum() - vs->value()); // implies vs->minimum() == 0
2284 void MainWindow::slotThreadMsgList()
2286 // We want to save user's preferences and not override them with "threading disabled" when the server
2287 // doesn't report them, like in initial greetings. That's why we have to check for isEnabled() here.
2288 const bool useThreading = actionThreadMsgList->isChecked();
2290 // Switching between threaded/unthreaded view shall reset the sorting criteria. The goal is to make
2291 // sorting rather seldomly used as people shall instead use proper threading.
2292 if (useThreading) {
2293 m_actionSortThreading->setEnabled(true);
2294 if (!m_actionSortThreading->isChecked())
2295 m_actionSortThreading->trigger();
2296 m_actionSortNone->setEnabled(false);
2297 } else {
2298 m_actionSortNone->setEnabled(true);
2299 if (!m_actionSortNone->isChecked())
2300 m_actionSortNone->trigger();
2301 m_actionSortThreading->setEnabled(false);
2304 QPersistentModelIndex currentItem = msgListWidget->tree->currentIndex();
2306 if (useThreading && actionThreadMsgList->isEnabled()) {
2307 msgListWidget->tree->setRootIsDecorated(true);
2308 qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(m_imapAccess->threadingMsgListModel())->setUserWantsThreading(true);
2309 } else {
2310 msgListWidget->tree->setRootIsDecorated(false);
2311 qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(m_imapAccess->threadingMsgListModel())->setUserWantsThreading(false);
2313 m_settings->setValue(Common::SettingsNames::guiMsgListShowThreading, QVariant(useThreading));
2315 if (currentItem.isValid()) {
2316 msgListWidget->tree->scrollTo(currentItem);
2317 } else {
2318 // If we cannot determine the current item, at least scroll to a predictable place. Without this, the view
2319 // would jump to "weird" places, probably due to some heuristics about trying to show "roughly the same"
2320 // objects as what was visible before the reshuffling.
2321 slotScrollToUnseenMessage();
2325 void MainWindow::slotSortingPreferenceChanged()
2327 Qt::SortOrder order = m_actionSortDescending->isChecked() ? Qt::DescendingOrder : Qt::AscendingOrder;
2329 using namespace Imap::Mailbox;
2331 int column = -1;
2332 if (m_actionSortByArrival->isChecked()) {
2333 column = MsgListModel::RECEIVED_DATE;
2334 } else if (m_actionSortByCc->isChecked()) {
2335 column = MsgListModel::CC;
2336 } else if (m_actionSortByDate->isChecked()) {
2337 column = MsgListModel::DATE;
2338 } else if (m_actionSortByFrom->isChecked()) {
2339 column = MsgListModel::FROM;
2340 } else if (m_actionSortBySize->isChecked()) {
2341 column = MsgListModel::SIZE;
2342 } else if (m_actionSortBySubject->isChecked()) {
2343 column = MsgListModel::SUBJECT;
2344 } else if (m_actionSortByTo->isChecked()) {
2345 column = MsgListModel::TO;
2346 } else {
2347 column = -1;
2350 msgListWidget->tree->header()->setSortIndicator(column, order);
2353 void MainWindow::slotSortingConfirmed(int column, Qt::SortOrder order)
2355 // don't do anything during initialization
2356 if (!m_actionSortNone)
2357 return;
2359 using namespace Imap::Mailbox;
2360 QAction *action;
2362 switch (column) {
2363 case MsgListModel::SEEN:
2364 case MsgListModel::FLAGGED:
2365 case MsgListModel::ATTACHMENT:
2366 case MsgListModel::COLUMN_COUNT:
2367 case MsgListModel::BCC:
2368 case -1:
2369 if (actionThreadMsgList->isChecked())
2370 action = m_actionSortThreading;
2371 else
2372 action = m_actionSortNone;
2373 break;
2374 case MsgListModel::SUBJECT:
2375 action = m_actionSortBySubject;
2376 break;
2377 case MsgListModel::FROM:
2378 action = m_actionSortByFrom;
2379 break;
2380 case MsgListModel::TO:
2381 action = m_actionSortByTo;
2382 break;
2383 case MsgListModel::CC:
2384 action = m_actionSortByCc;
2385 break;
2386 case MsgListModel::DATE:
2387 action = m_actionSortByDate;
2388 break;
2389 case MsgListModel::RECEIVED_DATE:
2390 action = m_actionSortByArrival;
2391 break;
2392 case MsgListModel::SIZE:
2393 action = m_actionSortBySize;
2394 break;
2395 default:
2396 action = m_actionSortNone;
2399 action->setChecked(true);
2400 if (order == Qt::DescendingOrder)
2401 m_actionSortDescending->setChecked(true);
2402 else
2403 m_actionSortAscending->setChecked(true);
2406 void MainWindow::slotSearchRequested(const QStringList &searchConditions)
2408 if (!searchConditions.isEmpty() && actionThreadMsgList->isChecked()) {
2409 // right now, searching and threading doesn't play well together at all
2410 actionThreadMsgList->trigger();
2412 Imap::Mailbox::ThreadingMsgListModel * threadingMsgListModel =
2413 qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(m_imapAccess->threadingMsgListModel());
2414 threadingMsgListModel->setUserSearchingSortingPreference(searchConditions, threadingMsgListModel->currentSortCriterium(),
2415 threadingMsgListModel->currentSortOrder());
2418 void MainWindow::slotHideRead()
2420 const bool hideRead = actionHideRead->isChecked();
2421 prettyMsgListModel->setHideRead(hideRead);
2422 m_settings->setValue(Common::SettingsNames::guiMsgListHideRead, QVariant(hideRead));
2425 void MainWindow::slotCapabilitiesUpdated(const QStringList &capabilities)
2427 msgListWidget->tree->header()->viewport()->removeEventFilter(this);
2428 if (capabilities.contains(QStringLiteral("SORT"))) {
2429 m_actionSortByDate->actionGroup()->setEnabled(true);
2430 } else {
2431 m_actionSortByDate->actionGroup()->setEnabled(false);
2432 msgListWidget->tree->header()->viewport()->installEventFilter(this);
2435 msgListWidget->setFuzzySearchSupported(capabilities.contains(QStringLiteral("SEARCH=FUZZY")));
2437 m_actionShowOnlySubscribed->setEnabled(capabilities.contains(QStringLiteral("LIST-EXTENDED")));
2438 m_actionShowOnlySubscribed->setChecked(m_actionShowOnlySubscribed->isEnabled() &&
2439 m_settings->value(
2440 Common::SettingsNames::guiMailboxListShowOnlySubscribed, false).toBool());
2441 m_actionSubscribeMailbox->setEnabled(m_actionShowOnlySubscribed->isEnabled());
2443 const QStringList supportedCapabilities = Imap::Mailbox::ThreadingMsgListModel::supportedCapabilities();
2444 Q_FOREACH(const QString &capability, capabilities) {
2445 if (supportedCapabilities.contains(capability)) {
2446 actionThreadMsgList->setEnabled(true);
2447 if (actionThreadMsgList->isChecked())
2448 slotThreadMsgList();
2449 return;
2452 actionThreadMsgList->setEnabled(false);
2455 void MainWindow::slotShowImapInfo()
2457 QString caps;
2458 Q_FOREACH(const QString &cap, imapModel()->capabilities()) {
2459 caps += tr("<li>%1</li>\n").arg(cap);
2462 QString idString;
2463 if (!imapModel()->serverId().isEmpty() && imapModel()->capabilities().contains(QStringLiteral("ID"))) {
2464 QMap<QByteArray,QByteArray> serverId = imapModel()->serverId();
2466 #define IMAP_ID_FIELD(Var, Name) bool has_##Var = serverId.contains(Name); \
2467 QString Var = has_##Var ? QString::fromUtf8(serverId[Name]).toHtmlEscaped() : tr("Unknown");
2468 IMAP_ID_FIELD(serverName, "name");
2469 IMAP_ID_FIELD(serverVersion, "version");
2470 IMAP_ID_FIELD(os, "os");
2471 IMAP_ID_FIELD(osVersion, "os-version");
2472 IMAP_ID_FIELD(vendor, "vendor");
2473 IMAP_ID_FIELD(supportUrl, "support-url");
2474 IMAP_ID_FIELD(address, "address");
2475 IMAP_ID_FIELD(date, "date");
2476 IMAP_ID_FIELD(command, "command");
2477 IMAP_ID_FIELD(arguments, "arguments");
2478 IMAP_ID_FIELD(environment, "environment");
2479 #undef IMAP_ID_FIELD
2480 if (has_serverName) {
2481 idString = tr("<p>");
2482 if (has_serverVersion)
2483 idString += tr("Server: %1 %2").arg(serverName, serverVersion);
2484 else
2485 idString += tr("Server: %1").arg(serverName);
2487 if (has_vendor) {
2488 idString += tr(" (%1)").arg(vendor);
2490 if (has_os) {
2491 if (has_osVersion)
2492 idString += tr(" on %1 %2", "%1 is the operating system of an IMAP server and %2 is its version.").arg(os, osVersion);
2493 else
2494 idString += tr(" on %1", "%1 is the operationg system of an IMAP server.").arg(os);
2496 idString += tr("</p>");
2497 } else {
2498 idString = tr("<p>The IMAP server did not return usable information about itself.</p>");
2500 QString fullId;
2501 for (QMap<QByteArray,QByteArray>::const_iterator it = serverId.constBegin(); it != serverId.constEnd(); ++it) {
2502 fullId += tr("<li>%1: %2</li>").arg(QString::fromUtf8(it.key()).toHtmlEscaped(), QString::fromUtf8(it.value()).toHtmlEscaped());
2504 idString += tr("<ul>%1</ul>").arg(fullId);
2505 } else {
2506 idString = tr("<p>The server has not provided information about its software version.</p>");
2509 QMessageBox::information(this, tr("IMAP Server Information"),
2510 tr("%1"
2511 "<p>The following capabilities are currently advertised:</p>\n"
2512 "<ul>\n%2</ul>").arg(idString, caps));
2515 QSize MainWindow::sizeHint() const
2517 return QSize(1150, 980);
2520 void MainWindow::slotUpdateWindowTitle()
2522 QModelIndex mailbox = qobject_cast<Imap::Mailbox::MsgListModel *>(m_imapAccess->msgListModel())->currentMailbox();
2523 QString profileName = QString::fromUtf8(qgetenv("TROJITA_PROFILE"));
2524 if (!profileName.isEmpty())
2525 profileName = QLatin1String(" [") + profileName + QLatin1Char(']');
2526 if (mailbox.isValid()) {
2527 if (mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt()) {
2528 setWindowTitle(trUtf8("%1 - %n unread - Trojitá", 0, mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt())
2529 .arg(mailbox.data(Imap::Mailbox::RoleShortMailboxName).toString()) + profileName);
2530 } else {
2531 setWindowTitle(trUtf8("%1 - Trojitá").arg(mailbox.data(Imap::Mailbox::RoleShortMailboxName).toString()) + profileName);
2533 } else {
2534 setWindowTitle(trUtf8("Trojitá") + profileName);
2538 void MainWindow::slotLayoutCompact()
2540 saveSizesAndState();
2541 if (!m_mainHSplitter) {
2542 m_mainHSplitter = new QSplitter();
2543 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
2544 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, this, &MainWindow::possiblyLoadMessageOnSplittersChanged);
2546 if (!m_mainVSplitter) {
2547 m_mainVSplitter = new QSplitter();
2548 m_mainVSplitter->setOrientation(Qt::Vertical);
2549 connect(m_mainVSplitter.data(), &QSplitter::splitterMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
2550 connect(m_mainVSplitter.data(), &QSplitter::splitterMoved, this, &MainWindow::possiblyLoadMessageOnSplittersChanged);
2553 m_mainVSplitter->addWidget(msgListWidget);
2554 m_mainVSplitter->addWidget(m_messageWidget);
2555 m_mainHSplitter->addWidget(mboxTree);
2556 m_mainHSplitter->addWidget(m_mainVSplitter);
2558 mboxTree->show();
2559 msgListWidget->show();
2560 m_messageWidget->show();
2561 m_mainVSplitter->show();
2562 m_mainHSplitter->show();
2564 // The mboxTree shall not expand...
2565 m_mainHSplitter->setStretchFactor(0, 0);
2566 // ...while the msgListTree shall consume all the remaining space
2567 m_mainHSplitter->setStretchFactor(1, 1);
2568 // The CompleteMessageWidget shall not not collapse
2569 m_mainVSplitter->setCollapsible(m_mainVSplitter->indexOf(m_messageWidget), false);
2571 setCentralWidget(m_mainHSplitter);
2573 delete m_mainStack;
2575 m_layoutMode = LAYOUT_COMPACT;
2576 m_settings->setValue(Common::SettingsNames::guiMainWindowLayout, Common::SettingsNames::guiMainWindowLayoutCompact);
2577 applySizesAndState();
2580 void MainWindow::slotLayoutWide()
2582 saveSizesAndState();
2583 if (!m_mainHSplitter) {
2584 m_mainHSplitter = new QSplitter();
2585 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
2586 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, this, &MainWindow::possiblyLoadMessageOnSplittersChanged);
2589 m_mainHSplitter->addWidget(mboxTree);
2590 m_mainHSplitter->addWidget(msgListWidget);
2591 m_mainHSplitter->addWidget(m_messageWidget);
2592 msgListWidget->resize(mboxTree->size());
2593 m_messageWidget->resize(mboxTree->size());
2594 m_mainHSplitter->setStretchFactor(0, 0);
2595 m_mainHSplitter->setStretchFactor(1, 1);
2596 m_mainHSplitter->setStretchFactor(2, 1);
2598 m_mainHSplitter->setCollapsible(m_mainHSplitter->indexOf(m_messageWidget), false);
2600 mboxTree->show();
2601 msgListWidget->show();
2602 m_messageWidget->show();
2603 m_mainHSplitter->show();
2605 setCentralWidget(m_mainHSplitter);
2607 delete m_mainStack;
2608 delete m_mainVSplitter;
2610 m_layoutMode = LAYOUT_WIDE;
2611 m_settings->setValue(Common::SettingsNames::guiMainWindowLayout, Common::SettingsNames::guiMainWindowLayoutWide);
2612 applySizesAndState();
2615 void MainWindow::slotLayoutOneAtTime()
2617 saveSizesAndState();
2618 if (m_mainStack)
2619 return;
2621 m_mainStack = new OnePanelAtTimeWidget(this, mboxTree, msgListWidget, m_messageWidget, m_mainToolbar, m_oneAtTimeGoBack);
2622 setCentralWidget(m_mainStack);
2624 delete m_mainHSplitter;
2625 delete m_mainVSplitter;
2627 m_layoutMode = LAYOUT_ONE_AT_TIME;
2628 m_settings->setValue(Common::SettingsNames::guiMainWindowLayout, Common::SettingsNames::guiMainWindowLayoutOneAtTime);
2629 applySizesAndState();
2632 Imap::Mailbox::Model *MainWindow::imapModel() const
2634 return qobject_cast<Imap::Mailbox::Model *>(m_imapAccess->imapModel());
2637 void MainWindow::desktopGeometryChanged()
2639 m_delayedStateSaving->start();
2642 QString MainWindow::settingsKeyForLayout(const LayoutMode layout)
2644 switch (layout) {
2645 case LAYOUT_COMPACT:
2646 return Common::SettingsNames::guiSizesInMainWinWhenCompact;
2647 case LAYOUT_WIDE:
2648 return Common::SettingsNames::guiSizesInMainWinWhenWide;
2649 case LAYOUT_ONE_AT_TIME:
2650 return Common::SettingsNames::guiSizesInaMainWinWhenOneAtATime;
2651 break;
2653 return QString();
2656 void MainWindow::saveSizesAndState()
2658 if (m_skipSavingOfUI)
2659 return;
2661 QRect geometry = qApp->desktop()->availableGeometry(this);
2662 QString key = settingsKeyForLayout(m_layoutMode);
2663 if (key.isEmpty())
2664 return;
2666 QList<QByteArray> items;
2667 items << saveGeometry();
2668 items << saveState();
2669 items << (m_mainVSplitter ? m_mainVSplitter->saveState() : QByteArray());
2670 items << (m_mainHSplitter ? m_mainHSplitter->saveState() : QByteArray());
2671 items << msgListWidget->tree->header()->saveState();
2672 items << QByteArray::number(msgListWidget->tree->header()->count());
2673 for (int i = 0; i < msgListWidget->tree->header()->count(); ++i) {
2674 items << QByteArray::number(msgListWidget->tree->header()->sectionSize(i));
2676 // a bool cannot be pushed directly onto a QByteArray so we must convert it to a number
2677 items << QByteArray::number(menuBar()->isVisible());
2678 QByteArray buf;
2679 QDataStream stream(&buf, QIODevice::WriteOnly);
2680 stream << items.size();
2681 Q_FOREACH(const QByteArray &item, items) {
2682 stream << item;
2685 m_settings->setValue(key.arg(QString::number(geometry.width())), buf);
2688 void MainWindow::saveRawStateSetting(bool enabled)
2690 m_settings->setValue(Common::SettingsNames::guiAllowRawSearch, enabled);
2693 void MainWindow::applySizesAndState()
2695 QRect geometry = qApp->desktop()->availableGeometry(this);
2696 QString key = settingsKeyForLayout(m_layoutMode);
2697 if (key.isEmpty())
2698 return;
2700 QByteArray buf = m_settings->value(key.arg(QString::number(geometry.width()))).toByteArray();
2701 if (buf.isEmpty())
2702 return;
2704 int size;
2705 QDataStream stream(&buf, QIODevice::ReadOnly);
2706 stream >> size;
2707 QByteArray item;
2709 // There are slots connected to various events triggered by both restoreGeometry() and restoreState() which would attempt to
2710 // save our geometries and state, which is what we must avoid while this method is executing.
2711 bool skipSaving = m_skipSavingOfUI;
2712 m_skipSavingOfUI = true;
2714 if (size-- && !stream.atEnd()) {
2715 stream >> item;
2717 // https://bugreports.qt-project.org/browse/QTBUG-30636
2718 if (windowState() & Qt::WindowMaximized) {
2719 // restoreGeometry(.) restores the wrong size for at least maximized window
2720 // However, QWidget does also not notice that the configure request for this
2721 // is ignored by many window managers (because users really don't like when windows
2722 // drop themselves out of maximization) and has a wrong QWidget::geometry() idea from
2723 // the wrong assumption the request would have been hononred.
2724 // So we just "fix" the internal geometry immediately afterwards to prevent
2725 // mislayouting
2726 // There's atm. no flicker due to this (and because Qt compresses events)
2727 // In case it ever occurs, we can frame this in setUpdatesEnabled(false/true)
2728 QRect oldGeometry = MainWindow::geometry();
2729 restoreGeometry(item);
2730 if (windowState() & Qt::WindowMaximized)
2731 setGeometry(oldGeometry);
2732 } else {
2733 restoreGeometry(item);
2734 if (windowState() & Qt::WindowMaximized) {
2735 // ensure to try setting the proper geometry and have the WM constrain us
2736 setGeometry(QApplication::desktop()->availableGeometry());
2741 if (size-- && !stream.atEnd()) {
2742 stream >> item;
2743 restoreState(item);
2746 if (size-- && !stream.atEnd()) {
2747 stream >> item;
2748 if (m_mainVSplitter) {
2749 m_mainVSplitter->restoreState(item);
2753 if (size-- && !stream.atEnd()) {
2754 stream >> item;
2755 if (m_mainHSplitter) {
2756 m_mainHSplitter->restoreState(item);
2760 if (size-- && !stream.atEnd()) {
2761 stream >> item;
2762 msgListWidget->tree->header()->restoreState(item);
2763 // got to manually update the state of the actions which control the visibility state
2764 msgListWidget->tree->updateActionsAfterRestoredState();
2767 connect(msgListWidget->tree->header(), &QHeaderView::sectionCountChanged, msgListWidget->tree, &MsgListView::slotHandleNewColumns);
2769 if (size-- && !stream.atEnd()) {
2770 stream >> item;
2771 bool ok;
2772 int columns = item.toInt(&ok);
2773 if (ok) {
2774 msgListWidget->tree->header()->setStretchLastSection(false);
2775 for (int i = 0; i < columns && size-- && !stream.atEnd(); ++i) {
2776 stream >> item;
2777 int sectionSize = item.toInt();
2778 QHeaderView::ResizeMode resizeMode = msgListWidget->tree->resizeModeForColumn(i);
2779 if (sectionSize > 0 && resizeMode == QHeaderView::Interactive) {
2780 // fun fact: user cannot resize by mouse when size <= 0
2781 msgListWidget->tree->setColumnWidth(i, sectionSize);
2782 } else {
2783 msgListWidget->tree->setColumnWidth(i, msgListWidget->tree->sizeHintForColumn(i));
2785 msgListWidget->tree->header()->setSectionResizeMode(i, resizeMode);
2790 if (size-- && !stream.atEnd()) {
2791 stream >> item;
2792 bool ok;
2793 bool visibility = item.toInt(&ok);
2794 if (ok) {
2795 menuBar()->setVisible(visibility);
2796 showMenuBar->setChecked(visibility);
2800 m_skipSavingOfUI = skipSaving;
2803 void MainWindow::resizeEvent(QResizeEvent *)
2805 m_delayedStateSaving->start();
2808 /** @short Make sure that the message gets loaded after the splitters have changed their position */
2809 void MainWindow::possiblyLoadMessageOnSplittersChanged()
2811 if (m_messageWidget->isVisible() && !m_messageWidget->size().isEmpty()) {
2812 // We do not have to check whether it's a different message; the setMessage() will do this or us
2813 // and there are multiple proxy models involved anyway
2814 QModelIndex index = msgListWidget->tree->currentIndex();
2815 if (index.isValid()) {
2816 // OTOH, setting an invalid QModelIndex would happily assert-fail
2817 m_messageWidget->messageView->setMessage(msgListWidget->tree->currentIndex());
2822 Imap::ImapAccess *MainWindow::imapAccess() const
2824 return m_imapAccess;
2827 void MainWindow::enableLoggingToDisk()
2829 imapLogger->slotSetPersistentLogging(true);
2832 void MainWindow::slotPluginsChanged()
2834 Plugins::AddressbookPlugin *addressbook = pluginManager()->addressbook();
2835 if (!addressbook || !(addressbook->features() & Plugins::AddressbookPlugin::FeatureAddressbookWindow))
2836 m_actionContactEditor->setEnabled(false);
2837 else
2838 m_actionContactEditor->setEnabled(true);
2841 /** @short Update the default action to make sure that we show a correct status of the network connection */
2842 void MainWindow::updateNetworkIndication()
2844 if (QAction *action = qobject_cast<QAction*>(sender())) {
2845 if (action->isChecked()) {
2846 m_netToolbarDefaultAction->setIcon(action->icon());
2851 void MainWindow::showStatusMessage(const QString &message)
2853 networkIndicator->setToolTip(message);
2854 if (isActiveWindow())
2855 QToolTip::showText(networkIndicator->mapToGlobal(QPoint(0, 0)), message);
2858 void MainWindow::slotMessageModelChanged(QAbstractItemModel *model)
2860 mailMimeTree->setModel(model);
2863 void MainWindow::slotFavoriteTagsChanged()
2865 for (int i = 1; i <= m_favoriteTags->rowCount(); ++i) {
2866 QAction *action = ShortcutHandler::instance()->action(QStringLiteral("action_tag_") + QString::number(i));
2867 if (action)
2868 action->setText(tr("Tag with \"%1\"").arg(m_favoriteTags->tagNameByIndex(i - 1)));