Remember window geometry of standalone message widgets
[trojita.git] / src / Gui / Window.cpp
blob23552232e744d4590a331a6ee822e637137c9998
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/Utils.h"
72 #include "Imap/Tasks/ImapTask.h"
73 #include "Imap/Network/FileDownloadManager.h"
74 #include "MSA/ImapSubmit.h"
75 #include "MSA/Sendmail.h"
76 #include "MSA/SMTP.h"
77 #include "Plugins/AddressbookPlugin.h"
78 #include "Plugins/PasswordPlugin.h"
79 #include "Plugins/PluginManager.h"
80 #include "CompleteMessageWidget.h"
81 #include "ComposeWidget.h"
82 #include "MailBoxTreeView.h"
83 #include "MessageListWidget.h"
84 #include "MessageView.h"
85 #include "MessageSourceWidget.h"
86 #include "Gui/MessageHeadersWidget.h"
87 #include "MsgListView.h"
88 #include "OnePanelAtTimeWidget.h"
89 #include "PasswordDialog.h"
90 #include "ProtocolLoggerWidget.h"
91 #include "SettingsDialog.h"
92 #include "SimplePartWidget.h"
93 #include "Streams/SocketFactory.h"
94 #include "TaskProgressIndicator.h"
95 #include "Util.h"
96 #include "Window.h"
97 #include "ShortcutHandler/ShortcutHandler.h"
99 #include "ui_CreateMailboxDialog.h"
100 #include "ui_AboutDialog.h"
102 #include "Imap/Model/ModelTest/modeltest.h"
103 #include "UiUtils/IconLoader.h"
104 #include "UiUtils/QaimDfsIterator.h"
106 /** @short All user-facing widgets and related classes */
107 namespace Gui
110 static const char * const netErrorUnseen = "net_error_unseen";
112 MainWindow::MainWindow(QSettings *settings): QMainWindow(), m_imapAccess(0), m_mainHSplitter(0), m_mainVSplitter(0),
113 m_mainStack(0), m_layoutMode(LAYOUT_COMPACT), m_skipSavingOfUI(true), m_delayedStateSaving(0), m_actionSortNone(0),
114 m_ignoreStoredPassword(false), m_settings(settings), m_pluginManager(0), m_networkErrorMessageBox(0), m_trayIcon(0)
116 setAttribute(Qt::WA_AlwaysShowToolTips);
117 // m_pluginManager must be created before calling createWidgets
118 m_pluginManager = new Plugins::PluginManager(this, m_settings,
119 Common::SettingsNames::addressbookPlugin, Common::SettingsNames::passwordPlugin);
120 connect(m_pluginManager, &Plugins::PluginManager::pluginsChanged, this, &MainWindow::slotPluginsChanged);
121 connect(m_pluginManager, &Plugins::PluginManager::pluginError, this, [this](const QString &errorMessage) {
122 Gui::Util::messageBoxWarning(this, tr("Plugin Error"),
123 //: The %1 placeholder is a full error message as provided by Qt, ready for human consumption.
124 trUtf8("A plugin failed to load, therefore some functionality might be lost. "
125 "You might want to update your system or report a bug to your vendor."
126 "\n\n%1").arg(errorMessage));
128 #ifdef TROJITA_HAVE_CRYPTO_MESSAGES
129 Plugins::PluginManager::MimePartReplacers replacers;
130 #ifdef TROJITA_HAVE_GPGMEPP
131 replacers.emplace_back(std::make_shared<Cryptography::GpgMeReplacer>());
132 #endif
133 m_pluginManager->setMimePartReplacers(replacers);
134 #endif
136 // ImapAccess contains a wrapper for retrieving passwords through some plugin.
137 // That PasswordWatcher is used by the SettingsDialog's widgets *and* by this class,
138 // which means that ImapAccess has to be constructed before we go and open the settings dialog.
140 // FIXME: use another account-id at some point in future
141 // we are now using the profile to avoid overwriting passwords of
142 // other profiles in secure storage
143 QString profileName = QString::fromUtf8(qgetenv("TROJITA_PROFILE"));
144 m_imapAccess = new Imap::ImapAccess(this, m_settings, m_pluginManager, profileName);
145 connect(m_imapAccess, &Imap::ImapAccess::cacheError, this, &MainWindow::cacheError);
146 connect(m_imapAccess, &Imap::ImapAccess::checkSslPolicy, this, &MainWindow::checkSslPolicy, Qt::QueuedConnection);
148 ShortcutHandler *shortcutHandler = new ShortcutHandler(this);
149 shortcutHandler->setSettingsObject(m_settings);
150 defineActions();
151 shortcutHandler->readSettings(); // must happen after defineActions()
153 createWidgets();
155 Imap::migrateSettings(m_settings);
157 m_senderIdentities = new Composer::SenderIdentitiesModel(this);
158 m_senderIdentities->loadFromSettings(*m_settings);
160 if (! m_settings->contains(Common::SettingsNames::imapMethodKey)) {
161 QTimer::singleShot(0, this, SLOT(slotShowSettings()));
165 setupModels();
166 createActions();
167 createMenus();
168 slotToggleSysTray();
169 slotPluginsChanged();
171 // Please note that Qt 4.6.1 really requires passing the method signature this way, *not* using the SLOT() macro
172 QDesktopServices::setUrlHandler(QStringLiteral("mailto"), this, "slotComposeMailUrl");
173 QDesktopServices::setUrlHandler(QStringLiteral("x-trojita-manage-contact"), this, "slotManageContact");
175 slotUpdateWindowTitle();
177 recoverDrafts();
179 if (m_actionLayoutWide->isEnabled() &&
180 m_settings->value(Common::SettingsNames::guiMainWindowLayout) == Common::SettingsNames::guiMainWindowLayoutWide) {
181 m_actionLayoutWide->trigger();
182 } else if (m_settings->value(Common::SettingsNames::guiMainWindowLayout) == Common::SettingsNames::guiMainWindowLayoutOneAtTime) {
183 m_actionLayoutOneAtTime->trigger();
184 } else {
185 m_actionLayoutCompact->trigger();
188 connect(qApp, &QGuiApplication::applicationStateChanged, this,
189 [&](Qt::ApplicationState state) {
190 if (state == Qt::ApplicationActive && m_networkErrorMessageBox && m_networkErrorMessageBox->property(netErrorUnseen).toBool()) {
191 m_networkErrorMessageBox->setProperty(netErrorUnseen, false);
192 m_networkErrorMessageBox->show();
196 // Don't listen to QDesktopWidget::resized; that is emitted too early (when it gets fired, the screen size has changed, but
197 // the workspace area is still the old one). Instead, listen to workAreaResized which gets emitted at an appropriate time.
198 // The delay is still there to guarantee some smoothing; on jkt's box there are typically three events in a rapid sequence
199 // (some of them most likely due to the fact that at first, the actual desktop gets resized, the plasma panel reacts
200 // to that and only after the panel gets resized, the available size of "the rest" is correct again).
201 // Which is why it makes sense to introduce some delay in there. The 0.5s delay is my best guess and "should work" (especially
202 // because every change bumps the timer anyway, as Thomas pointed out).
203 QTimer *delayedResize = new QTimer(this);
204 delayedResize->setSingleShot(true);
205 delayedResize->setInterval(500);
206 connect(delayedResize, &QTimer::timeout, this, &MainWindow::desktopGeometryChanged);
207 connect(qApp->desktop(), &QDesktopWidget::workAreaResized, delayedResize, static_cast<void (QTimer::*)()>(&QTimer::start));
208 m_skipSavingOfUI = false;
211 void MainWindow::defineActions()
213 ShortcutHandler *shortcutHandler = ShortcutHandler::instance();
214 shortcutHandler->defineAction(QStringLiteral("action_application_exit"), QStringLiteral("application-exit"), tr("E&xit"), QKeySequence::Quit);
215 shortcutHandler->defineAction(QStringLiteral("action_compose_mail"), QStringLiteral("document-edit"), tr("&New Message..."), QKeySequence::New);
216 shortcutHandler->defineAction(QStringLiteral("action_compose_draft"), QStringLiteral("document-open-recent"), tr("&Edit Draft..."));
217 shortcutHandler->defineAction(QStringLiteral("action_show_menubar"), QStringLiteral("view-list-text"), tr("Show Main Menu &Bar"), tr("Ctrl+M"));
218 shortcutHandler->defineAction(QStringLiteral("action_expunge"), QStringLiteral("trash-empty"), tr("Exp&unge"), tr("Ctrl+E"));
219 shortcutHandler->defineAction(QStringLiteral("action_mark_as_read"), QStringLiteral("mail-mark-read"), tr("Mark as &Read"), QStringLiteral("M"));
220 shortcutHandler->defineAction(QStringLiteral("action_go_to_next_unread"), QStringLiteral("arrow-right"), tr("&Next Unread Message"), QStringLiteral("N"));
221 shortcutHandler->defineAction(QStringLiteral("action_go_to_previous_unread"), QStringLiteral("arrow-left"), tr("&Previous Unread Message"), QStringLiteral("P"));
222 shortcutHandler->defineAction(QStringLiteral("action_mark_as_deleted"), QStringLiteral("list-remove"), tr("Mark as &Deleted"), QKeySequence(Qt::Key_Delete).toString());
223 shortcutHandler->defineAction(QStringLiteral("action_mark_as_flagged"), QStringLiteral("mail-flagged"), tr("Mark as &Flagged"), QStringLiteral("S"));
224 shortcutHandler->defineAction(QStringLiteral("action_mark_as_junk"), QStringLiteral("mail-mark-junk"), tr("Mark as &Junk"), QStringLiteral("J"));
225 shortcutHandler->defineAction(QStringLiteral("action_mark_as_notjunk"), QStringLiteral("mail-mark-notjunk"), tr("Mark as Not &junk"), QStringLiteral("Shift+J"));
226 shortcutHandler->defineAction(QStringLiteral("action_save_message_as"), QStringLiteral("document-save"), tr("&Save Message..."));
227 shortcutHandler->defineAction(QStringLiteral("action_view_message_source"), QString(), tr("View Message &Source..."));
228 shortcutHandler->defineAction(QStringLiteral("action_view_message_headers"), QString(), tr("View Message &Headers..."), tr("Ctrl+U"));
229 shortcutHandler->defineAction(QStringLiteral("action_reply_private"), QStringLiteral("mail-reply-sender"), tr("&Private Reply"), tr("Ctrl+Shift+A"));
230 shortcutHandler->defineAction(QStringLiteral("action_reply_all_but_me"), QStringLiteral("mail-reply-all"), tr("Reply to All &but Me"), tr("Ctrl+Shift+R"));
231 shortcutHandler->defineAction(QStringLiteral("action_reply_all"), QStringLiteral("mail-reply-all"), tr("Reply to &All"), tr("Ctrl+Alt+Shift+R"));
232 shortcutHandler->defineAction(QStringLiteral("action_reply_list"), QStringLiteral("mail-reply-list"), tr("Reply to &Mailing List"), tr("Ctrl+L"));
233 shortcutHandler->defineAction(QStringLiteral("action_reply_guess"), QString(), tr("Reply by &Guess"), tr("Ctrl+R"));
234 shortcutHandler->defineAction(QStringLiteral("action_forward_attachment"), QStringLiteral("mail-forward"), tr("&Forward"), tr("Ctrl+Shift+F"));
235 shortcutHandler->defineAction(QStringLiteral("action_archive"), QStringLiteral("mail-move-to-archive"), tr("&Archive"), QStringLiteral("A"));
236 shortcutHandler->defineAction(QStringLiteral("action_contact_editor"), QStringLiteral("contact-unknown"), tr("Address Book..."));
237 shortcutHandler->defineAction(QStringLiteral("action_network_offline"), QStringLiteral("network-disconnect"), tr("&Offline"));
238 shortcutHandler->defineAction(QStringLiteral("action_network_expensive"), QStringLiteral("network-wireless"), tr("&Expensive Connection"));
239 shortcutHandler->defineAction(QStringLiteral("action_network_online"), QStringLiteral("network-connect"), tr("&Free Access"));
240 shortcutHandler->defineAction(QStringLiteral("action_messagewindow_close"), QStringLiteral("window-close"), tr("Close Standalone Message Window"));
241 shortcutHandler->defineAction(QStringLiteral("action_oneattime_go_back"), QStringLiteral("go-previous"), tr("Navigate Back"), QKeySequence(QKeySequence::Back).toString());
242 shortcutHandler->defineAction(QStringLiteral("action_zoom_in"), QStringLiteral("zoom-in"), tr("Zoom In"), QKeySequence::ZoomIn);
243 shortcutHandler->defineAction(QStringLiteral("action_zoom_out"), QStringLiteral("zoom-out"), tr("Zoom Out"), QKeySequence::ZoomOut);
244 shortcutHandler->defineAction(QStringLiteral("action_zoom_original"), QStringLiteral("zoom-original"), tr("Original Size"));
247 void MainWindow::createActions()
249 // The shortcuts are a little bit complicated, unfortunately. This is what the other applications use by default:
251 // Thunderbird:
252 // private: Ctrl+R
253 // all: Ctrl+Shift+R
254 // list: Ctrl+Shift+L
255 // forward: Ctrl+L
256 // (no shortcuts for type of forwarding)
257 // bounce: ctrl+B
258 // new message: Ctrl+N
260 // KMail:
261 // "reply": R
262 // private: Shift+A
263 // all: A
264 // list: L
265 // forward as attachment: F
266 // forward inline: Shift+F
267 // bounce: E
268 // new: Ctrl+N
270 m_actionContactEditor = ShortcutHandler::instance()->createAction(QStringLiteral("action_contact_editor"), this, SLOT(invokeContactEditor()), this);
272 m_mainToolbar = addToolBar(tr("Navigation"));
273 m_mainToolbar->setObjectName(QStringLiteral("mainToolbar"));
275 reloadMboxList = new QAction(style()->standardIcon(QStyle::SP_ArrowRight), tr("&Update List of Child Mailboxes"), this);
276 connect(reloadMboxList, &QAction::triggered, this, &MainWindow::slotReloadMboxList);
278 resyncMbox = new QAction(UiUtils::loadIcon(QStringLiteral("view-refresh")), tr("Check for &New Messages"), this);
279 connect(resyncMbox, &QAction::triggered, this, &MainWindow::slotResyncMbox);
281 reloadAllMailboxes = new QAction(tr("&Reload Everything"), this);
282 // connect later
284 exitAction = ShortcutHandler::instance()->createAction(QStringLiteral("action_application_exit"), qApp, SLOT(quit()), this);
285 exitAction->setStatusTip(tr("Exit the application"));
287 netOffline = ShortcutHandler::instance()->createAction(QStringLiteral("action_network_offline"));
288 netOffline->setCheckable(true);
289 // connect later
290 netExpensive = ShortcutHandler::instance()->createAction(QStringLiteral("action_network_expensive"));
291 netExpensive->setCheckable(true);
292 // connect later
293 netOnline = ShortcutHandler::instance()->createAction(QStringLiteral("action_network_online"));
294 netOnline->setCheckable(true);
295 // connect later
297 QActionGroup *netPolicyGroup = new QActionGroup(this);
298 netPolicyGroup->setExclusive(true);
299 netPolicyGroup->addAction(netOffline);
300 netPolicyGroup->addAction(netExpensive);
301 netPolicyGroup->addAction(netOnline);
303 //: a debugging tool showing the full contents of the whole IMAP server; all folders, messages and their parts
304 showFullView = new QAction(UiUtils::loadIcon(QStringLiteral("edit-find-mail")), tr("Show Full &Tree Window"), this);
305 showFullView->setCheckable(true);
306 connect(showFullView, &QAction::triggered, allDock, &QWidget::setVisible);
307 connect(allDock, &QDockWidget::visibilityChanged, showFullView, &QAction::setChecked);
309 //: list of active "tasks", entities which are performing certain action like downloading a message or syncing a mailbox
310 showTaskView = new QAction(tr("Show ImapTask t&ree"), this);
311 showTaskView->setCheckable(true);
312 connect(showTaskView, &QAction::triggered, taskDock, &QWidget::setVisible);
313 connect(taskDock, &QDockWidget::visibilityChanged, showTaskView, &QAction::setChecked);
315 //: a debugging tool showing the mime tree of the current message
316 showMimeView = new QAction(tr("Show &MIME tree"), this);
317 showMimeView->setCheckable(true);
318 connect(showMimeView, &QAction::triggered, mailMimeDock, &QWidget::setVisible);
319 connect(mailMimeDock, &QDockWidget::visibilityChanged, showMimeView, &QAction::setChecked);
321 showImapLogger = new QAction(tr("Show IMAP protocol &log"), this);
322 showImapLogger->setCheckable(true);
323 connect(showImapLogger, &QAction::toggled, imapLoggerDock, &QWidget::setVisible);
324 connect(imapLoggerDock, &QDockWidget::visibilityChanged, showImapLogger, &QAction::setChecked);
326 //: file to save the debug log into
327 logPersistent = new QAction(tr("Log &into %1").arg(Imap::Mailbox::persistentLogFileName()), this);
328 logPersistent->setCheckable(true);
329 connect(logPersistent, &QAction::triggered, imapLogger, &ProtocolLoggerWidget::slotSetPersistentLogging);
330 connect(imapLogger, &ProtocolLoggerWidget::persistentLoggingChanged, logPersistent, &QAction::setChecked);
332 showImapCapabilities = new QAction(tr("IMAP Server In&formation..."), this);
333 connect(showImapCapabilities, &QAction::triggered, this, &MainWindow::slotShowImapInfo);
335 showMenuBar = ShortcutHandler::instance()->createAction(QStringLiteral("action_show_menubar"), this);
336 showMenuBar->setCheckable(true);
337 showMenuBar->setChecked(true);
338 connect(showMenuBar, &QAction::triggered, menuBar(), &QMenuBar::setVisible);
339 connect(showMenuBar, &QAction::triggered, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
341 showToolBar = new QAction(tr("Show &Toolbar"), this);
342 showToolBar->setCheckable(true);
343 connect(showToolBar, &QAction::triggered, m_mainToolbar, &QWidget::setVisible);
344 connect(m_mainToolbar, &QToolBar::visibilityChanged, showToolBar, &QAction::setChecked);
345 connect(m_mainToolbar, &QToolBar::visibilityChanged, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
347 configSettings = new QAction(UiUtils::loadIcon(QStringLiteral("configure")), tr("&Settings..."), this);
348 connect(configSettings, &QAction::triggered, this, &MainWindow::slotShowSettings);
350 QAction *triggerSearch = new QAction(this);
351 addAction(triggerSearch);
352 triggerSearch->setShortcut(QKeySequence(QStringLiteral(":, =")));
353 connect(triggerSearch, &QAction::triggered, msgListWidget, &MessageListWidget::focusRawSearch);
355 triggerSearch = new QAction(this);
356 addAction(triggerSearch);
357 triggerSearch->setShortcut(QKeySequence(QStringLiteral("/")));
358 connect(triggerSearch, &QAction::triggered, msgListWidget, &MessageListWidget::focusSearch);
360 m_oneAtTimeGoBack = ShortcutHandler::instance()->createAction(QStringLiteral("action_oneattime_go_back"), this);
361 m_oneAtTimeGoBack->setEnabled(false);
363 composeMail = ShortcutHandler::instance()->createAction(QStringLiteral("action_compose_mail"), this, SLOT(slotComposeMail()), this);
364 m_editDraft = ShortcutHandler::instance()->createAction(QStringLiteral("action_compose_draft"), this, SLOT(slotEditDraft()), this);
366 expunge = ShortcutHandler::instance()->createAction(QStringLiteral("action_expunge"), this, SLOT(slotExpunge()), this);
368 m_forwardAsAttachment = ShortcutHandler::instance()->createAction(QStringLiteral("action_forward_attachment"), this, SLOT(slotForwardAsAttachment()), this);
369 markAsRead = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_read"), this);
370 markAsRead->setCheckable(true);
371 msgListWidget->tree->addAction(markAsRead);
372 connect(markAsRead, &QAction::triggered, this, &MainWindow::handleMarkAsRead);
374 m_nextMessage = ShortcutHandler::instance()->createAction(QStringLiteral("action_go_to_next_unread"), this, SLOT(slotNextUnread()), this);
375 msgListWidget->tree->addAction(m_nextMessage);
376 m_messageWidget->messageView->addAction(m_nextMessage);
378 m_previousMessage = ShortcutHandler::instance()->createAction(QStringLiteral("action_go_to_previous_unread"), this, SLOT(slotPreviousUnread()), this);
379 msgListWidget->tree->addAction(m_previousMessage);
380 m_messageWidget->messageView->addAction(m_previousMessage);
382 markAsDeleted = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_deleted"), this);
383 markAsDeleted->setCheckable(true);
384 msgListWidget->tree->addAction(markAsDeleted);
385 connect(markAsDeleted, &QAction::triggered, this, &MainWindow::handleMarkAsDeleted);
387 markAsFlagged = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_flagged"), this);
388 markAsFlagged->setCheckable(true);
389 connect(markAsFlagged, &QAction::triggered, this, &MainWindow::handleMarkAsFlagged);
391 markAsJunk = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_junk"), this);
392 markAsJunk->setCheckable(true);
393 connect(markAsJunk, &QAction::triggered, this, &MainWindow::handleMarkAsJunk);
395 markAsNotJunk = ShortcutHandler::instance()->createAction(QStringLiteral("action_mark_as_notjunk"), this);
396 markAsNotJunk->setCheckable(true);
397 connect(markAsNotJunk, &QAction::triggered, this, &MainWindow::handleMarkAsNotJunk);
399 saveWholeMessage = ShortcutHandler::instance()->createAction(QStringLiteral("action_save_message_as"), this, SLOT(slotSaveCurrentMessageBody()), this);
400 msgListWidget->tree->addAction(saveWholeMessage);
402 viewMsgSource = ShortcutHandler::instance()->createAction(QStringLiteral("action_view_message_source"), this, SLOT(slotViewMsgSource()), this);
403 msgListWidget->tree->addAction(viewMsgSource);
405 viewMsgHeaders = ShortcutHandler::instance()->createAction(QStringLiteral("action_view_message_headers"), this, SLOT(slotViewMsgHeaders()), this);
406 msgListWidget->tree->addAction(viewMsgHeaders);
408 moveToArchive = ShortcutHandler::instance()->createAction(QStringLiteral("action_archive"), this);
409 connect(moveToArchive, &QAction::triggered, this, &MainWindow::handleMoveToArchive);
411 //: "mailbox" as a "folder of messages", not as a "mail account"
412 createChildMailbox = new QAction(tr("Create &Child Mailbox..."), this);
413 connect(createChildMailbox, &QAction::triggered, this, &MainWindow::slotCreateMailboxBelowCurrent);
415 //: "mailbox" as a "folder of messages", not as a "mail account"
416 createTopMailbox = new QAction(tr("Create &New Mailbox..."), this);
417 connect(createTopMailbox, &QAction::triggered, this, &MainWindow::slotCreateTopMailbox);
419 m_actionMarkMailboxAsRead = new QAction(tr("&Mark Mailbox as Read"), this);
420 connect(m_actionMarkMailboxAsRead, &QAction::triggered, this, &MainWindow::slotMarkCurrentMailboxRead);
422 //: "mailbox" as a "folder of messages", not as a "mail account"
423 deleteCurrentMailbox = new QAction(tr("&Remove Mailbox"), this);
424 connect(deleteCurrentMailbox, &QAction::triggered, this, &MainWindow::slotDeleteCurrentMailbox);
426 #ifdef XTUPLE_CONNECT
427 xtIncludeMailboxInSync = new QAction(tr("&Synchronize with xTuple"), this);
428 xtIncludeMailboxInSync->setCheckable(true);
429 connect(xtIncludeMailboxInSync, SIGNAL(triggered()), this, SLOT(slotXtSyncCurrentMailbox()));
430 #endif
432 m_replyPrivate = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_private"), this, SLOT(slotReplyTo()), this);
433 m_replyPrivate->setEnabled(false);
435 m_replyAllButMe = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_all_but_me"), this, SLOT(slotReplyAllButMe()), this);
436 m_replyAllButMe->setEnabled(false);
438 m_replyAll = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_all"), this, SLOT(slotReplyAll()), this);
439 m_replyAll->setEnabled(false);
441 m_replyList = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_list"), this, SLOT(slotReplyList()), this);
442 m_replyList->setEnabled(false);
444 m_replyGuess = ShortcutHandler::instance()->createAction(QStringLiteral("action_reply_guess"), this, SLOT(slotReplyGuess()), this);
445 m_replyGuess->setEnabled(true);
447 actionThreadMsgList = new QAction(UiUtils::loadIcon(QStringLiteral("format-justify-right")), tr("Show Messages in &Threads"), this);
448 actionThreadMsgList->setCheckable(true);
449 // This action is enabled/disabled by model's capabilities
450 actionThreadMsgList->setEnabled(false);
451 if (m_settings->value(Common::SettingsNames::guiMsgListShowThreading).toBool()) {
452 actionThreadMsgList->setChecked(true);
453 // The actual threading will be performed only when model updates its capabilities
455 connect(actionThreadMsgList, &QAction::triggered, this, &MainWindow::slotThreadMsgList);
457 QActionGroup *sortOrderGroup = new QActionGroup(this);
458 m_actionSortAscending = new QAction(tr("&Ascending"), sortOrderGroup);
459 m_actionSortAscending->setCheckable(true);
460 m_actionSortAscending->setChecked(true);
461 m_actionSortDescending = new QAction(tr("&Descending"), sortOrderGroup);
462 m_actionSortDescending->setCheckable(true);
463 // QActionGroup has no toggle signal, but connecting descending will implicitly catch the acscending complement ;-)
464 connect(m_actionSortDescending, &QAction::toggled, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
465 connect(m_actionSortDescending, &QAction::toggled, this, &MainWindow::slotScrollToCurrent);
466 connect(sortOrderGroup, &QActionGroup::triggered, this, &MainWindow::slotSortingPreferenceChanged);
468 QActionGroup *sortColumnGroup = new QActionGroup(this);
469 m_actionSortNone = new QAction(tr("&No sorting"), sortColumnGroup);
470 m_actionSortNone->setCheckable(true);
471 m_actionSortThreading = new QAction(tr("Sorted by &Threading"), sortColumnGroup);
472 m_actionSortThreading->setCheckable(true);
473 m_actionSortByArrival = new QAction(tr("A&rrival"), sortColumnGroup);
474 m_actionSortByArrival->setCheckable(true);
475 m_actionSortByCc = new QAction(tr("&Cc (Carbon Copy)"), sortColumnGroup);
476 m_actionSortByCc->setCheckable(true);
477 m_actionSortByDate = new QAction(tr("Date from &Message Headers"), sortColumnGroup);
478 m_actionSortByDate->setCheckable(true);
479 m_actionSortByFrom = new QAction(tr("&From Address"), sortColumnGroup);
480 m_actionSortByFrom->setCheckable(true);
481 m_actionSortBySize = new QAction(tr("&Size"), sortColumnGroup);
482 m_actionSortBySize->setCheckable(true);
483 m_actionSortBySubject = new QAction(tr("S&ubject"), sortColumnGroup);
484 m_actionSortBySubject->setCheckable(true);
485 m_actionSortByTo = new QAction(tr("T&o Address"), sortColumnGroup);
486 m_actionSortByTo->setCheckable(true);
487 connect(sortColumnGroup, &QActionGroup::triggered, this, &MainWindow::slotSortingPreferenceChanged);
488 slotSortingConfirmed(-1, Qt::AscendingOrder);
490 actionHideRead = new QAction(tr("&Hide Read Messages"), this);
491 actionHideRead->setCheckable(true);
492 if (m_settings->value(Common::SettingsNames::guiMsgListHideRead).toBool()) {
493 actionHideRead->setChecked(true);
494 prettyMsgListModel->setHideRead(true);
496 connect(actionHideRead, &QAction::triggered, this, &MainWindow::slotHideRead);
498 QActionGroup *layoutGroup = new QActionGroup(this);
499 m_actionLayoutCompact = new QAction(tr("&Compact"), layoutGroup);
500 m_actionLayoutCompact->setCheckable(true);
501 m_actionLayoutCompact->setChecked(true);
502 connect(m_actionLayoutCompact, &QAction::triggered, this, &MainWindow::slotLayoutCompact);
503 m_actionLayoutWide = new QAction(tr("&Wide"), layoutGroup);
504 m_actionLayoutWide->setCheckable(true);
505 connect(m_actionLayoutWide, &QAction::triggered, this, &MainWindow::slotLayoutWide);
506 m_actionLayoutOneAtTime = new QAction(tr("&One At Time"), layoutGroup);
507 m_actionLayoutOneAtTime->setCheckable(true);
508 connect(m_actionLayoutOneAtTime, &QAction::triggered, this, &MainWindow::slotLayoutOneAtTime);
511 m_actionShowOnlySubscribed = new QAction(tr("Show Only S&ubscribed Folders"), this);
512 m_actionShowOnlySubscribed->setCheckable(true);
513 m_actionShowOnlySubscribed->setEnabled(false);
514 connect(m_actionShowOnlySubscribed, &QAction::toggled, this, &MainWindow::slotShowOnlySubscribed);
515 m_actionSubscribeMailbox = new QAction(tr("Su&bscribed"), this);
516 m_actionSubscribeMailbox->setCheckable(true);
517 m_actionSubscribeMailbox->setEnabled(false);
518 connect(m_actionSubscribeMailbox, &QAction::triggered, this, &MainWindow::slotSubscribeCurrentMailbox);
520 aboutTrojita = new QAction(trUtf8("&About Trojitá..."), this);
521 connect(aboutTrojita, &QAction::triggered, this, &MainWindow::slotShowAboutTrojita);
523 donateToTrojita = new QAction(tr("&Donate to the project"), this);
524 connect(donateToTrojita, &QAction::triggered, this, &MainWindow::slotDonateToTrojita);
526 connectModelActions();
528 m_composeMenu = new QMenu(tr("Compose Mail"), this);
529 m_composeMenu->addAction(composeMail);
530 m_composeMenu->addAction(m_editDraft);
531 m_composeButton = new QToolButton(this);
532 m_composeButton->setPopupMode(QToolButton::MenuButtonPopup);
533 m_composeButton->setMenu(m_composeMenu);
534 m_composeButton->setDefaultAction(composeMail);
536 m_replyButton = new QToolButton(this);
537 m_replyButton->setPopupMode(QToolButton::MenuButtonPopup);
538 m_replyMenu = new QMenu(m_replyButton);
539 m_replyMenu->addAction(m_replyPrivate);
540 m_replyMenu->addAction(m_replyAllButMe);
541 m_replyMenu->addAction(m_replyAll);
542 m_replyMenu->addAction(m_replyList);
543 m_replyButton->setMenu(m_replyMenu);
544 m_replyButton->setDefaultAction(m_replyPrivate);
546 m_mainToolbar->addWidget(m_composeButton);
547 m_mainToolbar->addWidget(m_replyButton);
548 m_mainToolbar->addAction(m_forwardAsAttachment);
549 m_mainToolbar->addAction(expunge);
550 m_mainToolbar->addSeparator();
551 m_mainToolbar->addAction(markAsRead);
552 m_mainToolbar->addAction(markAsDeleted);
553 m_mainToolbar->addAction(markAsFlagged);
554 m_mainToolbar->addAction(markAsJunk);
555 m_mainToolbar->addAction(markAsNotJunk);
556 m_mainToolbar->addAction(moveToArchive);
558 // Push the status indicators all the way to the other side of the toolbar -- either to the far right, or far bottom.
559 QWidget *toolbarSpacer = new QWidget(m_mainToolbar);
560 toolbarSpacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
561 m_mainToolbar->addWidget(toolbarSpacer);
563 m_mainToolbar->addSeparator();
564 m_mainToolbar->addWidget(busyParsersIndicator);
566 networkIndicator = new QToolButton(this);
567 // This is deliberate; we want to show this button in the same style as the other ones in the toolbar
568 networkIndicator->setPopupMode(QToolButton::MenuButtonPopup);
569 m_mainToolbar->addWidget(networkIndicator);
571 m_menuFromToolBar = new QToolButton(this);
572 m_menuFromToolBar->setIcon(UiUtils::loadIcon(QStringLiteral("menu_new")));
573 m_menuFromToolBar->setText(QChar(0x205d)); // Unicode 'TRICOLON'
574 m_menuFromToolBar->setPopupMode(QToolButton::MenuButtonPopup);
575 connect(m_menuFromToolBar, &QAbstractButton::clicked, m_menuFromToolBar, &QToolButton::showMenu);
576 m_mainToolbar->addWidget(m_menuFromToolBar);
577 connect(showMenuBar, &QAction::toggled, [this](const bool menuBarVisible) {
578 // https://bugreports.qt.io/browse/QTBUG-35768 , we have to work on the QAction, not QToolButton
579 m_mainToolbar->actions().last()->setVisible(!menuBarVisible);
581 m_mainToolbar->actions().last()->setVisible(false); // initial state to complement the default of the QMenuBar's visibility
583 busyParsersIndicator->setFixedSize(m_mainToolbar->iconSize());
586 // Custom widgets which are added into a QToolBar are by default aligned to the left, while QActions are justified.
587 // That sucks, because some of our widgets use multiple actions with an expanding arrow at right.
588 // Make sure everything is aligned to the left, so that the actual buttons are aligned properly and the extra arrows
589 // are, well, at right.
590 // I have no idea how this works on RTL layouts.
591 QLayout *lay = m_mainToolbar->layout();
592 for (int i = 0; i < lay->count(); ++i) {
593 QLayoutItem *it = lay->itemAt(i);
594 if (it->widget() == toolbarSpacer) {
595 // Don't align this one, otherwise it won't push stuff when in horizontal direction
596 continue;
598 if (it->widget() == busyParsersIndicator) {
599 // It looks much better when centered
600 it->setAlignment(Qt::AlignJustify);
601 continue;
603 it->setAlignment(Qt::AlignLeft);
607 updateMessageFlags();
610 void MainWindow::connectModelActions()
612 connect(reloadAllMailboxes, &QAction::triggered, imapModel(), &Imap::Mailbox::Model::reloadMailboxList);
613 connect(netOffline, &QAction::triggered,
614 qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()), &Imap::Mailbox::NetworkWatcher::setNetworkOffline);
615 connect(netExpensive, &QAction::triggered,
616 qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()), &Imap::Mailbox::NetworkWatcher::setNetworkExpensive);
617 connect(netOnline, &QAction::triggered,
618 qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()), &Imap::Mailbox::NetworkWatcher::setNetworkOnline);
619 netExpensive->setEnabled(imapAccess()->isConfigured());
620 netOnline->setEnabled(imapAccess()->isConfigured());
623 void MainWindow::createMenus()
625 #define ADD_ACTION(MENU, ACTION) \
626 MENU->addAction(ACTION); \
627 addAction(ACTION);
629 QMenu *imapMenu = menuBar()->addMenu(tr("&IMAP"));
630 imapMenu->addMenu(m_composeMenu);
631 ADD_ACTION(imapMenu, m_actionContactEditor);
632 ADD_ACTION(imapMenu, m_replyGuess);
633 ADD_ACTION(imapMenu, m_replyPrivate);
634 ADD_ACTION(imapMenu, m_replyAll);
635 ADD_ACTION(imapMenu, m_replyAllButMe);
636 ADD_ACTION(imapMenu, m_replyList);
637 imapMenu->addSeparator();
638 ADD_ACTION(imapMenu, m_forwardAsAttachment);
639 imapMenu->addSeparator();
640 ADD_ACTION(imapMenu, expunge);
641 imapMenu->addSeparator()->setText(tr("Network Access"));
642 QMenu *netPolicyMenu = imapMenu->addMenu(tr("&Network Access"));
643 ADD_ACTION(netPolicyMenu, netOffline);
644 ADD_ACTION(netPolicyMenu, netExpensive);
645 ADD_ACTION(netPolicyMenu, netOnline);
646 QMenu *debugMenu = imapMenu->addMenu(tr("&Debugging"));
647 ADD_ACTION(debugMenu, showFullView);
648 ADD_ACTION(debugMenu, showTaskView);
649 ADD_ACTION(debugMenu, showMimeView);
650 ADD_ACTION(debugMenu, showImapLogger);
651 ADD_ACTION(debugMenu, logPersistent);
652 ADD_ACTION(debugMenu, showImapCapabilities);
653 imapMenu->addSeparator();
654 ADD_ACTION(imapMenu, configSettings);
655 ADD_ACTION(imapMenu, ShortcutHandler::instance()->shortcutConfigAction());
656 imapMenu->addSeparator();
657 ADD_ACTION(imapMenu, exitAction);
659 QMenu *viewMenu = menuBar()->addMenu(tr("&View"));
660 ADD_ACTION(viewMenu, showMenuBar);
661 ADD_ACTION(viewMenu, showToolBar);
662 QMenu *layoutMenu = viewMenu->addMenu(tr("&Layout"));
663 ADD_ACTION(layoutMenu, m_actionLayoutCompact);
664 ADD_ACTION(layoutMenu, m_actionLayoutWide);
665 ADD_ACTION(layoutMenu, m_actionLayoutOneAtTime);
666 viewMenu->addSeparator();
667 ADD_ACTION(viewMenu, m_previousMessage);
668 ADD_ACTION(viewMenu, m_nextMessage);
669 viewMenu->addSeparator();
670 QMenu *sortMenu = viewMenu->addMenu(tr("S&orting"));
671 ADD_ACTION(sortMenu, m_actionSortNone);
672 ADD_ACTION(sortMenu, m_actionSortThreading);
673 ADD_ACTION(sortMenu, m_actionSortByArrival);
674 ADD_ACTION(sortMenu, m_actionSortByCc);
675 ADD_ACTION(sortMenu, m_actionSortByDate);
676 ADD_ACTION(sortMenu, m_actionSortByFrom);
677 ADD_ACTION(sortMenu, m_actionSortBySize);
678 ADD_ACTION(sortMenu, m_actionSortBySubject);
679 ADD_ACTION(sortMenu, m_actionSortByTo);
680 sortMenu->addSeparator();
681 ADD_ACTION(sortMenu, m_actionSortAscending);
682 ADD_ACTION(sortMenu, m_actionSortDescending);
684 ADD_ACTION(viewMenu, actionThreadMsgList);
685 ADD_ACTION(viewMenu, actionHideRead);
686 ADD_ACTION(viewMenu, m_actionShowOnlySubscribed);
688 QMenu *mailboxMenu = menuBar()->addMenu(tr("&Mailbox"));
689 ADD_ACTION(mailboxMenu, resyncMbox);
690 mailboxMenu->addSeparator();
691 ADD_ACTION(mailboxMenu, reloadAllMailboxes);
693 QMenu *helpMenu = menuBar()->addMenu(tr("&Help"));
694 ADD_ACTION(helpMenu, donateToTrojita);
695 helpMenu->addSeparator();
696 ADD_ACTION(helpMenu, aboutTrojita);
698 QMenu *mainMenuBehindToolBar = new QMenu(this);
699 m_menuFromToolBar->setMenu(mainMenuBehindToolBar);
700 m_menuFromToolBar->menu()->addMenu(imapMenu);
701 m_menuFromToolBar->menu()->addMenu(viewMenu);
702 m_menuFromToolBar->menu()->addMenu(mailboxMenu);
703 m_menuFromToolBar->menu()->addMenu(helpMenu);
704 m_menuFromToolBar->menu()->addSeparator();
705 m_menuFromToolBar->menu()->addAction(showMenuBar);
707 networkIndicator->setMenu(netPolicyMenu);
708 m_netToolbarDefaultAction = new QAction(this);
709 networkIndicator->setDefaultAction(m_netToolbarDefaultAction);
710 connect(m_netToolbarDefaultAction, &QAction::triggered, networkIndicator, &QToolButton::showMenu);
711 connect(netOffline, &QAction::toggled, this, &MainWindow::updateNetworkIndication);
712 connect(netExpensive, &QAction::toggled, this, &MainWindow::updateNetworkIndication);
713 connect(netOnline, &QAction::toggled, this, &MainWindow::updateNetworkIndication);
715 #undef ADD_ACTION
718 void MainWindow::createWidgets()
720 // The state of the GUI is only saved after a certain time has passed. This is just an optimization to make sure
721 // we do not hit the disk continually when e.g. resizing some random widget.
722 m_delayedStateSaving = new QTimer(this);
723 m_delayedStateSaving->setInterval(1000);
724 m_delayedStateSaving->setSingleShot(true);
725 connect(m_delayedStateSaving, &QTimer::timeout, this, &MainWindow::saveSizesAndState);
727 mboxTree = new MailBoxTreeView();
728 mboxTree->setDesiredExpansion(m_settings->value(Common::SettingsNames::guiExpandedMailboxes).toStringList());
729 connect(mboxTree, &QWidget::customContextMenuRequested, this, &MainWindow::showContextMenuMboxTree);
730 connect(mboxTree, &MailBoxTreeView::mailboxExpansionChanged, this, [this](const QStringList &mailboxNames) {
731 m_settings->setValue(Common::SettingsNames::guiExpandedMailboxes, mailboxNames);
734 msgListWidget = new MessageListWidget();
735 msgListWidget->tree->setContextMenuPolicy(Qt::CustomContextMenu);
736 msgListWidget->tree->setAlternatingRowColors(true);
737 msgListWidget->setRawSearchEnabled(m_settings->value(Common::SettingsNames::guiAllowRawSearch).toBool());
738 connect (msgListWidget, &MessageListWidget::rawSearchSettingChanged, this, &MainWindow::saveRawStateSetting);
740 connect(msgListWidget->tree, &QWidget::customContextMenuRequested, this, &MainWindow::showContextMenuMsgListTree);
741 connect(msgListWidget->tree, &QAbstractItemView::activated, this, &MainWindow::msgListClicked);
742 connect(msgListWidget->tree, &QAbstractItemView::clicked, this, &MainWindow::msgListClicked);
743 connect(msgListWidget->tree, &QAbstractItemView::doubleClicked, this, &MainWindow::msgListDoubleClicked);
744 connect(msgListWidget, &MessageListWidget::requestingSearch, this, &MainWindow::slotSearchRequested);
745 connect(msgListWidget->tree->header(), &QHeaderView::sectionMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
746 connect(msgListWidget->tree->header(), &QHeaderView::sectionResized, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
748 msgListWidget->tree->installEventFilter(this);
750 m_messageWidget = new CompleteMessageWidget(this, m_settings, m_pluginManager);
751 connect(m_messageWidget->messageView, &MessageView::messageChanged, this, &MainWindow::scrollMessageUp);
752 connect(m_messageWidget->messageView, &MessageView::messageChanged, this, &MainWindow::slotUpdateMessageActions);
753 #if QT_VERSION >= QT_VERSION_CHECK(5, 4, 0)
754 connect(m_messageWidget->messageView, &MessageView::linkHovered, [](const QString &url) {
755 if (url.isEmpty()) {
756 QToolTip::hideText();
757 } else {
758 // indirection due to https://bugs.kde.org/show_bug.cgi?id=363783
759 QTimer::singleShot(250, [url]() {
760 QToolTip::showText(QCursor::pos(), QObject::tr("Link target: %1").arg(UiUtils::Formatting::htmlEscaped(url)));
764 #endif
765 connect(m_messageWidget->messageView, &MessageView::transferError, this, &MainWindow::slotDownloadTransferError);
766 // Do not try to get onto the homepage when we are on EXPENSIVE connection
767 if (m_settings->value(Common::SettingsNames::appLoadHomepage, QVariant(true)).toBool() &&
768 m_imapAccess->preferredNetworkPolicy() == Imap::Mailbox::NETWORK_ONLINE) {
769 m_messageWidget->messageView->setHomepageUrl(QUrl(QStringLiteral("http://welcome.trojita.flaska.net/%1").arg(Common::Application::version)));
772 allDock = new QDockWidget(tr("Everything"), this);
773 allDock->setObjectName(QStringLiteral("allDock"));
774 allTree = new QTreeView(allDock);
775 allDock->hide();
776 allTree->setUniformRowHeights(true);
777 allTree->setHeaderHidden(true);
778 allDock->setWidget(allTree);
779 addDockWidget(Qt::LeftDockWidgetArea, allDock);
780 taskDock = new QDockWidget(tr("IMAP Tasks"), this);
781 taskDock->setObjectName(QStringLiteral("taskDock"));
782 taskTree = new QTreeView(taskDock);
783 taskDock->hide();
784 taskTree->setHeaderHidden(true);
785 taskDock->setWidget(taskTree);
786 addDockWidget(Qt::LeftDockWidgetArea, taskDock);
787 mailMimeDock = new QDockWidget(tr("MIME Tree"), this);
788 mailMimeDock->setObjectName(QStringLiteral("mailMimeDock"));
789 mailMimeTree = new QTreeView(mailMimeDock);
790 mailMimeDock->hide();
791 mailMimeTree->setUniformRowHeights(true);
792 mailMimeTree->setHeaderHidden(true);
793 mailMimeDock->setWidget(mailMimeTree);
794 addDockWidget(Qt::RightDockWidgetArea, mailMimeDock);
795 connect(m_messageWidget->messageView, &MessageView::messageModelChanged, this, &MainWindow::slotMessageModelChanged);
797 imapLoggerDock = new QDockWidget(tr("IMAP Protocol"), this);
798 imapLoggerDock->setObjectName(QStringLiteral("imapLoggerDock"));
799 imapLogger = new ProtocolLoggerWidget(imapLoggerDock);
800 imapLoggerDock->hide();
801 imapLoggerDock->setWidget(imapLogger);
802 addDockWidget(Qt::BottomDockWidgetArea, imapLoggerDock);
804 busyParsersIndicator = new TaskProgressIndicator(this);
807 void MainWindow::setupModels()
809 m_imapAccess->reloadConfiguration();
810 m_imapAccess->doConnect();
812 m_messageWidget->messageView->setNetworkWatcher(qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()));
814 auto realThreadingModel = qobject_cast<Imap::Mailbox::ThreadingMsgListModel*>(m_imapAccess->threadingMsgListModel());
815 Q_ASSERT(realThreadingModel);
816 auto realMsgListModel = qobject_cast<Imap::Mailbox::MsgListModel*>(m_imapAccess->msgListModel());
817 Q_ASSERT(realMsgListModel);
819 prettyMboxModel = new Imap::Mailbox::PrettyMailboxModel(this, qobject_cast<QAbstractItemModel *>(m_imapAccess->mailboxModel()));
820 prettyMboxModel->setObjectName(QStringLiteral("prettyMboxModel"));
821 connect(realThreadingModel, &Imap::Mailbox::ThreadingMsgListModel::sortingFailed,
822 msgListWidget, &MessageListWidget::slotSortingFailed);
823 prettyMsgListModel = new Imap::Mailbox::PrettyMsgListModel(this);
824 prettyMsgListModel->setSourceModel(m_imapAccess->threadingMsgListModel());
825 prettyMsgListModel->setObjectName(QStringLiteral("prettyMsgListModel"));
827 connect(mboxTree, &MailBoxTreeView::clicked,
828 realMsgListModel,
829 static_cast<void (Imap::Mailbox::MsgListModel::*)(const QModelIndex &)>(&Imap::Mailbox::MsgListModel::setMailbox));
830 connect(mboxTree, &MailBoxTreeView::activated,
831 realMsgListModel,
832 static_cast<void (Imap::Mailbox::MsgListModel::*)(const QModelIndex &)>(&Imap::Mailbox::MsgListModel::setMailbox));
833 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::dataChanged, this, &MainWindow::updateMessageFlags);
834 connect(qobject_cast<Imap::Mailbox::MsgListModel*>(m_imapAccess->msgListModel()), &Imap::Mailbox::MsgListModel::messagesAvailable,
835 this, &MainWindow::slotScrollToUnseenMessage);
836 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::rowsInserted, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
837 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::rowsRemoved, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
838 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::rowsRemoved, this, &MainWindow::updateMessageFlags);
839 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::layoutChanged, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
840 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::layoutChanged, this, &MainWindow::updateMessageFlags);
841 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::modelReset, msgListWidget, &MessageListWidget::slotAutoEnableDisableSearch);
842 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::modelReset, this, &MainWindow::updateMessageFlags);
843 connect(realMsgListModel, &Imap::Mailbox::MsgListModel::mailboxChanged, this, &MainWindow::slotMailboxChanged);
845 connect(imapModel(), &Imap::Mailbox::Model::alertReceived, this, &MainWindow::alertReceived);
846 connect(imapModel(), &Imap::Mailbox::Model::imapError, this, &MainWindow::imapError);
847 connect(imapModel(), &Imap::Mailbox::Model::networkError, this, &MainWindow::networkError);
848 connect(imapModel(), &Imap::Mailbox::Model::authRequested, this, &MainWindow::authenticationRequested, Qt::QueuedConnection);
849 connect(imapModel(), &Imap::Mailbox::Model::authAttemptFailed, this, [this]() {
850 m_ignoreStoredPassword = true;
853 connect(imapModel(), &Imap::Mailbox::Model::networkPolicyOffline, this, &MainWindow::networkPolicyOffline);
854 connect(imapModel(), &Imap::Mailbox::Model::networkPolicyExpensive, this, &MainWindow::networkPolicyExpensive);
855 connect(imapModel(), &Imap::Mailbox::Model::networkPolicyOnline, this, &MainWindow::networkPolicyOnline);
856 connect(imapModel(), &Imap::Mailbox::Model::connectionStateChanged, this, [this](uint, const Imap::ConnectionState state) {
857 if (state == Imap::CONN_STATE_AUTHENTICATED) {
858 m_ignoreStoredPassword = false;
861 connect(imapModel(), &Imap::Mailbox::Model::connectionStateChanged, this, &MainWindow::showConnectionStatus);
863 connect(imapModel(), &Imap::Mailbox::Model::mailboxDeletionFailed, this, &MainWindow::slotMailboxDeleteFailed);
864 connect(imapModel(), &Imap::Mailbox::Model::mailboxCreationFailed, this, &MainWindow::slotMailboxCreateFailed);
865 connect(imapModel(), &Imap::Mailbox::Model::mailboxSyncFailed, this, &MainWindow::slotMailboxSyncFailed);
867 connect(imapModel(), &Imap::Mailbox::Model::logged, imapLogger, &ProtocolLoggerWidget::slotImapLogged);
868 connect(imapModel(), &Imap::Mailbox::Model::connectionStateChanged, imapLogger, &ProtocolLoggerWidget::onConnectionClosed);
870 auto nw = qobject_cast<Imap::Mailbox::NetworkWatcher *>(m_imapAccess->networkWatcher());
871 Q_ASSERT(nw);
872 connect(nw, &Imap::Mailbox::NetworkWatcher::reconnectAttemptScheduled,
873 this, [this](const int timeout) {
874 showStatusMessage(tr("Attempting to reconnect in %n seconds..", 0, timeout/1000));
876 connect(nw, &Imap::Mailbox::NetworkWatcher::resetReconnectState, this, &MainWindow::slotResetReconnectState);
878 connect(imapModel(), &Imap::Mailbox::Model::mailboxFirstUnseenMessage, this, &MainWindow::slotScrollToUnseenMessage);
880 connect(imapModel(), &Imap::Mailbox::Model::capabilitiesUpdated, this, &MainWindow::slotCapabilitiesUpdated);
882 connect(m_imapAccess->msgListModel(), &QAbstractItemModel::modelReset, this, &MainWindow::slotUpdateWindowTitle);
883 connect(imapModel(), &Imap::Mailbox::Model::messageCountPossiblyChanged, this, &MainWindow::slotUpdateWindowTitle);
885 connect(prettyMsgListModel, &Imap::Mailbox::PrettyMsgListModel::sortingPreferenceChanged, this, &MainWindow::slotSortingConfirmed);
887 //Imap::Mailbox::ModelWatcher* w = new Imap::Mailbox::ModelWatcher( this );
888 //w->setModel( imapModel() );
890 //ModelTest* tester = new ModelTest( prettyMboxModel, this ); // when testing, test just one model at time
892 mboxTree->setModel(prettyMboxModel);
893 msgListWidget->tree->setModel(prettyMsgListModel);
894 connect(msgListWidget->tree->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::updateMessageFlags);
896 allTree->setModel(imapModel());
897 taskTree->setModel(imapModel()->taskModel());
898 connect(imapModel()->taskModel(), &QAbstractItemModel::layoutChanged, taskTree, &QTreeView::expandAll);
899 connect(imapModel()->taskModel(), &QAbstractItemModel::modelReset, taskTree, &QTreeView::expandAll);
900 connect(imapModel()->taskModel(), &QAbstractItemModel::rowsInserted, taskTree, &QTreeView::expandAll);
901 connect(imapModel()->taskModel(), &QAbstractItemModel::rowsRemoved, taskTree, &QTreeView::expandAll);
902 connect(imapModel()->taskModel(), &QAbstractItemModel::rowsMoved, taskTree, &QTreeView::expandAll);
904 busyParsersIndicator->setImapModel(imapModel());
906 auto accountIconName = m_settings->value(Common::SettingsNames::imapAccountIcon).toString();
907 if (accountIconName.isEmpty()) {
908 qApp->setWindowIcon(UiUtils::loadIcon(QStringLiteral("trojita")));
909 } else if (accountIconName.contains(QDir::separator())) {
910 // Absolute paths are OK for users, but unsupported by our icon loader
911 qApp->setWindowIcon(QIcon(accountIconName));
912 } else {
913 qApp->setWindowIcon(UiUtils::loadIcon(accountIconName));
917 void MainWindow::createSysTray()
919 if (m_trayIcon)
920 return;
922 qApp->setQuitOnLastWindowClosed(false);
924 m_trayIcon = new QSystemTrayIcon(this);
925 handleTrayIconChange();
927 QAction* quitAction = new QAction(tr("&Quit"), m_trayIcon);
928 connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
930 QMenu *trayIconMenu = new QMenu(this);
931 trayIconMenu->addAction(quitAction);
932 m_trayIcon->setContextMenu(trayIconMenu);
934 // QMenu cannot be a child of QSystemTrayIcon, and we don't want the QMenu in MainWindow scope.
935 connect(m_trayIcon, &QObject::destroyed, trayIconMenu, &QObject::deleteLater);
937 connect(m_trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::slotIconActivated);
938 connect(imapModel(), &Imap::Mailbox::Model::messageCountPossiblyChanged, this, &MainWindow::handleTrayIconChange);
939 m_trayIcon->setVisible(true);
940 m_trayIcon->show();
943 void MainWindow::removeSysTray()
945 delete m_trayIcon;
946 m_trayIcon = 0;
948 qApp->setQuitOnLastWindowClosed(true);
951 void MainWindow::slotToggleSysTray()
953 bool showSystray = m_settings->value(Common::SettingsNames::guiShowSystray, QVariant(true)).toBool();
954 if (showSystray && !m_trayIcon && QSystemTrayIcon::isSystemTrayAvailable()) {
955 createSysTray();
956 } else if (!showSystray && m_trayIcon) {
957 removeSysTray();
961 void MainWindow::handleTrayIconChange()
963 if (!m_trayIcon)
964 return;
966 const bool isOffline = qobject_cast<Imap::Mailbox::NetworkWatcher *>(m_imapAccess->networkWatcher())->effectiveNetworkPolicy()
967 == Imap::Mailbox::NETWORK_OFFLINE;
968 auto pixmap = qApp->windowIcon()
969 .pixmap(QSize(32, 32), isOffline ? QIcon::Disabled : QIcon::Normal);
970 QString tooltip;
971 auto profileName = QString::fromUtf8(qgetenv("TROJITA_PROFILE"));
972 if (profileName.isEmpty()) {
973 tooltip = QStringLiteral("Trojitá");
974 } else {
975 tooltip = QStringLiteral("Trojitá [%1]").arg(profileName);
978 uint unreadCount = 0;
979 bool numbersValid = false;
981 auto watchingMode = settings()->value(Common::SettingsNames::watchedFoldersKey).toString();
982 if (watchingMode == Common::SettingsNames::watchAll || watchingMode == Common::SettingsNames::watchSubscribed) {
983 bool subscribedOnly = watchingMode == Common::SettingsNames::watchSubscribed;
984 unreadCount = std::accumulate(UiUtils::QaimDfsIterator(m_imapAccess->mailboxModel()->index(0, 0)),
985 UiUtils::QaimDfsIterator(), 0, [subscribedOnly](const uint acc, const QModelIndex &idx) {
987 if (subscribedOnly && !idx.data(Imap::Mailbox::RoleMailboxIsSubscribed).toBool())
988 return acc;
990 auto x = idx.data(Imap::Mailbox::RoleUnreadMessageCount).toInt();
991 if (x > 0) {
992 return acc + x;
993 } else {
994 return acc;
997 // only show stuff if there are some mailboxes, and if there are such messages
998 numbersValid = m_imapAccess->mailboxModel()->hasChildren() && unreadCount > 0;
1000 } else {
1001 // just for the INBOX
1002 QModelIndex mailbox = imapModel()->index(1, 0, QModelIndex());
1003 if (mailbox.isValid() && mailbox.data(Imap::Mailbox::RoleMailboxName).toString() == QLatin1String("INBOX")
1004 && mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt() > 0) {
1005 unreadCount = mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt();
1006 numbersValid = true;
1010 if (numbersValid) {
1011 QFont f;
1012 f.setPixelSize(pixmap.height() * 0.59);
1013 f.setWeight(QFont::Bold);
1015 QString text = QString::number(unreadCount);
1016 QFontMetrics fm(f);
1017 if (unreadCount > 666) {
1018 // You just have too many messages.
1019 text = QStringLiteral("🐮");
1020 fm = QFontMetrics(f);
1021 } else if (fm.width(text) > pixmap.width()) {
1022 f.setPixelSize(f.pixelSize() * pixmap.width() / fm.width(text));
1023 fm = QFontMetrics(f);
1026 QRect boundingRect = fm.tightBoundingRect(text);
1027 boundingRect.setWidth(boundingRect.width() + 2);
1028 boundingRect.setHeight(boundingRect.height() + 2);
1029 boundingRect.moveCenter(QPoint(pixmap.width() / 2, pixmap.height() / 2));
1030 boundingRect = boundingRect.intersected(pixmap.rect());
1032 QPainterPath path;
1033 path.addText(boundingRect.bottomLeft(), f, text);
1035 QPainter painter(&pixmap);
1036 painter.setRenderHint(QPainter::Antialiasing);
1037 painter.setPen(QColor(255,255,255, 180));
1038 painter.setBrush(isOffline ? Qt::red : Qt::black);
1039 painter.drawPath(path);
1041 //: This is a tooltip for the tray icon. It will be prefixed by something like "Trojita" or "Trojita [work]"
1042 tooltip += trUtf8(" - %n unread message(s)", 0, unreadCount);
1043 } else if (isOffline) {
1044 //: A tooltip suffix when offline. The prefix is something like "Trojita" or "Trojita [work]"
1045 tooltip += tr(" - offline");
1047 m_trayIcon->setToolTip(tooltip);
1048 m_trayIcon->setIcon(QIcon(pixmap));
1051 void MainWindow::closeEvent(QCloseEvent *event)
1053 if (m_trayIcon && m_trayIcon->isVisible()) {
1054 Util::askForSomethingUnlessTold(trUtf8("Trojitá"),
1055 tr("The application will continue in systray. This can be disabled within the settings."),
1056 Common::SettingsNames::guiOnSystrayClose, QMessageBox::Ok, this, m_settings);
1057 hide();
1058 event->ignore();
1062 bool MainWindow::eventFilter(QObject *o, QEvent *e)
1064 if (msgListWidget && o == msgListWidget->tree && m_messageWidget->messageView) {
1065 if (e->type() == QEvent::KeyPress) {
1066 QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
1067 if (keyEvent->key() == Qt::Key_Space || keyEvent->key() == Qt::Key_Backspace) {
1068 QCoreApplication::sendEvent(m_messageWidget, keyEvent);
1069 return true;
1071 return false;
1073 return false;
1075 if (msgListWidget && msgListWidget->tree && o == msgListWidget->tree->header()->viewport()) {
1076 // installed if sorting is not really possible.
1077 QWidget *header = static_cast<QWidget*>(o);
1078 QMouseEvent *mouse = static_cast<QMouseEvent*>(e);
1079 if (e->type() == QEvent::MouseButtonPress) {
1080 if (mouse->button() == Qt::LeftButton && header->cursor().shape() == Qt::ArrowCursor) {
1081 m_headerDragStart = mouse->pos();
1083 return false;
1085 if (e->type() == QEvent::MouseButtonRelease) {
1086 if (mouse->button() == Qt::LeftButton && header->cursor().shape() == Qt::ArrowCursor &&
1087 (m_headerDragStart - mouse->pos()).manhattanLength() < QApplication::startDragDistance()) {
1088 m_actionSortDescending->toggle();
1089 Qt::SortOrder order = m_actionSortDescending->isChecked() ? Qt::DescendingOrder : Qt::AscendingOrder;
1090 msgListWidget->tree->header()->setSortIndicator(-1, order);
1091 return true; // prevent regular click
1095 return false;
1098 void MainWindow::slotIconActivated(const QSystemTrayIcon::ActivationReason reason)
1100 if (reason == QSystemTrayIcon::Trigger) {
1101 setVisible(!isVisible());
1102 if (isVisible())
1103 showMainWindow();
1107 void MainWindow::showMainWindow()
1109 setVisible(true);
1110 activateWindow();
1111 raise();
1114 void MainWindow::msgListClicked(const QModelIndex &index)
1116 Q_ASSERT(index.isValid());
1118 if (qApp->keyboardModifiers() & Qt::ShiftModifier || qApp->keyboardModifiers() & Qt::ControlModifier)
1119 return;
1121 if (! index.data(Imap::Mailbox::RoleMessageUid).isValid())
1122 return;
1124 // Because it's quite possible that we have switched into another mailbox, make sure that we're in the "current" one so that
1125 // user will be notified about new arrivals, etc.
1126 QModelIndex translated = Imap::deproxifiedIndex(index);
1127 imapModel()->switchToMailbox(translated.parent().parent());
1129 if (index.column() == Imap::Mailbox::MsgListModel::SEEN) {
1130 if (!translated.data(Imap::Mailbox::RoleIsFetched).toBool())
1131 return;
1132 Imap::Mailbox::FlagsOperation flagOp = translated.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool() ?
1133 Imap::Mailbox::FLAG_REMOVE : Imap::Mailbox::FLAG_ADD;
1134 imapModel()->markMessagesRead(QModelIndexList() << translated, flagOp);
1136 if (translated == m_messageWidget->messageView->currentMessage()) {
1137 m_messageWidget->messageView->stopAutoMarkAsRead();
1139 } else if (index.column() == Imap::Mailbox::MsgListModel::FLAGGED) {
1140 if (!translated.data(Imap::Mailbox::RoleIsFetched).toBool())
1141 return;
1143 Imap::Mailbox::FlagsOperation flagOp = translated.data(Imap::Mailbox::RoleMessageIsMarkedFlagged).toBool() ?
1144 Imap::Mailbox::FLAG_REMOVE : Imap::Mailbox::FLAG_ADD;
1145 imapModel()->setMessageFlags(QModelIndexList() << translated, Imap::Mailbox::FlagNames::flagged, flagOp);
1146 } else {
1147 if ((m_messageWidget->isVisible() && !m_messageWidget->size().isEmpty()) || m_layoutMode == LAYOUT_ONE_AT_TIME) {
1148 // isVisible() won't work, the splitter manipulates width, not the visibility state
1149 m_messageWidget->messageView->setMessage(index);
1151 msgListWidget->tree->setCurrentIndex(index);
1155 void MainWindow::msgListDoubleClicked(const QModelIndex &index)
1157 Q_ASSERT(index.isValid());
1159 if (! index.data(Imap::Mailbox::RoleMessageUid).isValid())
1160 return;
1162 CompleteMessageWidget *widget = new CompleteMessageWidget(0, m_settings, m_pluginManager);
1163 widget->messageView->setMessage(index);
1164 widget->messageView->setNetworkWatcher(qobject_cast<Imap::Mailbox::NetworkWatcher*>(m_imapAccess->networkWatcher()));
1165 widget->setFocusPolicy(Qt::StrongFocus);
1166 widget->setWindowTitle(index.data(Imap::Mailbox::RoleMessageSubject).toString());
1167 widget->setAttribute(Qt::WA_DeleteOnClose);
1168 QAction *closeAction = ShortcutHandler::instance()->createAction(QStringLiteral("action_messagewindow_close"), widget, SLOT(close()), widget);
1169 widget->addAction(closeAction);
1170 widget->show();
1173 void MainWindow::showContextMenuMboxTree(const QPoint &position)
1175 QList<QAction *> actionList;
1176 if (mboxTree->indexAt(position).isValid()) {
1177 actionList.append(createChildMailbox);
1178 actionList.append(deleteCurrentMailbox);
1179 actionList.append(m_actionMarkMailboxAsRead);
1180 actionList.append(resyncMbox);
1181 actionList.append(reloadMboxList);
1183 actionList.append(m_actionSubscribeMailbox);
1184 m_actionSubscribeMailbox->setChecked(mboxTree->indexAt(position).data(Imap::Mailbox::RoleMailboxIsSubscribed).toBool());
1186 #ifdef XTUPLE_CONNECT
1187 actionList.append(xtIncludeMailboxInSync);
1188 xtIncludeMailboxInSync->setChecked(
1189 m_settings->value(Common::SettingsNames::xtSyncMailboxList).toStringList().contains(
1190 mboxTree->indexAt(position).data(Imap::Mailbox::RoleMailboxName).toString()));
1191 #endif
1192 } else {
1193 actionList.append(createTopMailbox);
1195 actionList.append(reloadAllMailboxes);
1196 actionList.append(m_actionShowOnlySubscribed);
1197 QMenu::exec(actionList, mboxTree->mapToGlobal(position));
1200 void MainWindow::showContextMenuMsgListTree(const QPoint &position)
1202 QList<QAction *> actionList;
1203 QModelIndex index = msgListWidget->tree->indexAt(position);
1204 if (index.isValid()) {
1205 updateMessageFlagsOf(index);
1206 actionList.append(markAsRead);
1207 actionList.append(markAsDeleted);
1208 actionList.append(markAsFlagged);
1209 actionList.append(markAsJunk);
1210 actionList.append(markAsNotJunk);
1211 actionList.append(moveToArchive);
1212 actionList.append(m_actionMarkMailboxAsRead);
1213 actionList.append(saveWholeMessage);
1214 actionList.append(viewMsgSource);
1215 actionList.append(viewMsgHeaders);
1217 if (! actionList.isEmpty())
1218 QMenu::exec(actionList, msgListWidget->tree->mapToGlobal(position));
1221 /** @short Ask for an updated list of mailboxes situated below the selected one
1224 void MainWindow::slotReloadMboxList()
1226 Q_FOREACH(const QModelIndex &item, mboxTree->selectionModel()->selectedIndexes()) {
1227 Q_ASSERT(item.isValid());
1228 if (item.column() != 0)
1229 continue;
1230 Imap::Mailbox::TreeItemMailbox *mbox = dynamic_cast<Imap::Mailbox::TreeItemMailbox *>(
1231 Imap::Mailbox::Model::realTreeItem(item)
1233 Q_ASSERT(mbox);
1234 mbox->rescanForChildMailboxes(imapModel());
1238 /** @short Request a check for new messages in selected mailbox */
1239 void MainWindow::slotResyncMbox()
1241 if (! imapModel()->isNetworkAvailable())
1242 return;
1244 Q_FOREACH(const QModelIndex &item, mboxTree->selectionModel()->selectedIndexes()) {
1245 Q_ASSERT(item.isValid());
1246 if (item.column() != 0)
1247 continue;
1248 imapModel()->resyncMailbox(item);
1252 void MainWindow::alertReceived(const QString &message)
1254 //: "ALERT" is a special warning which we're required to show to the user
1255 Gui::Util::messageBoxWarning(this, tr("IMAP Alert"), message);
1258 void MainWindow::imapError(const QString &message)
1260 Gui::Util::messageBoxCritical(this, tr("IMAP Protocol Error"), message);
1261 // Show the IMAP logger -- maybe some user will take that as a hint that they shall include it in the bug report.
1262 // </joke>
1263 showImapLogger->setChecked(true);
1266 void MainWindow::networkError(const QString &message)
1268 const QString title = tr("Network Error");
1269 if (!m_networkErrorMessageBox) {
1270 m_networkErrorMessageBox = new QMessageBox(QMessageBox::Critical, title,
1271 QString(), QMessageBox::Ok, this);
1273 // User must be informed about a new (but not recurring) error
1274 if (message != m_networkErrorMessageBox->text()) {
1275 m_networkErrorMessageBox->setText(message);
1276 if (qApp->applicationState() == Qt::ApplicationActive) {
1277 m_networkErrorMessageBox->setProperty(netErrorUnseen, false);
1278 m_networkErrorMessageBox->show();
1279 } else {
1280 m_networkErrorMessageBox->setProperty(netErrorUnseen, true);
1281 if (m_trayIcon && m_trayIcon->isVisible())
1282 m_trayIcon->showMessage(title, message, QSystemTrayIcon::Warning, 3333);
1287 void MainWindow::cacheError(const QString &message)
1289 Gui::Util::messageBoxCritical(this, tr("IMAP Cache Error"),
1290 tr("The caching subsystem managing a cache of the data already "
1291 "downloaded from the IMAP server is having troubles. "
1292 "All caching will be disabled.\n\n%1").arg(message));
1295 void MainWindow::networkPolicyOffline()
1297 netExpensive->setChecked(false);
1298 netOnline->setChecked(false);
1299 netOffline->setChecked(true);
1300 updateActionsOnlineOffline(false);
1301 showStatusMessage(tr("Offline"));
1302 handleTrayIconChange();
1305 void MainWindow::networkPolicyExpensive()
1307 netOffline->setChecked(false);
1308 netOnline->setChecked(false);
1309 netExpensive->setChecked(true);
1310 updateActionsOnlineOffline(true);
1311 handleTrayIconChange();
1314 void MainWindow::networkPolicyOnline()
1316 netOffline->setChecked(false);
1317 netExpensive->setChecked(false);
1318 netOnline->setChecked(true);
1319 updateActionsOnlineOffline(true);
1320 handleTrayIconChange();
1323 /** @short Deletes a network error message box instance upon resetting of reconnect state */
1324 void MainWindow::slotResetReconnectState()
1326 if (m_networkErrorMessageBox) {
1327 delete m_networkErrorMessageBox;
1328 m_networkErrorMessageBox = 0;
1332 void MainWindow::slotShowSettings()
1334 SettingsDialog *dialog = new SettingsDialog(this, m_senderIdentities, m_settings);
1335 if (dialog->exec() == QDialog::Accepted) {
1336 // FIXME: wipe cache in case we're moving between servers
1337 nukeModels();
1338 setupModels();
1339 connectModelActions();
1340 // The systray is still connected to the old model -- got to make sure it's getting updated
1341 removeSysTray();
1342 slotToggleSysTray();
1344 QString method = m_settings->value(Common::SettingsNames::imapMethodKey).toString();
1345 if (method != Common::SettingsNames::methodTCP && method != Common::SettingsNames::methodSSL &&
1346 method != Common::SettingsNames::methodProcess ) {
1347 Gui::Util::messageBoxCritical(this, tr("No Configuration"),
1348 trUtf8("No IMAP account is configured. Trojitá cannot do much without one."));
1350 applySizesAndState();
1353 void MainWindow::authenticationRequested()
1355 Plugins::PasswordPlugin *password = pluginManager()->password();
1356 if (password) {
1357 // FIXME: use another account-id at some point in future
1358 // Currently the accountName will be empty unless Trojita has been
1359 // called with a profile, and then the profile will be used as the
1360 // accountName.
1361 QString accountName = m_imapAccess->accountName();
1362 if (accountName.isEmpty())
1363 accountName = QStringLiteral("account-0");
1364 Plugins::PasswordJob *job = password->requestPassword(accountName, QStringLiteral("imap"));
1365 if (job) {
1366 connect(job, &Plugins::PasswordJob::passwordAvailable, this, [this](const QString &password) {
1367 authenticationContinue(password);
1369 connect(job, &Plugins::PasswordJob::error, this, [this](const Plugins::PasswordJob::Error error, const QString &message) {
1370 if (error == Plugins::PasswordJob::Error::NoSuchPassword) {
1371 authenticationContinue(QString());
1372 } else {
1373 authenticationContinue(QString(), tr("Failed to retrieve password from the store: %1").arg(message));
1376 job->setAutoDelete(true);
1377 job->start();
1378 return;
1382 authenticationContinue(QString());
1386 void MainWindow::authenticationContinue(const QString &password, const QString &errorMessage)
1388 const QString &user = m_settings->value(Common::SettingsNames::imapUserKey).toString();
1389 QString pass = password;
1390 if (m_ignoreStoredPassword || pass.isEmpty()) {
1391 auto dialog = PasswordDialog::getPassword(this, tr("Authentication Required"),
1392 tr("<p>Please provide IMAP password for user <b>%1</b> on <b>%2</b>:</p>").arg(
1393 user.toHtmlEscaped(),
1394 m_settings->value(Common::SettingsNames::imapHostKey).toString().toHtmlEscaped()
1396 errorMessage + (errorMessage.isEmpty() ? QString() : QStringLiteral("\n\n"))
1397 + imapModel()->imapAuthError());
1398 connect(dialog, &PasswordDialog::gotPassword, imapModel(), &Imap::Mailbox::Model::setImapPassword);
1399 connect(dialog, &PasswordDialog::rejected, imapModel(), &Imap::Mailbox::Model::unsetImapPassword);
1400 } else {
1401 imapModel()->setImapPassword(pass);
1405 void MainWindow::checkSslPolicy()
1407 m_imapAccess->setSslPolicy(QMessageBox(static_cast<QMessageBox::Icon>(m_imapAccess->sslInfoIcon()),
1408 m_imapAccess->sslInfoTitle(), m_imapAccess->sslInfoMessage(),
1409 QMessageBox::Yes | QMessageBox::No, this).exec() == QMessageBox::Yes);
1412 void MainWindow::nukeModels()
1414 m_messageWidget->messageView->setEmpty();
1415 mboxTree->setModel(0);
1416 msgListWidget->tree->setModel(0);
1417 allTree->setModel(0);
1418 taskTree->setModel(0);
1419 delete prettyMsgListModel;
1420 prettyMsgListModel = 0;
1421 delete prettyMboxModel;
1422 prettyMboxModel = 0;
1425 void MainWindow::recoverDrafts()
1427 QDir draftPath(Common::writablePath(Common::LOCATION_CACHE) + QLatin1String("Drafts/"));
1428 QStringList drafts(draftPath.entryList(QStringList() << QStringLiteral("*.draft")));
1429 Q_FOREACH(const QString &draft, drafts) {
1430 ComposeWidget *w = ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createDraft(this, draftPath.filePath(draft)), this);
1431 // No need to further try creating widgets for drafts if a nullptr is being returned by ComposeWidget::warnIfMsaNotConfigured
1432 if (!w)
1433 break;
1437 void MainWindow::slotComposeMail()
1439 ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createBlank(this), this);
1442 void MainWindow::slotEditDraft()
1444 QString path(Common::writablePath(Common::LOCATION_DATA) + tr("Drafts"));
1445 QDir().mkpath(path);
1446 path = QFileDialog::getOpenFileName(this, tr("Edit draft"), path, tr("Drafts") + QLatin1String(" (*.draft)"));
1447 if (!path.isNull()) {
1448 ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createDraft(this, path), this);
1452 QModelIndexList MainWindow::translatedSelection() const
1454 QModelIndexList translatedIndexes;
1455 QModelIndexList selected = msgListWidget->tree->selectionModel()->selectedIndexes();
1456 const int originalItems = selected.length(); // only check collapsed/expanded status on original selection
1457 for (int i = 0; i < selected.length(); ++i) {
1458 const QModelIndex item = selected[i];
1459 if (item.column() != 0 || !item.data(Imap::Mailbox::RoleMessageUid).isValid())
1460 continue;
1461 translatedIndexes << Imap::deproxifiedIndex(item);
1462 // Now see if this is a collapsed thread and include all the collapsed items as needed
1463 // Also note that this is recursive - each child found is run through this same item loop for validity/child checks as well
1464 if (i >= originalItems || !msgListWidget->tree->isExpanded(item)) {
1465 for (int j = 0; j < item.model()->rowCount(item); ++j) {
1466 selected << item.child(j, 0); // Make sure this is run through the main loop as well - don't add it directly
1470 return translatedIndexes;
1473 void MainWindow::handleMarkAsRead(bool value)
1475 const QModelIndexList translatedIndexes = translatedSelection();
1476 if (translatedIndexes.isEmpty()) {
1477 qDebug() << "Model::handleMarkAsRead: no valid messages";
1478 } else {
1479 imapModel()->markMessagesRead(translatedIndexes, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1480 if (translatedIndexes.contains(m_messageWidget->messageView->currentMessage())) {
1481 m_messageWidget->messageView->stopAutoMarkAsRead();
1486 void MainWindow::slotNextUnread()
1488 QModelIndex current = msgListWidget->tree->currentIndex();
1490 UiUtils::gotoNext(msgListWidget->tree->model(), current,
1491 [](const QModelIndex &idx) { return !idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool(); },
1492 [this](const QModelIndex &idx) {
1493 Q_ASSERT(!idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool());
1494 m_messageWidget->messageView->setMessage(idx);
1495 msgListWidget->tree->setCurrentIndex(idx);
1497 []() {
1498 // nothing to do
1502 void MainWindow::slotPreviousUnread()
1504 QModelIndex current = msgListWidget->tree->currentIndex();
1506 UiUtils::gotoPrevious(msgListWidget->tree->model(), current,
1507 [](const QModelIndex &idx) { return !idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool(); },
1508 [this](const QModelIndex &idx) {
1509 Q_ASSERT(!idx.data(Imap::Mailbox::RoleMessageIsMarkedRead).toBool());
1510 m_messageWidget->messageView->setMessage(idx);
1511 msgListWidget->tree->setCurrentIndex(idx);
1513 []() {
1514 // nothing to do
1518 void MainWindow::handleMarkAsDeleted(bool value)
1520 const QModelIndexList translatedIndexes = translatedSelection();
1521 if (translatedIndexes.isEmpty()) {
1522 qDebug() << "Model::handleMarkAsDeleted: no valid messages";
1523 } else {
1524 imapModel()->markMessagesDeleted(translatedIndexes, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1528 void MainWindow::handleMarkAsFlagged(const bool value)
1530 const QModelIndexList translatedIndexes = translatedSelection();
1531 if (translatedIndexes.isEmpty()) {
1532 qDebug() << "Model::handleMarkAsFlagged: no valid messages";
1533 } else {
1534 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::flagged, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1538 void MainWindow::handleMarkAsJunk(const bool value)
1540 const QModelIndexList translatedIndexes = translatedSelection();
1541 if (translatedIndexes.isEmpty()) {
1542 qDebug() << "Model::handleMarkAsJunk: no valid messages";
1543 } else {
1544 if (value) {
1545 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::notjunk, Imap::Mailbox::FLAG_REMOVE);
1547 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::junk, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1551 void MainWindow::handleMarkAsNotJunk(const bool value)
1553 const QModelIndexList translatedIndexes = translatedSelection();
1554 if (translatedIndexes.isEmpty()) {
1555 qDebug() << "Model::handleMarkAsNotJunk: no valid messages";
1556 } else {
1557 if (value) {
1558 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::junk, Imap::Mailbox::FLAG_REMOVE);
1560 imapModel()->setMessageFlags(translatedIndexes, Imap::Mailbox::FlagNames::notjunk, value ? Imap::Mailbox::FLAG_ADD : Imap::Mailbox::FLAG_REMOVE);
1564 void MainWindow::slotMoveToArchiveFailed(const QString &error)
1566 // XXX disable busy cursor
1567 QMessageBox::critical(this, tr("Failed to archive"), error);
1570 void MainWindow::handleMoveToArchive()
1572 const QModelIndexList translatedIndexes = translatedSelection();
1573 if (translatedIndexes.isEmpty()) {
1574 qDebug() << "Model::handleMoveToArchive: no valid messages";
1575 } else {
1576 auto archiveFolderName = m_settings->value(Common::SettingsNames::imapArchiveFolderName).toString();
1577 auto copyMoveMessagesTask = imapModel()->copyMoveMessages(
1578 archiveFolderName.isEmpty() ? Common::SettingsNames::imapDefaultArchiveFolderName : archiveFolderName,
1579 translatedIndexes, Imap::Mailbox::CopyMoveOperation::MOVE);
1580 connect(copyMoveMessagesTask, &Imap::Mailbox::ImapTask::failed, this, &MainWindow::slotMoveToArchiveFailed);
1585 void MainWindow::slotExpunge()
1587 imapModel()->expungeMailbox(qobject_cast<Imap::Mailbox::MsgListModel *>(m_imapAccess->msgListModel())->currentMailbox());
1590 void MainWindow::slotMarkCurrentMailboxRead()
1592 imapModel()->markMailboxAsRead(mboxTree->currentIndex());
1595 void MainWindow::slotCreateMailboxBelowCurrent()
1597 createMailboxBelow(mboxTree->currentIndex());
1600 void MainWindow::slotCreateTopMailbox()
1602 createMailboxBelow(QModelIndex());
1605 void MainWindow::createMailboxBelow(const QModelIndex &index)
1607 Imap::Mailbox::TreeItemMailbox *mboxPtr = index.isValid() ?
1608 dynamic_cast<Imap::Mailbox::TreeItemMailbox *>(
1609 Imap::Mailbox::Model::realTreeItem(index)) :
1612 Ui::CreateMailboxDialog ui;
1613 QDialog *dialog = new QDialog(this);
1614 ui.setupUi(dialog);
1616 dialog->setWindowTitle(mboxPtr ?
1617 tr("Create a Subfolder of %1").arg(mboxPtr->mailbox()) :
1618 tr("Create a Top-level Mailbox"));
1620 if (dialog->exec() == QDialog::Accepted) {
1621 QStringList parts;
1622 if (mboxPtr)
1623 parts << mboxPtr->mailbox();
1624 parts << ui.mailboxName->text();
1625 if (ui.otherMailboxes->isChecked())
1626 parts << QString();
1627 QString targetName = parts.join(mboxPtr ? mboxPtr->separator() : QString()); // FIXME: top-level separator
1628 imapModel()->createMailbox(targetName,
1629 ui.subscribe->isChecked() ?
1630 Imap::Mailbox::AutoSubscription::SUBSCRIBE :
1631 Imap::Mailbox::AutoSubscription::NO_EXPLICIT_SUBSCRIPTION
1636 void MainWindow::slotDeleteCurrentMailbox()
1638 if (! mboxTree->currentIndex().isValid())
1639 return;
1641 QModelIndex mailbox = Imap::deproxifiedIndex(mboxTree->currentIndex());
1642 Q_ASSERT(mailbox.isValid());
1643 QString name = mailbox.data(Imap::Mailbox::RoleMailboxName).toString();
1645 if (QMessageBox::question(this, tr("Delete Mailbox"),
1646 tr("Are you sure to delete mailbox %1?").arg(name),
1647 QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
1648 imapModel()->deleteMailbox(name);
1652 void MainWindow::updateMessageFlags()
1654 updateMessageFlagsOf(QModelIndex());
1657 void MainWindow::updateMessageFlagsOf(const QModelIndex &index)
1659 QModelIndexList indexes = index.isValid() ? QModelIndexList() << index : translatedSelection();
1660 const bool isValid = !indexes.isEmpty() &&
1661 // either we operate on the -already valided- selection or the index must be valid
1662 (!index.isValid() || index.data(Imap::Mailbox::RoleMessageUid).toUInt() > 0);
1663 const bool okToModify = imapModel()->isNetworkAvailable() && isValid;
1665 markAsRead->setEnabled(okToModify);
1666 markAsDeleted->setEnabled(okToModify);
1667 markAsFlagged->setEnabled(okToModify);
1668 markAsJunk->setEnabled(okToModify);
1669 markAsNotJunk->setEnabled(okToModify);
1671 // There's no point in moving from Archive to, well, Archive
1672 auto archiveFolderName = m_settings->value(Common::SettingsNames::imapArchiveFolderName).toString();
1673 if (archiveFolderName.isEmpty()) {
1674 archiveFolderName = Common::SettingsNames::imapDefaultArchiveFolderName;
1676 moveToArchive->setEnabled(okToModify &&
1677 std::any_of(indexes.cbegin(), indexes.cend(),
1678 [archiveFolderName](const QModelIndex &i) {
1679 return i.data(Imap::Mailbox::RoleMailboxName) != archiveFolderName;
1680 }));
1682 bool isRead = isValid,
1683 isDeleted = isValid,
1684 isFlagged = isValid,
1685 isJunk = isValid,
1686 isNotJunk = isValid;
1687 Q_FOREACH (const QModelIndex &i, indexes) {
1688 #define UPDATE_STATE(PROP) \
1689 if (is##PROP && !i.data(Imap::Mailbox::RoleMessageIsMarked##PROP).toBool()) \
1690 is##PROP = false;
1691 UPDATE_STATE(Read)
1692 UPDATE_STATE(Deleted)
1693 UPDATE_STATE(Flagged)
1694 UPDATE_STATE(Junk)
1695 UPDATE_STATE(NotJunk)
1696 #undef UPDATE_STATE
1698 markAsRead->setChecked(isRead);
1699 markAsDeleted->setChecked(isDeleted);
1700 markAsFlagged->setChecked(isFlagged);
1701 markAsJunk->setChecked(isJunk && !isNotJunk);
1702 markAsNotJunk->setChecked(isNotJunk && !isJunk);
1705 void MainWindow::updateActionsOnlineOffline(bool online)
1707 reloadMboxList->setEnabled(online);
1708 resyncMbox->setEnabled(online);
1709 expunge->setEnabled(online);
1710 createChildMailbox->setEnabled(online);
1711 createTopMailbox->setEnabled(online);
1712 deleteCurrentMailbox->setEnabled(online);
1713 m_actionMarkMailboxAsRead->setEnabled(online);
1714 updateMessageFlags();
1715 showImapCapabilities->setEnabled(online);
1716 if (!online) {
1717 m_replyGuess->setEnabled(false);
1718 m_replyPrivate->setEnabled(false);
1719 m_replyAll->setEnabled(false);
1720 m_replyAllButMe->setEnabled(false);
1721 m_replyList->setEnabled(false);
1722 m_forwardAsAttachment->setEnabled(false);
1726 void MainWindow::slotUpdateMessageActions()
1728 Composer::RecipientList dummy;
1729 m_replyPrivate->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_PRIVATE, senderIdentitiesModel(),
1730 m_messageWidget->messageView->currentMessage(), dummy));
1731 m_replyAllButMe->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_ALL_BUT_ME, senderIdentitiesModel(),
1732 m_messageWidget->messageView->currentMessage(), dummy));
1733 m_replyAll->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_ALL, senderIdentitiesModel(),
1734 m_messageWidget->messageView->currentMessage(), dummy));
1735 m_replyList->setEnabled(Composer::Util::replyRecipientList(Composer::REPLY_LIST, senderIdentitiesModel(),
1736 m_messageWidget->messageView->currentMessage(), dummy));
1737 m_replyGuess->setEnabled(m_replyPrivate->isEnabled() || m_replyAllButMe->isEnabled()
1738 || m_replyAll->isEnabled() || m_replyList->isEnabled());
1740 // Check the default reply mode
1741 // I suspect this is not going to work for everybody. Suggestions welcome...
1742 if (m_replyList->isEnabled()) {
1743 m_replyButton->setDefaultAction(m_replyList);
1744 } else if (m_replyAllButMe->isEnabled()) {
1745 m_replyButton->setDefaultAction(m_replyAllButMe);
1746 } else {
1747 m_replyButton->setDefaultAction(m_replyPrivate);
1750 m_forwardAsAttachment->setEnabled(m_messageWidget->messageView->currentMessage().isValid());
1753 void MainWindow::scrollMessageUp()
1755 m_messageWidget->area->ensureVisible(0, 0, 0, 0);
1758 void MainWindow::slotReplyTo()
1760 m_messageWidget->messageView->reply(this, Composer::REPLY_PRIVATE);
1763 void MainWindow::slotReplyAll()
1765 m_messageWidget->messageView->reply(this, Composer::REPLY_ALL);
1768 void MainWindow::slotReplyAllButMe()
1770 m_messageWidget->messageView->reply(this, Composer::REPLY_ALL_BUT_ME);
1773 void MainWindow::slotReplyList()
1775 m_messageWidget->messageView->reply(this, Composer::REPLY_LIST);
1778 void MainWindow::slotReplyGuess()
1780 if (m_replyButton->defaultAction() == m_replyAllButMe) {
1781 slotReplyAllButMe();
1782 } else if (m_replyButton->defaultAction() == m_replyAll) {
1783 slotReplyAll();
1784 } else if (m_replyButton->defaultAction() == m_replyList) {
1785 slotReplyList();
1786 } else {
1787 slotReplyTo();
1791 void MainWindow::slotForwardAsAttachment()
1793 m_messageWidget->messageView->forward(this, Composer::ForwardMode::FORWARD_AS_ATTACHMENT);
1796 void MainWindow::slotComposeMailUrl(const QUrl &url)
1798 ComposeWidget::warnIfMsaNotConfigured(ComposeWidget::createFromUrl(this, url), this);
1801 void MainWindow::slotManageContact(const QUrl &url)
1803 Imap::Message::MailAddress addr;
1804 if (!Imap::Message::MailAddress::fromUrl(addr, url, QStringLiteral("x-trojita-manage-contact")))
1805 return;
1807 Plugins::AddressbookPlugin *addressbook = pluginManager()->addressbook();
1808 if (!addressbook)
1809 return;
1811 addressbook->openContactWindow(addr.mailbox + QLatin1Char('@') + addr.host, addr.name);
1814 void MainWindow::invokeContactEditor()
1816 Plugins::AddressbookPlugin *addressbook = pluginManager()->addressbook();
1817 if (!addressbook)
1818 return;
1820 addressbook->openAddressbookWindow();
1823 /** @short Create an MSAFactory as per the settings */
1824 MSA::MSAFactory *MainWindow::msaFactory()
1826 using namespace Common;
1827 QString method = m_settings->value(SettingsNames::msaMethodKey).toString();
1828 MSA::MSAFactory *msaFactory = 0;
1829 if (method == SettingsNames::methodSMTP || method == SettingsNames::methodSSMTP) {
1830 msaFactory = new MSA::SMTPFactory(m_settings->value(SettingsNames::smtpHostKey).toString(),
1831 m_settings->value(SettingsNames::smtpPortKey).toInt(),
1832 (method == SettingsNames::methodSSMTP),
1833 (method == SettingsNames::methodSMTP)
1834 && m_settings->value(SettingsNames::smtpStartTlsKey).toBool(),
1835 m_settings->value(SettingsNames::smtpAuthKey).toBool(),
1836 m_settings->value(SettingsNames::smtpAuthReuseImapCredsKey, false).toBool() ?
1837 m_settings->value(SettingsNames::imapUserKey).toString() :
1838 m_settings->value(SettingsNames::smtpUserKey).toString());
1839 } else if (method == SettingsNames::methodSENDMAIL) {
1840 QStringList args = m_settings->value(SettingsNames::sendmailKey, SettingsNames::sendmailDefaultCmd).toString().split(QLatin1Char(' '));
1841 if (args.isEmpty()) {
1842 return 0;
1844 QString appName = args.takeFirst();
1845 msaFactory = new MSA::SendmailFactory(appName, args);
1846 } else if (method == SettingsNames::methodImapSendmail) {
1847 if (!imapModel()->capabilities().contains(QStringLiteral("X-DRAFT-I01-SENDMAIL"))) {
1848 return 0;
1850 msaFactory = new MSA::ImapSubmitFactory(qobject_cast<Imap::Mailbox::Model*>(imapAccess()->imapModel()));
1851 } else {
1852 return 0;
1854 return msaFactory;
1857 void MainWindow::slotMailboxDeleteFailed(const QString &mailbox, const QString &msg)
1859 Gui::Util::messageBoxWarning(this, tr("Can't delete mailbox"),
1860 tr("Deleting mailbox \"%1\" failed with the following message:\n%2").arg(mailbox, msg));
1863 void MainWindow::slotMailboxCreateFailed(const QString &mailbox, const QString &msg)
1865 Gui::Util::messageBoxWarning(this, tr("Can't create mailbox"),
1866 tr("Creating mailbox \"%1\" failed with the following message:\n%2").arg(mailbox, msg));
1869 void MainWindow::slotMailboxSyncFailed(const QString &mailbox, const QString &msg)
1871 Gui::Util::messageBoxWarning(this, tr("Can't open mailbox"),
1872 tr("Opening mailbox \"%1\" failed with the following message:\n%2").arg(mailbox, msg));
1875 void MainWindow::slotMailboxChanged(const QModelIndex &mailbox)
1877 using namespace Imap::Mailbox;
1878 QString mailboxName = mailbox.data(RoleMailboxName).toString();
1879 bool isSentMailbox = mailbox.isValid() && !mailboxName.isEmpty() &&
1880 m_settings->value(Common::SettingsNames::composerSaveToImapKey).toBool() &&
1881 mailboxName == m_settings->value(Common::SettingsNames::composerImapSentKey).toString();
1882 QTreeView *tree = msgListWidget->tree;
1884 // Automatically trigger visibility of the TO and FROM columns
1885 if (isSentMailbox) {
1886 if (tree->isColumnHidden(MsgListModel::TO) && !tree->isColumnHidden(MsgListModel::FROM)) {
1887 tree->hideColumn(MsgListModel::FROM);
1888 tree->showColumn(MsgListModel::TO);
1890 } else {
1891 if (tree->isColumnHidden(MsgListModel::FROM) && !tree->isColumnHidden(MsgListModel::TO)) {
1892 tree->hideColumn(MsgListModel::TO);
1893 tree->showColumn(MsgListModel::FROM);
1897 updateMessageFlags();
1898 slotScrollToUnseenMessage();
1901 void MainWindow::showConnectionStatus(uint parserId, Imap::ConnectionState state)
1903 Q_UNUSED(parserId);
1904 static Imap::ConnectionState previousState = Imap::ConnectionState::CONN_STATE_NONE;
1905 QString message = connectionStateToString(state);
1907 if (state == Imap::ConnectionState::CONN_STATE_SELECTED && previousState >= Imap::ConnectionState::CONN_STATE_SELECTED) {
1908 // prevent excessive popups when we "reset the state" to something which is shown quite often
1909 showStatusMessage(QString());
1910 } else {
1911 showStatusMessage(message);
1913 previousState = state;
1916 void MainWindow::slotShowLinkTarget(const QString &link)
1918 if (link.isEmpty()) {
1919 QToolTip::hideText();
1920 } else {
1921 QToolTip::showText(QCursor::pos(), tr("Link target: %1").arg(UiUtils::Formatting::htmlEscaped(link)));
1925 void MainWindow::slotShowAboutTrojita()
1927 Ui::AboutDialog ui;
1928 QDialog *widget = new QDialog(this);
1929 widget->setAttribute(Qt::WA_DeleteOnClose);
1930 ui.setupUi(widget);
1931 ui.versionLabel->setText(Common::Application::version);
1932 ui.qtVersion->setText(QStringLiteral("<a href=\"about-qt\">Qt " QT_VERSION_STR "</a>"));
1933 connect(ui.qtVersion, &QLabel::linkActivated, qApp, &QApplication::aboutQt);
1935 std::vector<std::pair<QString, bool>> features;
1936 features.emplace_back(tr("Plugins"),
1937 #ifdef WITH_SHARED_PLUGINS
1938 true
1939 #else
1940 false
1941 #endif
1943 features.emplace_back(tr("Encrypted and signed messages"),
1944 #ifdef TROJITA_HAVE_CRYPTO_MESSAGES
1945 true
1946 #else
1947 false
1948 #endif
1950 features.emplace_back(tr("IMAP compression"),
1951 #ifdef TROJITA_HAVE_ZLIB
1952 true
1953 #else
1954 false
1955 #endif
1958 QString featuresText = QStringLiteral("<ul>");
1959 for (const auto x: features) {
1960 featuresText += x.second ?
1961 tr("<li>%1: supported</li>").arg(x.first)
1962 : tr("<li>%1: <strong>disabled</strong></li>").arg(x.first);
1964 featuresText += QStringLiteral("</ul>");
1965 ui.descriptionLabel->setText(ui.descriptionLabel->text() + featuresText);
1967 QStringList copyright;
1969 // Find the names of the authors and remove date codes from there
1970 QFile license(QStringLiteral(":/LICENSE"));
1971 license.open(QFile::ReadOnly);
1972 const QString prefix(QStringLiteral("Copyright (C) "));
1973 Q_FOREACH(const QString &line, QString::fromUtf8(license.readAll()).split(QLatin1Char('\n'))) {
1974 if (line.startsWith(prefix)) {
1975 const int pos = prefix.size();
1976 copyright << QChar(0xa9 /* COPYRIGHT SIGN */) + QLatin1Char(' ') +
1977 line.mid(pos).replace(QRegExp(QLatin1String("(\\d) - (\\d)")),
1978 QLatin1String("\\1") + QChar(0x2014 /* EM DASH */) + QLatin1String("\\2"));
1982 ui.credits->setTextFormat(Qt::PlainText);
1983 ui.credits->setText(copyright.join(QStringLiteral("\n")));
1984 widget->show();
1987 void MainWindow::slotDonateToTrojita()
1989 QDesktopServices::openUrl(QStringLiteral("https://sourceforge.net/p/trojita/donate/"));
1992 void MainWindow::slotSaveCurrentMessageBody()
1994 Q_FOREACH(const QModelIndex &item, msgListWidget->tree->selectionModel()->selectedIndexes()) {
1995 Q_ASSERT(item.isValid());
1996 if (item.column() != 0)
1997 continue;
1998 if (! item.data(Imap::Mailbox::RoleMessageUid).isValid())
1999 continue;
2001 QModelIndex messageIndex = Imap::deproxifiedIndex(item);
2003 Imap::Network::MsgPartNetAccessManager *netAccess = new Imap::Network::MsgPartNetAccessManager(this);
2004 netAccess->setModelMessage(messageIndex);
2005 Imap::Network::FileDownloadManager *fileDownloadManager =
2006 new Imap::Network::FileDownloadManager(this, netAccess, messageIndex);
2007 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::succeeded, fileDownloadManager, &QObject::deleteLater);
2008 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::transferError, fileDownloadManager, &QObject::deleteLater);
2009 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::fileNameRequested,
2010 this, &MainWindow::slotDownloadMessageFileNameRequested);
2011 connect(fileDownloadManager, &Imap::Network::FileDownloadManager::transferError,
2012 this, &MainWindow::slotDownloadTransferError);
2013 connect(fileDownloadManager, &QObject::destroyed, netAccess, &QObject::deleteLater);
2014 fileDownloadManager->downloadMessage();
2018 void MainWindow::slotDownloadTransferError(const QString &errorString)
2020 Gui::Util::messageBoxCritical(this, tr("Can't save into file"),
2021 tr("Unable to save into file. Error:\n%1").arg(errorString));
2024 void MainWindow::slotDownloadMessageFileNameRequested(QString *fileName)
2026 *fileName = QFileDialog::getSaveFileName(this, tr("Save Message"), *fileName, QString(), 0,
2027 QFileDialog::HideNameFilterDetails);
2030 void MainWindow::slotViewMsgSource()
2032 Q_FOREACH(const QModelIndex &item, msgListWidget->tree->selectionModel()->selectedIndexes()) {
2033 Q_ASSERT(item.isValid());
2034 if (item.column() != 0)
2035 continue;
2036 if (! item.data(Imap::Mailbox::RoleMessageUid).isValid())
2037 continue;
2038 auto w = messageSourceWidget(item);
2039 //: Translators: %1 is the UID of a message (a number) and %2 is the name of a mailbox.
2040 w->setWindowTitle(tr("Message source of UID %1 in %2").arg(
2041 QString::number(item.data(Imap::Mailbox::RoleMessageUid).toUInt()),
2042 Imap::deproxifiedIndex(item).parent().parent().data(Imap::Mailbox::RoleMailboxName).toString()
2044 w->show();
2048 QWidget *MainWindow::messageSourceWidget(const QModelIndex &message)
2050 QModelIndex messageIndex = Imap::deproxifiedIndex(message);
2051 MessageSourceWidget *sourceWidget = new MessageSourceWidget(0, messageIndex);
2052 sourceWidget->setAttribute(Qt::WA_DeleteOnClose);
2053 QAction *close = new QAction(UiUtils::loadIcon(QStringLiteral("window-close")), tr("Close"), sourceWidget);
2054 sourceWidget->addAction(close);
2055 close->setShortcut(tr("Ctrl+W"));
2056 connect(close, &QAction::triggered, sourceWidget, &QWidget::close);
2057 return sourceWidget;
2060 void MainWindow::slotViewMsgHeaders()
2062 Q_FOREACH(const QModelIndex &item, msgListWidget->tree->selectionModel()->selectedIndexes()) {
2063 Q_ASSERT(item.isValid());
2064 if (item.column() != 0)
2065 continue;
2066 if (! item.data(Imap::Mailbox::RoleMessageUid).isValid())
2067 continue;
2068 QModelIndex messageIndex = Imap::deproxifiedIndex(item);
2070 auto widget = new MessageHeadersWidget(nullptr, messageIndex);
2071 widget->setAttribute(Qt::WA_DeleteOnClose);
2072 QAction *close = new QAction(UiUtils::loadIcon(QStringLiteral("window-close")), tr("Close"), widget);
2073 widget->addAction(close);
2074 close->setShortcut(tr("Ctrl+W"));
2075 connect(close, &QAction::triggered, widget, &QWidget::close);
2076 widget->show();
2080 #ifdef XTUPLE_CONNECT
2081 void MainWindow::slotXtSyncCurrentMailbox()
2083 QModelIndex index = mboxTree->currentIndex();
2084 if (! index.isValid())
2085 return;
2087 QString mailbox = index.data(Imap::Mailbox::RoleMailboxName).toString();
2088 QSettings s;
2089 QStringList mailboxes = s.value(Common::SettingsNames::xtSyncMailboxList).toStringList();
2090 if (xtIncludeMailboxInSync->isChecked()) {
2091 if (! mailboxes.contains(mailbox)) {
2092 mailboxes.append(mailbox);
2094 } else {
2095 mailboxes.removeAll(mailbox);
2097 s.setValue(Common::SettingsNames::xtSyncMailboxList, mailboxes);
2098 QSettings(QSettings::UserScope, QString::fromAscii("xTuple.com"), QString::fromAscii("xTuple")).setValue(Common::SettingsNames::xtSyncMailboxList, mailboxes);
2099 prettyMboxModel->xtConnectStatusChanged(index);
2101 #endif
2103 void MainWindow::slotSubscribeCurrentMailbox()
2105 QModelIndex index = mboxTree->currentIndex();
2106 if (! index.isValid())
2107 return;
2109 QString mailbox = index.data(Imap::Mailbox::RoleMailboxName).toString();
2110 if (m_actionSubscribeMailbox->isChecked()) {
2111 imapModel()->subscribeMailbox(mailbox);
2112 } else {
2113 imapModel()->unsubscribeMailbox(mailbox);
2117 void MainWindow::slotShowOnlySubscribed()
2119 if (m_actionShowOnlySubscribed->isEnabled()) {
2120 m_settings->setValue(Common::SettingsNames::guiMailboxListShowOnlySubscribed, m_actionShowOnlySubscribed->isChecked());
2121 prettyMboxModel->setShowOnlySubscribed(m_actionShowOnlySubscribed->isChecked());
2125 void MainWindow::slotScrollToUnseenMessage()
2127 // Now this is much, much more reliable than messing around with finding out an "interesting message"...
2128 if (!m_actionSortNone->isChecked() && !m_actionSortThreading->isChecked()) {
2129 // we're using some funky sorting, better don't scroll anywhere
2131 if (m_actionSortDescending->isChecked()) {
2132 msgListWidget->tree->scrollToTop();
2133 } else {
2134 msgListWidget->tree->scrollToBottom();
2138 void MainWindow::slotScrollToCurrent()
2140 // TODO: begs for lambda
2141 if (QScrollBar *vs = msgListWidget->tree->verticalScrollBar()) {
2142 vs->setValue(vs->maximum() - vs->value()); // implies vs->minimum() == 0
2146 void MainWindow::slotThreadMsgList()
2148 // We want to save user's preferences and not override them with "threading disabled" when the server
2149 // doesn't report them, like in initial greetings. That's why we have to check for isEnabled() here.
2150 const bool useThreading = actionThreadMsgList->isChecked();
2152 // Switching between threaded/unthreaded view shall reset the sorting criteria. The goal is to make
2153 // sorting rather seldomly used as people shall instead use proper threading.
2154 if (useThreading) {
2155 m_actionSortThreading->setEnabled(true);
2156 if (!m_actionSortThreading->isChecked())
2157 m_actionSortThreading->trigger();
2158 m_actionSortNone->setEnabled(false);
2159 } else {
2160 m_actionSortNone->setEnabled(true);
2161 if (!m_actionSortNone->isChecked())
2162 m_actionSortNone->trigger();
2163 m_actionSortThreading->setEnabled(false);
2166 QPersistentModelIndex currentItem = msgListWidget->tree->currentIndex();
2168 if (useThreading && actionThreadMsgList->isEnabled()) {
2169 msgListWidget->tree->setRootIsDecorated(true);
2170 qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(m_imapAccess->threadingMsgListModel())->setUserWantsThreading(true);
2171 } else {
2172 msgListWidget->tree->setRootIsDecorated(false);
2173 qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(m_imapAccess->threadingMsgListModel())->setUserWantsThreading(false);
2175 m_settings->setValue(Common::SettingsNames::guiMsgListShowThreading, QVariant(useThreading));
2177 if (currentItem.isValid()) {
2178 msgListWidget->tree->scrollTo(currentItem);
2179 } else {
2180 // If we cannot determine the current item, at least scroll to a predictable place. Without this, the view
2181 // would jump to "weird" places, probably due to some heuristics about trying to show "roughly the same"
2182 // objects as what was visible before the reshuffling.
2183 slotScrollToUnseenMessage();
2187 void MainWindow::slotSortingPreferenceChanged()
2189 Qt::SortOrder order = m_actionSortDescending->isChecked() ? Qt::DescendingOrder : Qt::AscendingOrder;
2191 using namespace Imap::Mailbox;
2193 int column = -1;
2194 if (m_actionSortByArrival->isChecked()) {
2195 column = MsgListModel::RECEIVED_DATE;
2196 } else if (m_actionSortByCc->isChecked()) {
2197 column = MsgListModel::CC;
2198 } else if (m_actionSortByDate->isChecked()) {
2199 column = MsgListModel::DATE;
2200 } else if (m_actionSortByFrom->isChecked()) {
2201 column = MsgListModel::FROM;
2202 } else if (m_actionSortBySize->isChecked()) {
2203 column = MsgListModel::SIZE;
2204 } else if (m_actionSortBySubject->isChecked()) {
2205 column = MsgListModel::SUBJECT;
2206 } else if (m_actionSortByTo->isChecked()) {
2207 column = MsgListModel::TO;
2208 } else {
2209 column = -1;
2212 msgListWidget->tree->header()->setSortIndicator(column, order);
2215 void MainWindow::slotSortingConfirmed(int column, Qt::SortOrder order)
2217 // don't do anything during initialization
2218 if (!m_actionSortNone)
2219 return;
2221 using namespace Imap::Mailbox;
2222 QAction *action;
2224 switch (column) {
2225 case MsgListModel::SEEN:
2226 case MsgListModel::FLAGGED:
2227 case MsgListModel::ATTACHMENT:
2228 case MsgListModel::COLUMN_COUNT:
2229 case MsgListModel::BCC:
2230 case -1:
2231 if (actionThreadMsgList->isChecked())
2232 action = m_actionSortThreading;
2233 else
2234 action = m_actionSortNone;
2235 break;
2236 case MsgListModel::SUBJECT:
2237 action = m_actionSortBySubject;
2238 break;
2239 case MsgListModel::FROM:
2240 action = m_actionSortByFrom;
2241 break;
2242 case MsgListModel::TO:
2243 action = m_actionSortByTo;
2244 break;
2245 case MsgListModel::CC:
2246 action = m_actionSortByCc;
2247 break;
2248 case MsgListModel::DATE:
2249 action = m_actionSortByDate;
2250 break;
2251 case MsgListModel::RECEIVED_DATE:
2252 action = m_actionSortByArrival;
2253 break;
2254 case MsgListModel::SIZE:
2255 action = m_actionSortBySize;
2256 break;
2257 default:
2258 action = m_actionSortNone;
2261 action->setChecked(true);
2262 if (order == Qt::DescendingOrder)
2263 m_actionSortDescending->setChecked(true);
2264 else
2265 m_actionSortAscending->setChecked(true);
2268 void MainWindow::slotSearchRequested(const QStringList &searchConditions)
2270 if (!searchConditions.isEmpty() && actionThreadMsgList->isChecked()) {
2271 // right now, searching and threading doesn't play well together at all
2272 actionThreadMsgList->trigger();
2274 Imap::Mailbox::ThreadingMsgListModel * threadingMsgListModel =
2275 qobject_cast<Imap::Mailbox::ThreadingMsgListModel *>(m_imapAccess->threadingMsgListModel());
2276 threadingMsgListModel->setUserSearchingSortingPreference(searchConditions, threadingMsgListModel->currentSortCriterium(),
2277 threadingMsgListModel->currentSortOrder());
2280 void MainWindow::slotHideRead()
2282 const bool hideRead = actionHideRead->isChecked();
2283 prettyMsgListModel->setHideRead(hideRead);
2284 m_settings->setValue(Common::SettingsNames::guiMsgListHideRead, QVariant(hideRead));
2287 void MainWindow::slotCapabilitiesUpdated(const QStringList &capabilities)
2289 msgListWidget->tree->header()->viewport()->removeEventFilter(this);
2290 if (capabilities.contains(QStringLiteral("SORT"))) {
2291 m_actionSortByDate->actionGroup()->setEnabled(true);
2292 } else {
2293 m_actionSortByDate->actionGroup()->setEnabled(false);
2294 msgListWidget->tree->header()->viewport()->installEventFilter(this);
2297 msgListWidget->setFuzzySearchSupported(capabilities.contains(QStringLiteral("SEARCH=FUZZY")));
2299 m_actionShowOnlySubscribed->setEnabled(capabilities.contains(QStringLiteral("LIST-EXTENDED")));
2300 m_actionShowOnlySubscribed->setChecked(m_actionShowOnlySubscribed->isEnabled() &&
2301 m_settings->value(
2302 Common::SettingsNames::guiMailboxListShowOnlySubscribed, false).toBool());
2303 m_actionSubscribeMailbox->setEnabled(m_actionShowOnlySubscribed->isEnabled());
2305 const QStringList supportedCapabilities = Imap::Mailbox::ThreadingMsgListModel::supportedCapabilities();
2306 Q_FOREACH(const QString &capability, capabilities) {
2307 if (supportedCapabilities.contains(capability)) {
2308 actionThreadMsgList->setEnabled(true);
2309 if (actionThreadMsgList->isChecked())
2310 slotThreadMsgList();
2311 return;
2314 actionThreadMsgList->setEnabled(false);
2317 void MainWindow::slotShowImapInfo()
2319 QString caps;
2320 Q_FOREACH(const QString &cap, imapModel()->capabilities()) {
2321 caps += tr("<li>%1</li>\n").arg(cap);
2324 QString idString;
2325 if (!imapModel()->serverId().isEmpty() && imapModel()->capabilities().contains(QStringLiteral("ID"))) {
2326 QMap<QByteArray,QByteArray> serverId = imapModel()->serverId();
2328 #define IMAP_ID_FIELD(Var, Name) bool has_##Var = serverId.contains(Name); \
2329 QString Var = has_##Var ? QString::fromUtf8(serverId[Name]).toHtmlEscaped() : tr("Unknown");
2330 IMAP_ID_FIELD(serverName, "name");
2331 IMAP_ID_FIELD(serverVersion, "version");
2332 IMAP_ID_FIELD(os, "os");
2333 IMAP_ID_FIELD(osVersion, "os-version");
2334 IMAP_ID_FIELD(vendor, "vendor");
2335 IMAP_ID_FIELD(supportUrl, "support-url");
2336 IMAP_ID_FIELD(address, "address");
2337 IMAP_ID_FIELD(date, "date");
2338 IMAP_ID_FIELD(command, "command");
2339 IMAP_ID_FIELD(arguments, "arguments");
2340 IMAP_ID_FIELD(environment, "environment");
2341 #undef IMAP_ID_FIELD
2342 if (has_serverName) {
2343 idString = tr("<p>");
2344 if (has_serverVersion)
2345 idString += tr("Server: %1 %2").arg(serverName, serverVersion);
2346 else
2347 idString += tr("Server: %1").arg(serverName);
2349 if (has_vendor) {
2350 idString += tr(" (%1)").arg(vendor);
2352 if (has_os) {
2353 if (has_osVersion)
2354 idString += tr(" on %1 %2", "%1 is the operating system of an IMAP server and %2 is its version.").arg(os, osVersion);
2355 else
2356 idString += tr(" on %1", "%1 is the operationg system of an IMAP server.").arg(os);
2358 idString += tr("</p>");
2359 } else {
2360 idString = tr("<p>The IMAP server did not return usable information about itself.</p>");
2362 QString fullId;
2363 for (QMap<QByteArray,QByteArray>::const_iterator it = serverId.constBegin(); it != serverId.constEnd(); ++it) {
2364 fullId += tr("<li>%1: %2</li>").arg(QString::fromUtf8(it.key()).toHtmlEscaped(), QString::fromUtf8(it.value()).toHtmlEscaped());
2366 idString += tr("<ul>%1</ul>").arg(fullId);
2367 } else {
2368 idString = tr("<p>The server has not provided information about its software version.</p>");
2371 QMessageBox::information(this, tr("IMAP Server Information"),
2372 tr("%1"
2373 "<p>The following capabilities are currently advertised:</p>\n"
2374 "<ul>\n%2</ul>").arg(idString, caps));
2377 QSize MainWindow::sizeHint() const
2379 return QSize(1150, 980);
2382 void MainWindow::slotUpdateWindowTitle()
2384 QModelIndex mailbox = qobject_cast<Imap::Mailbox::MsgListModel *>(m_imapAccess->msgListModel())->currentMailbox();
2385 QString profileName = QString::fromUtf8(qgetenv("TROJITA_PROFILE"));
2386 if (!profileName.isEmpty())
2387 profileName = QLatin1String(" [") + profileName + QLatin1Char(']');
2388 if (mailbox.isValid()) {
2389 if (mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt()) {
2390 setWindowTitle(trUtf8("%1 - %n unread - Trojitá", 0, mailbox.data(Imap::Mailbox::RoleUnreadMessageCount).toInt())
2391 .arg(mailbox.data(Imap::Mailbox::RoleShortMailboxName).toString()) + profileName);
2392 } else {
2393 setWindowTitle(trUtf8("%1 - Trojitá").arg(mailbox.data(Imap::Mailbox::RoleShortMailboxName).toString()) + profileName);
2395 } else {
2396 setWindowTitle(trUtf8("Trojitá") + profileName);
2400 void MainWindow::slotLayoutCompact()
2402 saveSizesAndState();
2403 if (!m_mainHSplitter) {
2404 m_mainHSplitter = new QSplitter();
2405 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
2406 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, this, &MainWindow::possiblyLoadMessageOnSplittersChanged);
2408 if (!m_mainVSplitter) {
2409 m_mainVSplitter = new QSplitter();
2410 m_mainVSplitter->setOrientation(Qt::Vertical);
2411 connect(m_mainVSplitter.data(), &QSplitter::splitterMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
2412 connect(m_mainVSplitter.data(), &QSplitter::splitterMoved, this, &MainWindow::possiblyLoadMessageOnSplittersChanged);
2415 m_mainVSplitter->addWidget(msgListWidget);
2416 m_mainVSplitter->addWidget(m_messageWidget);
2417 m_mainHSplitter->addWidget(mboxTree);
2418 m_mainHSplitter->addWidget(m_mainVSplitter);
2420 mboxTree->show();
2421 msgListWidget->show();
2422 m_messageWidget->show();
2423 m_mainVSplitter->show();
2424 m_mainHSplitter->show();
2426 // The mboxTree shall not expand...
2427 m_mainHSplitter->setStretchFactor(0, 0);
2428 // ...while the msgListTree shall consume all the remaining space
2429 m_mainHSplitter->setStretchFactor(1, 1);
2430 // The CompleteMessageWidget shall not not collapse
2431 m_mainVSplitter->setCollapsible(m_mainVSplitter->indexOf(m_messageWidget), false);
2433 setCentralWidget(m_mainHSplitter);
2435 delete m_mainStack;
2437 m_layoutMode = LAYOUT_COMPACT;
2438 m_settings->setValue(Common::SettingsNames::guiMainWindowLayout, Common::SettingsNames::guiMainWindowLayoutCompact);
2439 applySizesAndState();
2442 void MainWindow::slotLayoutWide()
2444 saveSizesAndState();
2445 if (!m_mainHSplitter) {
2446 m_mainHSplitter = new QSplitter();
2447 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, m_delayedStateSaving, static_cast<void (QTimer::*)()>(&QTimer::start));
2448 connect(m_mainHSplitter.data(), &QSplitter::splitterMoved, this, &MainWindow::possiblyLoadMessageOnSplittersChanged);
2451 m_mainHSplitter->addWidget(mboxTree);
2452 m_mainHSplitter->addWidget(msgListWidget);
2453 m_mainHSplitter->addWidget(m_messageWidget);
2454 msgListWidget->resize(mboxTree->size());
2455 m_messageWidget->resize(mboxTree->size());
2456 m_mainHSplitter->setStretchFactor(0, 0);
2457 m_mainHSplitter->setStretchFactor(1, 1);
2458 m_mainHSplitter->setStretchFactor(2, 1);
2460 m_mainHSplitter->setCollapsible(m_mainHSplitter->indexOf(m_messageWidget), false);
2462 mboxTree->show();
2463 msgListWidget->show();
2464 m_messageWidget->show();
2465 m_mainHSplitter->show();
2467 setCentralWidget(m_mainHSplitter);
2469 delete m_mainStack;
2470 delete m_mainVSplitter;
2472 m_layoutMode = LAYOUT_WIDE;
2473 m_settings->setValue(Common::SettingsNames::guiMainWindowLayout, Common::SettingsNames::guiMainWindowLayoutWide);
2474 applySizesAndState();
2477 void MainWindow::slotLayoutOneAtTime()
2479 saveSizesAndState();
2480 if (m_mainStack)
2481 return;
2483 m_mainStack = new OnePanelAtTimeWidget(this, mboxTree, msgListWidget, m_messageWidget, m_mainToolbar, m_oneAtTimeGoBack);
2484 setCentralWidget(m_mainStack);
2486 delete m_mainHSplitter;
2487 delete m_mainVSplitter;
2489 m_layoutMode = LAYOUT_ONE_AT_TIME;
2490 m_settings->setValue(Common::SettingsNames::guiMainWindowLayout, Common::SettingsNames::guiMainWindowLayoutOneAtTime);
2491 applySizesAndState();
2494 Imap::Mailbox::Model *MainWindow::imapModel() const
2496 return qobject_cast<Imap::Mailbox::Model *>(m_imapAccess->imapModel());
2499 void MainWindow::desktopGeometryChanged()
2501 m_delayedStateSaving->start();
2504 QString MainWindow::settingsKeyForLayout(const LayoutMode layout)
2506 switch (layout) {
2507 case LAYOUT_COMPACT:
2508 return Common::SettingsNames::guiSizesInMainWinWhenCompact;
2509 case LAYOUT_WIDE:
2510 return Common::SettingsNames::guiSizesInMainWinWhenWide;
2511 case LAYOUT_ONE_AT_TIME:
2512 return Common::SettingsNames::guiSizesInaMainWinWhenOneAtATime;
2513 break;
2515 return QString();
2518 void MainWindow::saveSizesAndState()
2520 if (m_skipSavingOfUI)
2521 return;
2523 QRect geometry = qApp->desktop()->availableGeometry(this);
2524 QString key = settingsKeyForLayout(m_layoutMode);
2525 if (key.isEmpty())
2526 return;
2528 QList<QByteArray> items;
2529 items << saveGeometry();
2530 items << saveState();
2531 items << (m_mainVSplitter ? m_mainVSplitter->saveState() : QByteArray());
2532 items << (m_mainHSplitter ? m_mainHSplitter->saveState() : QByteArray());
2533 items << msgListWidget->tree->header()->saveState();
2534 items << QByteArray::number(msgListWidget->tree->header()->count());
2535 for (int i = 0; i < msgListWidget->tree->header()->count(); ++i) {
2536 items << QByteArray::number(msgListWidget->tree->header()->sectionSize(i));
2538 // a bool cannot be pushed directly onto a QByteArray so we must convert it to a number
2539 items << QByteArray::number(menuBar()->isVisible());
2540 QByteArray buf;
2541 QDataStream stream(&buf, QIODevice::WriteOnly);
2542 stream << items.size();
2543 Q_FOREACH(const QByteArray &item, items) {
2544 stream << item;
2547 m_settings->setValue(key.arg(QString::number(geometry.width())), buf);
2550 void MainWindow::saveRawStateSetting(bool enabled)
2552 m_settings->setValue(Common::SettingsNames::guiAllowRawSearch, enabled);
2555 void MainWindow::applySizesAndState()
2557 QRect geometry = qApp->desktop()->availableGeometry(this);
2558 QString key = settingsKeyForLayout(m_layoutMode);
2559 if (key.isEmpty())
2560 return;
2562 QByteArray buf = m_settings->value(key.arg(QString::number(geometry.width()))).toByteArray();
2563 if (buf.isEmpty())
2564 return;
2566 int size;
2567 QDataStream stream(&buf, QIODevice::ReadOnly);
2568 stream >> size;
2569 QByteArray item;
2571 // There are slots connected to various events triggered by both restoreGeometry() and restoreState() which would attempt to
2572 // save our geometries and state, which is what we must avoid while this method is executing.
2573 bool skipSaving = m_skipSavingOfUI;
2574 m_skipSavingOfUI = true;
2576 if (size-- && !stream.atEnd()) {
2577 stream >> item;
2579 // https://bugreports.qt-project.org/browse/QTBUG-30636
2580 if (windowState() & Qt::WindowMaximized) {
2581 // restoreGeometry(.) restores the wrong size for at least maximized window
2582 // However, QWidget does also not notice that the configure request for this
2583 // is ignored by many window managers (because users really don't like when windows
2584 // drop themselves out of maximization) and has a wrong QWidget::geometry() idea from
2585 // the wrong assumption the request would have been hononred.
2586 // So we just "fix" the internal geometry immediately afterwards to prevent
2587 // mislayouting
2588 // There's atm. no flicker due to this (and because Qt compresses events)
2589 // In case it ever occurs, we can frame this in setUpdatesEnabled(false/true)
2590 QRect oldGeometry = MainWindow::geometry();
2591 restoreGeometry(item);
2592 if (windowState() & Qt::WindowMaximized)
2593 setGeometry(oldGeometry);
2594 } else {
2595 restoreGeometry(item);
2596 if (windowState() & Qt::WindowMaximized) {
2597 // ensure to try setting the proper geometry and have the WM constrain us
2598 setGeometry(QApplication::desktop()->availableGeometry());
2603 if (size-- && !stream.atEnd()) {
2604 stream >> item;
2605 restoreState(item);
2608 if (size-- && !stream.atEnd()) {
2609 stream >> item;
2610 if (m_mainVSplitter) {
2611 m_mainVSplitter->restoreState(item);
2615 if (size-- && !stream.atEnd()) {
2616 stream >> item;
2617 if (m_mainHSplitter) {
2618 m_mainHSplitter->restoreState(item);
2622 if (size-- && !stream.atEnd()) {
2623 stream >> item;
2624 msgListWidget->tree->header()->restoreState(item);
2625 // got to manually update the state of the actions which control the visibility state
2626 msgListWidget->tree->updateActionsAfterRestoredState();
2629 connect(msgListWidget->tree->header(), &QHeaderView::sectionCountChanged, msgListWidget->tree, &MsgListView::slotHandleNewColumns);
2631 if (size-- && !stream.atEnd()) {
2632 stream >> item;
2633 bool ok;
2634 int columns = item.toInt(&ok);
2635 if (ok) {
2636 msgListWidget->tree->header()->setStretchLastSection(false);
2637 for (int i = 0; i < columns && size-- && !stream.atEnd(); ++i) {
2638 stream >> item;
2639 int sectionSize = item.toInt();
2640 QHeaderView::ResizeMode resizeMode = msgListWidget->tree->resizeModeForColumn(i);
2641 if (sectionSize > 0 && resizeMode == QHeaderView::Interactive) {
2642 // fun fact: user cannot resize by mouse when size <= 0
2643 msgListWidget->tree->setColumnWidth(i, sectionSize);
2644 } else {
2645 msgListWidget->tree->setColumnWidth(i, msgListWidget->tree->sizeHintForColumn(i));
2647 msgListWidget->tree->header()->setSectionResizeMode(i, resizeMode);
2652 if (size-- && !stream.atEnd()) {
2653 stream >> item;
2654 bool ok;
2655 bool visibility = item.toInt(&ok);
2656 if (ok) {
2657 menuBar()->setVisible(visibility);
2658 showMenuBar->setChecked(visibility);
2662 m_skipSavingOfUI = skipSaving;
2665 void MainWindow::resizeEvent(QResizeEvent *)
2667 m_delayedStateSaving->start();
2670 /** @short Make sure that the message gets loaded after the splitters have changed their position */
2671 void MainWindow::possiblyLoadMessageOnSplittersChanged()
2673 if (m_messageWidget->isVisible() && !m_messageWidget->size().isEmpty()) {
2674 // We do not have to check whether it's a different message; the setMessage() will do this or us
2675 // and there are multiple proxy models involved anyway
2676 QModelIndex index = msgListWidget->tree->currentIndex();
2677 if (index.isValid()) {
2678 // OTOH, setting an invalid QModelIndex would happily assert-fail
2679 m_messageWidget->messageView->setMessage(msgListWidget->tree->currentIndex());
2684 Imap::ImapAccess *MainWindow::imapAccess() const
2686 return m_imapAccess;
2689 void MainWindow::enableLoggingToDisk()
2691 imapLogger->slotSetPersistentLogging(true);
2694 void MainWindow::slotPluginsChanged()
2696 Plugins::AddressbookPlugin *addressbook = pluginManager()->addressbook();
2697 if (!addressbook || !(addressbook->features() & Plugins::AddressbookPlugin::FeatureAddressbookWindow))
2698 m_actionContactEditor->setEnabled(false);
2699 else
2700 m_actionContactEditor->setEnabled(true);
2703 /** @short Update the default action to make sure that we show a correct status of the network connection */
2704 void MainWindow::updateNetworkIndication()
2706 if (QAction *action = qobject_cast<QAction*>(sender())) {
2707 if (action->isChecked()) {
2708 m_netToolbarDefaultAction->setIcon(action->icon());
2713 void MainWindow::showStatusMessage(const QString &message)
2715 networkIndicator->setToolTip(message);
2716 if (isActiveWindow())
2717 QToolTip::showText(networkIndicator->mapToGlobal(QPoint(0, 0)), message);
2720 void MainWindow::slotMessageModelChanged(QAbstractItemModel *model)
2722 mailMimeTree->setModel(model);