aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt1
-rw-r--r--src/config.h4
-rw-r--r--src/keymap.cpp9
-rw-r--r--src/mainwindow.cpp407
-rw-r--r--src/mainwindow.h101
-rw-r--r--src/syncmonitor.cpp151
-rw-r--r--src/syncmonitor.h106
7 files changed, 753 insertions, 26 deletions
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index 5214f42..a71a6f1 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -12,6 +12,7 @@ add_library(qtmaildir_lib STATIC
tagstrip.cpp
threadlistmodel.cpp
mailsync.cpp
+ syncmonitor.cpp
threadcidmap.cpp
messageview.cpp
mainwindow.cpp
diff --git a/src/config.h b/src/config.h
index ba9b7f6..84f02df 100644
--- a/src/config.h
+++ b/src/config.h
@@ -41,8 +41,8 @@ struct Account
QColor color;
/// Text shown on the chip. Empty falls back to the key, which can be long:
- /// "provider-work" is a lot of row for one bit of information.
- /// This renames nothing in notmuch, only what the chip displays.
+ /// a provider-plus-mailbox key of 25 characters is a lot of row for one
+ /// bit of information. This renames nothing in notmuch, only the display.
QString label;
bool isValid() const { return !key.isEmpty() && !maildir.isEmpty(); }
diff --git a/src/keymap.cpp b/src/keymap.cpp
index 0901cfb..f27f9a9 100644
--- a/src/keymap.cpp
+++ b/src/keymap.cpp
@@ -35,6 +35,8 @@ QStringList KeyMap::knownActions()
QStringLiteral("flag"),
QStringLiteral("focus_query"),
QStringLiteral("complete_query"),
+ QStringLiteral("select_all"),
+ QStringLiteral("clear_pane"),
QStringLiteral("toggle_html"),
QStringLiteral("load_remote"),
QStringLiteral("message_details"),
@@ -72,6 +74,13 @@ QList<QPair<QString, QString>> KeyMap::defaultBindings()
// shells and editors, and it is a named key rather than a symbol, so
// no layout has to shift it.
{ QStringLiteral("Ctrl+Space"), QStringLiteral("complete_query") },
+ // The conventional select-all key, and free here: the thread list is a
+ // read-only view, so nothing else in the window wants it.
+ { QStringLiteral("Ctrl+A"), QStringLiteral("select_all") },
+ // Escape is not claimed by anything else at window level. The query
+ // completer handles its own Escape while its popup is up, and a popup
+ // consumes the key before a window shortcut sees it.
+ { QStringLiteral("Esc"), QStringLiteral("clear_pane") },
{ QStringLiteral("Ctrl+H"), QStringLiteral("toggle_html") },
{ QStringLiteral("Ctrl+M"), QStringLiteral("load_remote") },
// Shifted because Ctrl+D is delete. Both are "D for details/delete"
diff --git a/src/mainwindow.cpp b/src/mainwindow.cpp
index 0a9f9d8..7cd2769 100644
--- a/src/mainwindow.cpp
+++ b/src/mainwindow.cpp
@@ -154,7 +154,7 @@ void MainWindow::closeEvent(QCloseEvent *event)
return;
}
- if (!m_closeApproved && m_pendingEdits > 0
+ if (!m_closeApproved && pendingEditCount() > 0
&& m_config.syncOnExit() != Config::SyncOnExit::Never) {
// Not a destructive-action confirmation, which CLAUDE.md forbids for
@@ -167,7 +167,7 @@ void MainWindow::closeEvent(QCloseEvent *event)
const auto answer = QMessageBox::warning(
this, tr("Unsynced changes"),
tr("%n tag change(s) have not been synced, and no sync command "
- "is configured. Quit anyway?", "", m_pendingEdits),
+ "is configured. Quit anyway?", "", pendingEditCount()),
QMessageBox::Discard | QMessageBox::Cancel,
QMessageBox::Cancel);
if (answer == QMessageBox::Cancel) {
@@ -181,7 +181,7 @@ void MainWindow::closeEvent(QCloseEvent *event)
box.setIcon(QMessageBox::Question);
box.setWindowTitle(tr("Unsynced changes"));
box.setText(tr("%n tag change(s) have not been synced.", "",
- m_pendingEdits));
+ pendingEditCount()));
box.setInformativeText(tr("Sync before quitting?"));
QPushButton *sync =
box.addButton(tr("Sync and quit"), QMessageBox::AcceptRole);
@@ -189,6 +189,15 @@ void MainWindow::closeEvent(QCloseEvent *event)
box.addButton(tr("Quit anyway"), QMessageBox::DestructiveRole);
box.addButton(QMessageBox::Cancel);
box.setDefaultButton(sync);
+
+ // The default is set correctly and Qt agrees (isDefault() and
+ // hasFocus() are both true on it), but qt6ct-style draws no
+ // visible default-button decoration, so Enter's target is
+ // invisible on this desktop. Naming it in the text costs nothing
+ // and does not fight the theme.
+ // ponytail: text, not a styled button. Restyling the button means
+ // overriding the user's theme, which is worse than a sentence.
+ sync->setText(tr("Sync and quit (default)"));
box.exec();
if (box.clickedButton() == sync) {
@@ -325,8 +334,29 @@ void MainWindow::buildUi()
// The status label is created first: the sync wiring below can report into
// it before the rest of the UI exists.
m_statusLabel = new QLabel(this);
+ m_statusLabel->setObjectName(QStringLiteral("statusMessage"));
statusBar()->addWidget(m_statusLabel);
+ // Transient messages describe an EVENT and go stale: "Sync complete" reads
+ // as the present tense until something else overwrites it. State messages,
+ // the selection count above all, describe what is true right now and must
+ // not expire while it stays true, so only showTransientStatus() arms this.
+ //
+ // ponytail: one timer beside the label, not QStatusBar::showMessage().
+ // That would mean moving off addWidget() and reworking the permanent
+ // widgets beside it, for the same behaviour.
+ m_statusTimer = new QTimer(this);
+ m_statusTimer->setObjectName(QStringLiteral("statusTimer"));
+ m_statusTimer->setSingleShot(true);
+ m_statusTimer->setInterval(kStatusMessageMs);
+ connect(m_statusTimer, &QTimer::timeout, this, [this]() {
+ // Only take back a message this timer armed. Anything written since is
+ // newer and more relevant than the default.
+ if (m_statusLabel->text() == m_transientMessage)
+ m_statusLabel->setText(m_defaultStatus);
+ m_transientMessage.clear();
+ });
+
// Beside the sync status rather than as a widget competing with it: the two
// say related things and reading them apart would be worse than reading
// them together.
@@ -409,6 +439,7 @@ void MainWindow::buildUi()
m_syncLogPane->hide();
m_syncButton = new QPushButton(tr("Sync"), central);
+ m_syncButton->setObjectName(QStringLiteral("syncButton"));
m_sync = new MailSync(m_config.syncCommand(), this);
m_syncButton->setEnabled(m_sync->isAvailable());
if (!m_sync->isAvailable()) {
@@ -417,7 +448,7 @@ void MainWindow::buildUi()
}
connect(m_syncButton, &QPushButton::clicked, this, [this]() {
if (!m_sync->start()) {
- m_statusLabel->setText(tr("Sync already running"));
+ showTransientStatus(tr("Sync already running"));
return;
}
// Fresh run, fresh output: leaving the previous run's lines in place
@@ -430,6 +461,15 @@ void MainWindow::buildUi()
m_syncLog->appendPlainText(chunk.trimmed());
});
+ // Syncs this window did not start. The user's cron runs the same script
+ // every ten minutes, so mail arrives and tags change while the window sits
+ // idle, and until now nothing here noticed.
+ m_syncMonitor = new SyncMonitor(SyncMonitor::defaultLockPath(),
+ QStringLiteral("/proc/locks"), this);
+ connect(m_syncMonitor, &SyncMonitor::stateChanged,
+ this, &MainWindow::onExternalSyncStateChanged);
+ m_syncMonitor->start();
+
queryRow->addWidget(m_accountBox);
queryRow->addWidget(m_queryEdit, 1);
queryRow->addWidget(m_syncButton);
@@ -488,6 +528,16 @@ void MainWindow::buildUi()
&QItemSelectionModel::currentRowChanged,
this, &MainWindow::onThreadSelected);
+ // Separate from currentRowChanged: a selection can grow without current
+ // moving at all. Ctrl+click adds a row and leaves current where it was, and
+ // selectAll() emits no currentRowChanged whatsoever (verified against
+ // Qt 6.11). Both are multi-select gestures that have to blank the pane and
+ // cancel a pending mark-read, so neither can rely on the current-index
+ // signal to notice them.
+ connect(m_threadView->selectionModel(),
+ &QItemSelectionModel::selectionChanged,
+ this, &MainWindow::onSelectionChanged);
+
m_messageView = new MessageView(central);
m_messageView->setTagColors(&m_tagColors);
connect(m_messageView, &MessageView::statusMessage,
@@ -564,8 +614,29 @@ void MainWindow::registerActions()
tagSelected({}, { QStringLiteral("inbox") }, tr("Archive"));
});
addAction(QStringLiteral("delete"), tr("&Delete"),
- tr("Add the deleted tag"), [this]() {
- tagSelected({ QStringLiteral("deleted") }, {}, tr("Delete"));
+ tr("Add or remove the deleted tag"), [this]() {
+ // A toggle, like toggle_unread: pressing Delete twice is the natural
+ // way to say "no, put it back", and adding a tag that is already there
+ // is a no-op the user cannot see.
+ //
+ // One direction for the WHOLE selection. Toggling each thread
+ // independently would leave one keystroke with the selection in two
+ // states, which is worse than either outcome, so undelete only when
+ // every selected thread is already deleted.
+ const QModelIndexList rows =
+ m_threadView->selectionModel()->selectedRows();
+ bool allDeleted = !rows.isEmpty();
+ for (const QModelIndex &index : rows) {
+ if (!m_model->threadAt(index.row()).isDeleted()) {
+ allDeleted = false;
+ break;
+ }
+ }
+
+ if (allDeleted)
+ tagSelected({}, { QStringLiteral("deleted") }, tr("Undelete"));
+ else
+ tagSelected({ QStringLiteral("deleted") }, {}, tr("Delete"));
});
addAction(QStringLiteral("spam"), tr("Mark &spam"),
tr("Add spam and remove inbox"), [this]() {
@@ -645,7 +716,7 @@ void MainWindow::registerActions()
if (m_undoStack.canUndo())
m_undoStack.undo();
else
- m_statusLabel->setText(tr("Nothing to undo"));
+ showTransientStatus(tr("Nothing to undo"));
});
addAction(QStringLiteral("sync"), tr("&Sync"),
tr("Run the configured sync command"), [this]() {
@@ -659,6 +730,29 @@ void MainWindow::registerActions()
m_queryEdit->setFocus();
m_queryCompleter->triggerCompletion();
});
+ addAction(QStringLiteral("clear_pane"), tr("Clear &message pane"),
+ tr("Blank the message pane without changing the selection"),
+ [this]() {
+ // A view change, not a mail change: the selection, the query and the
+ // undo stack are all left alone.
+ //
+ // m_currentThreadId is cleared with the pane, not merely alongside it.
+ // A threadLoaded still in flight for that id would otherwise paint the
+ // thread straight back, which is the queued-reply race documented in
+ // CLAUDE.md.
+ m_currentThreadId.clear();
+ m_messageView->clear();
+ m_markReadTimer->stop();
+ m_markReadThreadId.clear();
+ });
+ addAction(QStringLiteral("select_all"), tr("Select &all threads"),
+ tr("Select every thread in the current result list"), [this]() {
+ // A registered action rather than the view's built-in SelectAll key, so
+ // it reaches the Edit menu, the shortcut reference and [keys] the same
+ // way every other binding does. That is the whole point: multi-select
+ // already worked, it was simply invisible.
+ m_threadView->selectAll();
+ });
addAction(QStringLiteral("quit"), tr("&Quit"),
tr("Quit qtmaildir"), [this]() { close(); });
@@ -680,6 +774,8 @@ void MainWindow::buildMenus()
editMenu->addSeparator();
editMenu->addAction(m_actions.value(QStringLiteral("focus_query")));
editMenu->addAction(m_actions.value(QStringLiteral("complete_query")));
+ editMenu->addSeparator();
+ editMenu->addAction(m_actions.value(QStringLiteral("select_all")));
auto *messageMenu = menuBar()->addMenu(tr("&Message"));
messageMenu->addAction(m_actions.value(QStringLiteral("archive")));
@@ -731,6 +827,29 @@ void MainWindow::buildMenus()
action->setIcon(icon);
}
+ // Right-click on the thread list. Built from the same registered QActions
+ // as the menu bar, never from parallel copies: a [keys] override then shows
+ // the right shortcut here too, and an action cannot end up doing one thing
+ // from the menu bar and another from the context menu.
+ //
+ // Every entry applies to the whole selection already, since they all funnel
+ // through tagSelected(), so this needs no multi-row special casing.
+ m_threadContextMenu = new QMenu(this);
+ m_threadContextMenu->setObjectName(QStringLiteral("threadContextMenu"));
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("archive")));
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("delete")));
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("spam")));
+ m_threadContextMenu->addSeparator();
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("toggle_unread")));
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("flag")));
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("edit_tags")));
+ m_threadContextMenu->addSeparator();
+ m_threadContextMenu->addAction(m_actions.value(QStringLiteral("select_all")));
+
+ m_threadView->setContextMenuPolicy(Qt::CustomContextMenu);
+ connect(m_threadView, &QTableView::customContextMenuRequested,
+ this, &MainWindow::showThreadContextMenu);
+
// The frequent subset only. A toolbar holding every action is as
// unreadable as no toolbar.
auto *toolBar = addToolBar(tr("Main"));
@@ -787,6 +906,18 @@ void MainWindow::showShortcutReference()
"</tr></table>")
.arg(left, right));
+ // Mouse selection is view behaviour, not an action, so it cannot appear in
+ // the table above however the table is generated. Said here because it is
+ // otherwise undiscoverable: nothing in the UI hints that a thread list
+ // takes more than one row at a time.
+ auto *selectionNote = new QLabel(
+ tr("<b>Thread list:</b> <tt>Ctrl</tt>+click adds or removes a single "
+ "row, <tt>Shift</tt>+click extends the selection to a range. Tag, "
+ "archive and delete all apply to every selected thread."),
+ &dialog);
+ selectionNote->setTextFormat(Qt::RichText);
+ selectionNote->setWordWrap(true);
+
auto *note = new QLabel(
tr("Rebind any of these in the <tt>[keys]</tt> section of "
"<tt>qtmaildir.conf</tt>, using the action name."),
@@ -799,6 +930,7 @@ void MainWindow::showShortcutReference()
auto *layout = new QVBoxLayout(&dialog);
layout->addWidget(label);
+ layout->addWidget(selectionNote);
layout->addWidget(note);
layout->addStretch();
layout->addWidget(buttons);
@@ -970,7 +1102,74 @@ void MainWindow::onQueryFinished(int total, quint64 generation)
{
if (generation != m_generation)
return;
- m_statusLabel->setText(tr("%n thread(s)", "", total));
+ // The query's own result is what the bar says when nothing more pressing
+ // is happening, so a transient message falls back to it rather than to
+ // nothing.
+ m_defaultStatus = tr("%n thread(s)", "", total);
+ m_statusLabel->setText(m_defaultStatus);
+}
+
+void MainWindow::showThreadContextMenu(const QPoint &pos)
+{
+ const QModelIndex index = m_threadView->indexAt(pos);
+ if (!index.isValid())
+ return; // Right-click on empty space below the rows.
+
+ // Right-clicking a row that is already part of the selection must leave
+ // that selection alone: the actions apply to every selected thread, so
+ // collapsing to the clicked row here would silently narrow a deliberate
+ // multi-row selection to one. Right-clicking outside it selects that row
+ // instead, which is what every other list does.
+ if (!m_threadView->selectionModel()->isRowSelected(index.row()))
+ m_threadView->selectRow(index.row());
+
+ m_threadContextMenu->popup(m_threadView->viewport()->mapToGlobal(pos));
+}
+
+void MainWindow::onSelectionChanged()
+{
+ const int selected = m_threadView->selectionModel()->selectedRows().size();
+ if (selected <= 1) {
+ // Clearing the count here would wipe whatever the last action reported
+ // ("Archive: 3 threads"), which is the more useful message once the
+ // selection is gone. Only a count this function wrote is taken back.
+ if (m_statusLabel->text() == m_selectionMessage)
+ m_statusLabel->clear();
+ m_selectionMessage.clear();
+
+ // Collapsing a multi-row selection back to one row has to load that
+ // row here, and cannot be left to onThreadSelected. currentRowChanged
+ // is emitted BEFORE the selection model is updated (verified against
+ // Qt 6.11), so when a click collapses three rows to one, that handler
+ // still sees three selected, takes the multi-select branch and returns
+ // without loading anything. Only this signal sees the real count.
+ const QModelIndex current = m_threadView->currentIndex();
+ if (current.isValid()
+ && m_model->threadAt(current.row()).threadId != m_currentThreadId) {
+ onThreadSelected(current, QModelIndex());
+ }
+ return;
+ }
+
+ // The count is the part that actually teaches multi-select: it acknowledges
+ // the selection while it is being built, rather than only after an action
+ // has already been applied to it.
+ m_selectionMessage = tr("%n thread(s) selected", "", selected);
+ m_statusLabel->setText(m_selectionMessage);
+
+ // State, not an event: it must persist while the selection does. Cancel any
+ // transient message still counting down, or that timer fires and replaces a
+ // count that is still true.
+ m_statusTimer->stop();
+ m_transientMessage.clear();
+
+ // Ctrl+click and selectAll() reach a multi-row selection without moving
+ // current, so onThreadSelected never runs and its guard never fires. The
+ // pane and the pending timer have to be dealt with here as well.
+ m_markReadTimer->stop();
+ m_markReadThreadId.clear();
+ m_currentThreadId.clear();
+ m_messageView->clear();
}
void MainWindow::onThreadSelected(const QModelIndex &current,
@@ -979,6 +1178,31 @@ void MainWindow::onThreadSelected(const QModelIndex &current,
if (!current.isValid())
return;
+ // A selection spanning more than one row is aimed at a bulk action, not at
+ // reading. current follows the keyboard cursor as the selection extends, so
+ // without this every row swept through would be rendered and, worse,
+ // queued to be marked read: a selection gesture must not mutate mail.
+ //
+ // The count read here is deliberately not trusted on its own. This signal
+ // is emitted BEFORE the selection model is updated (verified against
+ // Qt 6.11), so a Ctrl+click that takes the selection from one row to two
+ // arrives here still reporting one. onSelectionChanged() always follows and
+ // sees the true count, and it is what finally blanks the pane and cancels
+ // the timer; this branch only catches the case where the count is already
+ // stale in the other direction.
+ //
+ // The stop() is not redundant with the guard. Clicking one row arms a timer
+ // legitimately and only then does the selection grow, so the timer already
+ // running for that first row has to be cancelled here or it fires behind a
+ // pane that no longer shows the thread.
+ if (m_threadView->selectionModel()->selectedRows().size() > 1) {
+ m_markReadTimer->stop();
+ m_markReadThreadId.clear();
+ m_currentThreadId.clear();
+ m_messageView->clear();
+ return;
+ }
+
const ThreadSummary thread = m_model->threadAt(current.row());
m_currentThreadId = thread.threadId;
m_messageView->setTags(thread.tags);
@@ -995,6 +1219,14 @@ void MainWindow::onThreadLoaded(const QVector<MessageRef> &messages,
if (generation != m_generation || messages.isEmpty())
return;
+ // A load started while the selection was still a single row can land after
+ // it has grown: loadThread crosses to the worker on a queued connection, so
+ // the reply arrives after onSelectionChanged() has already blanked the
+ // pane. Without this it would paint a thread back over the blank, and the
+ // pane would only look right once a third row made the count stale-proof.
+ if (m_threadView->selectionModel()->selectedRows().size() > 1)
+ return;
+
MimeParser parser;
QList<ThreadRenderItem> items;
items.reserve(messages.size());
@@ -1067,10 +1299,11 @@ void MainWindow::onSyncFinished(bool success, int exitCode)
// Only a SUCCESSFUL sync clears the count. Clearing on failure would
// assert the edits had reached the mail store when the sync is exactly
// what failed to put them there.
- m_pendingEdits = 0;
+ m_pendingTagEdits.clear();
+ m_unnettablePendingEdits = 0;
updatePendingIndicator();
- m_statusLabel->setText(tr("Sync complete"));
+ showTransientStatus(tr("Sync complete"));
if (m_syncingForExit) {
// The work is safely across, so finish the quit the user asked for.
@@ -1084,11 +1317,17 @@ void MainWindow::onSyncFinished(bool success, int exitCode)
// A sync is the usual way new tags enter the database.
requestAllTags();
} else if (exitCode == kSyncSkippedExitCode) {
+ // Skipped means the lock was never ours: some other run holds it. If
+ // both started inside the same poll interval the monitor will have
+ // latched this lock period as local, which would swallow the report
+ // when that other run finishes. Hand it back.
+ m_localSyncHoldsLock = false;
+
// Not a failure: another run holds the lock and is doing the work.
// The user's cron fires every ten minutes, so a click landing inside
// one is routine and must not raise an error or the log pane.
- m_statusLabel->setText(tr("A sync is already running (started "
- "elsewhere); this one was skipped"));
+ showTransientStatus(tr("A sync is already running (started "
+ "elsewhere); this one was skipped"));
if (m_syncingForExit) {
// The other run is syncing, but this application cannot see when
@@ -1125,10 +1364,33 @@ void MainWindow::onTagsApplied(const TagChange &change)
m_pendingChange = {};
m_pendingThreadIds.clear();
- // Counted here, where a write is CONFIRMED, rather than where one is sent:
+ // Recorded here, where a write is CONFIRMED, rather than where one is sent:
// an optimistic update the worker later rejects must not leave the
// indicator claiming an edit that never landed.
- ++m_pendingEdits;
+ //
+ // NET state, not a count of writes. An edit and its inverse leave the mail
+ // store where it started, so they must leave the indicator at zero: the
+ // automatic mark-read followed by Ctrl+U used to read as 2 unsynced
+ // changes when nothing was outstanding. What the user needs to know is
+ // whether quitting now would strand work.
+ //
+ // Keyed per (message, tag): removing `unread` and adding `flagged` on one
+ // message are two independent changes and must not cancel each other.
+ for (const QString &messageId : change.messageIds) {
+ for (const QString &tag : change.added)
+ recordPendingEdit(messageId, tag, true);
+ for (const QString &tag : change.removed)
+ recordPendingEdit(messageId, tag, false);
+ }
+
+ // A change carrying no message ids cannot be netted against anything, and
+ // must still register: losing an edit understates the indicator, which is
+ // the direction that costs the user work.
+ if (change.messageIds.isEmpty()
+ && !(change.added.isEmpty() && change.removed.isEmpty())) {
+ ++m_unnettablePendingEdits;
+ }
+
updatePendingIndicator();
// A tag the user has just created is the one they are most likely to type
@@ -1142,28 +1404,129 @@ void MainWindow::onTagsApplied(const TagChange &change)
}
}
+void MainWindow::onExternalSyncStateChanged(SyncMonitor::State state)
+{
+ if (state == SyncMonitor::State::Running) {
+ // A sync this window started is already reported by setSyncBusy().
+ // Remember that this particular lock period is ours, because the
+ // release at the end of it must be ignored too: the process exits, and
+ // therefore isRunning() goes false, BEFORE the monitor's next poll sees
+ // the lock gone. Testing isRunning() again on that poll would report a
+ // local sync as an external one, stamping "background sync completed"
+ // over the local run's own result up to two seconds later.
+ m_localSyncHoldsLock = (m_sync && m_sync->isRunning());
+ if (m_localSyncHoldsLock)
+ return;
+
+ m_externalSyncBusy = true;
+ updateSyncControls();
+ m_statusLabel->setText(tr("Background sync running..."));
+ return;
+ }
+
+ // The release of a lock this window took. onSyncFinished() has already
+ // said what happened, including for a failure, so there is nothing to add.
+ if (m_localSyncHoldsLock) {
+ m_localSyncHoldsLock = false;
+ m_externalSyncBusy = false;
+ updateSyncControls();
+ return;
+ }
+
+ // Cleared for Idle AND for Unknown. Unknown means /proc/locks could not be
+ // read, so nothing is observed; leaving the button disabled there would
+ // strand it permanently on a platform that cannot see the lock at all.
+ m_externalSyncBusy = false;
+ updateSyncControls();
+
+ // Deliberately reports rather than refreshes. runCurrentQuery() clears the
+ // undo stack, the selection and the message pane, which is right for a
+ // query the user typed and hostile for one fired by a cron timer: with a
+ // sync every ten minutes it would discard undo history and close the thread
+ // being read, up to six times an hour, with no action from the user.
+ //
+ // Unknown is not worth reporting either. It means the lock table could not
+ // be read, so nothing was observed, and "sync finished" would be a claim
+ // this cannot support.
+ if (state == SyncMonitor::State::Idle) {
+ showTransientStatus(
+ tr("Background sync completed. Press Enter in the query bar to "
+ "refresh."));
+ }
+}
+
+void MainWindow::showTransientStatus(const QString &text)
+{
+ m_transientMessage = text;
+ m_statusLabel->setText(text);
+ m_statusTimer->start();
+}
+
void MainWindow::setSyncBusy(bool busy)
{
+ m_localSyncBusy = busy;
+ updateSyncControls();
+
+ if (busy)
+ m_statusLabel->setText(tr("Syncing..."));
+}
+
+void MainWindow::updateSyncControls()
+{
+ // ONE function of both states, deliberately. Two independent assignments,
+ // one per sync path, means whichever fires second wins: a background sync
+ // ending would re-enable the button in the middle of a local run, and a
+ // local run ending would re-enable it while cron still holds the lock.
+ const bool busy = m_localSyncBusy || m_externalSyncBusy;
+
m_syncProgress->setVisible(busy);
+
// Disabled rather than left clickable: MailSync::start() already refuses a
- // second run, but a button that looks live and does nothing is worse than
- // one that shows it is unavailable.
+ // second run and the script exits 75 when another holds the lock, but a
+ // button that looks live and does nothing is worse than one that shows it
+ // is unavailable.
+ //
+ // Note this reads Running specifically, not "not Idle". Unknown means
+ // /proc/locks could not be read and nothing was observed, so the button
+ // stays usable: permanently disabling it where the lock cannot be seen is
+ // worse than occasionally offering a run that gets skipped.
m_syncButton->setEnabled(!busy && m_sync && m_sync->isAvailable());
+}
- if (busy)
- m_statusLabel->setText(tr("Syncing..."));
+void MainWindow::recordPendingEdit(const QString &messageId, const QString &tag,
+ bool added)
+{
+ const QString key = messageId + QLatin1Char('\n') + tag;
+
+ // A tag put back the way it was is not an outstanding change. Erase rather
+ // than store the new direction, or the ledger grows without bound over a
+ // long session of tagging and untagging.
+ const auto existing = m_pendingTagEdits.constFind(key);
+ if (existing != m_pendingTagEdits.constEnd()) {
+ if (*existing != added)
+ m_pendingTagEdits.erase(m_pendingTagEdits.find(key));
+ return;
+ }
+
+ m_pendingTagEdits.insert(key, added);
+}
+
+int MainWindow::pendingEditCount() const
+{
+ return m_pendingTagEdits.size() + m_unnettablePendingEdits;
}
void MainWindow::updatePendingIndicator()
{
- if (m_pendingEdits <= 0) {
+ const int pending = pendingEditCount();
+ if (pending <= 0) {
m_pendingLabel->hide();
return;
}
// "Changes" and not "mutations": the unit the user thinks in is the tagging
// they did, not the writes it became.
- m_pendingLabel->setText(tr("%n unsynced change(s)", "", m_pendingEdits));
+ m_pendingLabel->setText(tr("%n unsynced change(s)", "", pending));
m_pendingLabel->setToolTip(
tr("Tag changes made here that a sync has not yet carried to the mail "
"store. An external notmuch run can clear them without this count "
@@ -1244,7 +1607,7 @@ void MainWindow::editTagsOnSelection()
const QModelIndexList rows =
m_threadView->selectionModel()->selectedRows();
if (rows.isEmpty()) {
- m_statusLabel->setText(tr("Select a thread first"));
+ showTransientStatus(tr("Select a thread first"));
return;
}
@@ -1294,7 +1657,7 @@ void MainWindow::tagSelected(const QStringList &add, const QStringList &remove,
m_undoStack.push(new ThreadTagCommand(this, threadIds, add, remove,
description));
- m_statusLabel->setText(
+ showTransientStatus(
tr("%1: %n thread(s)", "", threadIds.size()).arg(description));
}
diff --git a/src/mainwindow.h b/src/mainwindow.h
index d1f7b1c..cf9aca6 100644
--- a/src/mainwindow.h
+++ b/src/mainwindow.h
@@ -28,11 +28,13 @@
#include "config.h"
#include "keymap.h"
+#include "syncmonitor.h"
#include "tagcolors.h"
#include "types.h"
class QAction;
class QLineEdit;
+class QMenu;
class QTableView;
class QLabel;
class QPushButton;
@@ -60,6 +62,12 @@ public:
/// really registered.
QStringList registeredActionNames() const;
+ /// The thread currently shown in the message pane, empty when it is blank.
+ ///
+ /// Empty is what "the pane is blanked" means internally: a late-arriving
+ /// load is discarded rather than painted, so no thread can reappear.
+ QString currentThreadId() const { return m_currentThreadId; }
+
/// The cid: namespace prefix for the nth message of a thread.
///
/// MainWindow is the only producer of this value in the application. It
@@ -76,6 +84,11 @@ public:
/// `assets/mailsync.sh` is the reference implementation of this contract.
static constexpr int kSyncSkippedExitCode = 75;
+ /// How long a transient status message stays before the bar falls back to
+ /// the thread count. Long enough to read a sentence, short enough that a
+ /// stale "Sync complete" does not sit there describing the present.
+ static constexpr int kStatusMessageMs = 6000;
+
/// Path of the machine-written UI state file. Deliberately not
/// Config::defaultPath(): the config is hand-edited and must never gain a
/// base64 geometry blob, nor be rewritten on exit (QSettings does not
@@ -95,10 +108,32 @@ private slots:
void onThreadsReady(const QVector<ThreadSummary> &threads, quint64 generation);
void onQueryFinished(int total, quint64 generation);
void onThreadSelected(const QModelIndex &current, const QModelIndex &previous);
+
+ /// Keeps the status bar's selection count and the multi-select guard in
+ /// step with selections that never move the current index.
+ void onSelectionChanged();
+
+ /// Pops up the thread-list context menu, preserving a multi-row selection
+ /// the click lands inside.
+ void showThreadContextMenu(const QPoint &pos);
void onThreadLoaded(const QVector<MessageRef> &messages, quint64 generation);
void onWorkerError(const QString &message);
void onSyncFinished(bool success, int exitCode);
+ /// Shows a message that describes an event and takes it back after a few
+ /// seconds, restoring the last query's thread count.
+ ///
+ /// Use this for events ("Sync complete"), never for state: the selection
+ /// count must persist while the selection does. A private slot so tests can
+ /// drive it through the meta-object.
+ void showTransientStatus(const QString &text);
+
+ /// Reacts to a sync started outside this window, by cron or by hand.
+ ///
+ /// A private slot rather than a plain method so tests can drive it through
+ /// the meta-object without widening the public API.
+ void onExternalSyncStateChanged(SyncMonitor::State state);
+
/// A tag mutation the worker has confirmed reached the database. Counts it
/// as unsynced, since reaching the index is not reaching the mail store.
void onTagsApplied(const TagChange &change);
@@ -141,9 +176,17 @@ private:
/// the one on screen.
void markCurrentThreadRead();
- /// Redraws the unsynced-edits indicator from m_pendingEdits.
+ /// Redraws the unsynced-edits indicator from pendingEditCount().
void updatePendingIndicator();
+ /// Records one confirmed (message, tag) change, cancelling it against an
+ /// opposite change already outstanding for the same pair.
+ void recordPendingEdit(const QString &messageId, const QString &tag,
+ bool added);
+
+ /// Net changes the index holds that a sync has not carried over.
+ int pendingEditCount() const;
+
/// Shows or hides the "syncing" state: the progress bar and a disabled
/// Sync button.
///
@@ -153,6 +196,15 @@ private:
/// says "working, duration unknown", which is the truth.
void setSyncBusy(bool busy);
+ /// Applies the sync progress bar and button state from BOTH sync sources.
+ ///
+ /// One function of both, never two assignments: with a local and a
+ /// background sync each writing the widgets independently, whichever
+ /// finished second would win and re-enable the button while the other was
+ /// still running.
+ void updateSyncControls();
+
+
/// Opens the tag dialog on the current selection and applies its result.
///
/// The only route to an arbitrary tag: every other tag action writes a
@@ -191,16 +243,47 @@ private:
ThreadListModel *m_model = nullptr;
MessageView *m_messageView = nullptr;
MailSync *m_sync = nullptr;
+
+ /// Watches the sync lock for runs this window did not start.
+ SyncMonitor *m_syncMonitor = nullptr;
+
+ /// True while the lock the monitor can see is held by this window's own
+ /// sync. Latched when the lock is taken, because by the time it is released
+ /// MailSync::isRunning() is already false and can no longer answer "was
+ /// that ours?".
+ bool m_localSyncHoldsLock = false;
+
+ /// True while a sync this window started is running. Half of the input to
+ /// updateSyncControls().
+ bool m_localSyncBusy = false;
+
+ /// True while a sync this window did NOT start holds the lock. The other
+ /// half. Tracked here rather than read back from SyncMonitor so the state
+ /// the UI acted on is the state it was told about.
+ bool m_externalSyncBusy = false;
QUndoStack m_undoStack;
QLineEdit *m_queryEdit = nullptr;
QueryCompleter *m_queryCompleter = nullptr;
QTableView *m_threadView = nullptr;
+
+ /// Right-click menu for the thread list, holding the same QActions the
+ /// menu bar does.
+ QMenu *m_threadContextMenu = nullptr;
QSplitter *m_splitter = nullptr;
QComboBox *m_accountBox = nullptr;
QPushButton *m_syncButton = nullptr;
QLabel *m_statusLabel = nullptr;
+ /// Expires a transient status message. See showTransientStatus().
+ QTimer *m_statusTimer = nullptr;
+
+ /// The message m_statusTimer armed for, so it takes back only its own.
+ QString m_transientMessage;
+
+ /// What the status bar falls back to: the last query's thread count.
+ QString m_defaultStatus;
+
/// Says how many tag changes have not been seen to reach the mail store.
/// Hidden entirely at zero rather than reading "0 unsynced", which is noise.
QLabel *m_pendingLabel = nullptr;
@@ -230,6 +313,10 @@ private:
QString m_lastQuery;
QString m_currentThreadId;
+ /// The selection count last written to the status bar, so it can be taken
+ /// back without clobbering a message some other action put there.
+ QString m_selectionMessage;
+
/// Confirmed tag mutations not yet known to have reached the mail store.
///
/// A count of its own rather than QUndoStack::isClean(), which cannot serve
@@ -239,7 +326,17 @@ private:
///
/// A lower bound on what is outstanding, never a guarantee: the user's cron
/// can run notmuch new without the application noticing.
- int m_pendingEdits = 0;
+ ///
+ /// NET state rather than a tally of writes. Keyed "<messageId>\n<tag>",
+ /// value true for added and false for removed; a pair that reverts is
+ /// erased rather than stored, so an edit and its inverse leave nothing
+ /// behind and the map cannot grow without bound.
+ QHash<QString, bool> m_pendingTagEdits;
+
+ /// Confirmed changes carrying no message ids, which cannot be netted
+ /// against anything. Counted separately rather than dropped: understating
+ /// the indicator is the direction that costs the user work.
+ int m_unnettablePendingEdits = 0;
/// Marks the open thread read once it has been on screen long enough.
///
diff --git a/src/syncmonitor.cpp b/src/syncmonitor.cpp
new file mode 100644
index 0000000..e2883dc
--- /dev/null
+++ b/src/syncmonitor.cpp
@@ -0,0 +1,151 @@
+/*
+ * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
+ * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#include "syncmonitor.h"
+
+#include <QFile>
+#include <QFileInfo>
+
+#include <sys/stat.h>
+
+namespace {
+
+/// Two seconds. The user chose continuous polling over a poll-only-while-
+/// quitting variant, and this is a read of one small procfs file, so the cost
+/// is negligible next to noticing a cron sync within a couple of seconds.
+constexpr int kDefaultIntervalMs = 2000;
+
+} // namespace
+
+SyncMonitor::SyncMonitor(const QString &lockPath, const QString &locksPath,
+ QObject *parent)
+ : QObject(parent), m_lockPath(lockPath), m_locksPath(locksPath)
+{
+ m_timer.setInterval(kDefaultIntervalMs);
+ connect(&m_timer, &QTimer::timeout, this, &SyncMonitor::poll);
+}
+
+void SyncMonitor::setInterval(int ms)
+{
+ m_timer.setInterval(ms);
+}
+
+void SyncMonitor::start()
+{
+ // Poll once immediately: a window opened during a cron sync should say so
+ // at once rather than after the first interval.
+ poll();
+ m_timer.start();
+}
+
+void SyncMonitor::stop()
+{
+ m_timer.stop();
+}
+
+QString SyncMonitor::defaultLockPath()
+{
+ // Must stay equal to LOCKFILE in assets/mailsync.sh.
+ return QStringLiteral("/tmp/mbsync.lock");
+}
+
+qint64 SyncMonitor::inodeOf(const QString &path)
+{
+ // Qt exposes no inode accessor, and /proc/locks identifies a file only by
+ // device and inode, so this has to come from stat(2) directly. That is also
+ // why the whole class is Linux-shaped; see the Unknown state for what
+ // happens where /proc/locks does not exist.
+ struct stat st;
+ if (::stat(QFile::encodeName(path).constData(), &st) != 0)
+ return -1;
+
+ return static_cast<qint64>(st.st_ino);
+}
+
+bool SyncMonitor::lockHeldIn(const QString &content, qint64 inode)
+{
+ if (content.isEmpty() || inode < 0)
+ return false;
+
+ // A /proc/locks line looks like:
+ // 82: FLOCK ADVISORY WRITE 9051 fc:00:12058676 0 EOF
+ // The inode is the last colon-separated part of the major:minor:inode
+ // field. Matching the raw number anywhere in the line would also match a
+ // pid or a byte range, so the field is located first and then split.
+ const QList<QStringView> lines = QStringView(content).split(u'\n',
+ Qt::SkipEmptyParts);
+ for (const QStringView &line : lines) {
+ const QList<QStringView> fields =
+ line.split(u' ', Qt::SkipEmptyParts);
+
+ // Shortest real line still has: index, type, ADVISORY, WRITE, pid,
+ // dev:inode. Anything shorter is truncated or not a lock line, and is
+ // skipped rather than guessed at.
+ if (fields.size() < 6)
+ continue;
+
+ // flock(2) only. mailsync.sh uses flock, and a POSIX record lock on
+ // the same file belongs to somebody else: the two namespaces cannot
+ // see each other, so treating a POSIX entry as ours would report a
+ // sync that is not running.
+ if (fields.at(1) != QLatin1String("FLOCK"))
+ continue;
+
+ for (const QStringView &field : fields) {
+ const qsizetype lastColon = field.lastIndexOf(u':');
+ if (lastColon < 0)
+ continue;
+
+ bool ok = false;
+ const qint64 candidate =
+ field.mid(lastColon + 1).toLongLong(&ok);
+ if (ok && candidate == inode)
+ return true;
+ }
+ }
+
+ return false;
+}
+
+void SyncMonitor::poll()
+{
+ State next = State::Unknown;
+
+ QFile locks(m_locksPath);
+ if (locks.open(QIODevice::ReadOnly | QIODevice::Text)) {
+ // Read in full rather than line by line: /proc/locks is small, and a
+ // partial read while the kernel is editing the table could truncate a
+ // line mid-field.
+ const QString content = QString::fromUtf8(locks.readAll());
+
+ const qint64 inode = inodeOf(m_lockPath);
+ if (inode < 0) {
+ // No lock file yet, before the first sync ever runs. The table was
+ // readable, so this is a real answer and not Unknown.
+ next = State::Idle;
+ } else {
+ next = lockHeldIn(content, inode) ? State::Running : State::Idle;
+ }
+ }
+
+ if (next == m_state)
+ return;
+
+ m_state = next;
+ emit stateChanged(m_state);
+}
diff --git a/src/syncmonitor.h b/src/syncmonitor.h
new file mode 100644
index 0000000..3aca520
--- /dev/null
+++ b/src/syncmonitor.h
@@ -0,0 +1,106 @@
+/*
+ * qtmaildir - a Qt6 mail client for notmuch-indexed Maildirs
+ * Copyright (C) 2026 Danilo M. <danix@danix.xyz>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License version 2 as
+ * published by the Free Software Foundation.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ */
+
+#pragma once
+
+#include <QObject>
+#include <QString>
+#include <QTimer>
+
+/// Notices syncs this process did not start.
+///
+/// The user's cron runs mailsync.sh every ten minutes, so mail can appear and
+/// tags can change while the window sits idle. The script holds an flock for
+/// the whole run, which is already the signal: no status file is needed, and a
+/// kernel lock cannot go stale because it dies with the process holding it.
+///
+/// **Read the lock, never take it.** Three ways to observe an flock look
+/// plausible and two are wrong, both verified on Slackware, Linux 6.18:
+///
+/// - `flock -n` acquires in order to test. Polling every two seconds would
+/// open a window every two seconds in which a starting mailsync.sh is
+/// refused the lock and exits 75. It would cause the very skips the sync
+/// script reports.
+/// - `fcntl(F_OFD_GETLK)` never acquires, and looks ideal, but reports
+/// UNLOCKED against a lock held by flock(2): the two are separate lock
+/// namespaces in the kernel and cannot see each other. A silent false
+/// negative, which is the worst failure available here.
+/// - /proc/locks is a pure read. It observes flock(2) entries correctly and
+/// cannot acquire, steal, or contend, so it can also never disturb the
+/// Xapian write lock notmuch new holds during the same run.
+///
+/// Do not "simplify" this to flock -n.
+class SyncMonitor : public QObject
+{
+ Q_OBJECT
+public:
+ enum class State {
+ Unknown, ///< The lock table cannot be read; claim nothing.
+ Idle, ///< Readable, and nothing holds the lock.
+ Running, ///< Something holds the lock: a sync is in progress.
+ };
+ Q_ENUM(State)
+
+ /// @param lockPath the file mailsync.sh flocks, /tmp/mbsync.lock.
+ /// @param locksPath the kernel lock table; injectable so tests can drive
+ /// transitions without holding real locks.
+ explicit SyncMonitor(const QString &lockPath,
+ const QString &locksPath = QStringLiteral("/proc/locks"),
+ QObject *parent = nullptr);
+
+ State state() const { return m_state; }
+
+ /// True only for State::Running. Unknown is deliberately not "running":
+ /// callers use this to decide whether to wait, and waiting forever on a
+ /// platform with no /proc/locks would be worse than not noticing a sync.
+ bool isRunning() const { return m_state == State::Running; }
+
+ void setInterval(int ms);
+ void start();
+ void stop();
+
+ /// One observation. Public so tests can step it without a running timer.
+ void poll();
+
+ /// Whether @p content holds an flock(2) entry for @p inode.
+ ///
+ /// Static and content-based: this is the part worth testing, and it is
+ /// testable only while it is separate from reading the file.
+ static bool lockHeldIn(const QString &content, qint64 inode);
+
+ /// The inode of @p path, or -1 when it does not exist.
+ static qint64 inodeOf(const QString &path);
+
+ /// The lock file assets/mailsync.sh takes, and the only one worth watching.
+ ///
+ /// Hardcoded to match LOCKFILE in that script. Two sources of truth is the
+ /// standing hazard here: change one and the monitor silently reports Idle
+ /// forever, since a missing lock file is a legitimate "no sync running".
+ static QString defaultLockPath();
+
+signals:
+ /// Emitted only when the state actually changes, never once per poll: the
+ /// status bar must not be repainted every two seconds forever.
+ void stateChanged(SyncMonitor::State state);
+
+private:
+ QString m_lockPath;
+ QString m_locksPath;
+ State m_state = State::Unknown;
+ QTimer m_timer;
+};