summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorDanilo M. <danix@danix.xyz>2026-08-04 18:57:20 +0200
committerDanilo M. <danix@danix.xyz>2026-08-04 18:57:20 +0200
commit0b3869c758f4dc54017ff91b5b69bfc263c0da52 (patch)
treea202a583a6f794c743cc838b33da2d1a79cfc07b /src
parent1407f70352c05d59fa2e1bb7c59b048b767972e5 (diff)
parentce0753bcb6263dec5a6acb53647ca7b64950f8fd (diff)
downloadqtmaildir-0b3869c758f4dc54017ff91b5b69bfc263c0da52.tar.gz
qtmaildir-0b3869c758f4dc54017ff91b5b69bfc263c0da52.zip
Merge branch 'multiselect-discoverability'
Multi-select discoverability (items 24, 25) and awareness of syncs this window did not start (item 27). Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Diffstat (limited to 'src')
-rw-r--r--src/CMakeLists.txt1
-rw-r--r--src/keymap.cpp4
-rw-r--r--src/mainwindow.cpp206
-rw-r--r--src/mainwindow.h40
-rw-r--r--src/syncmonitor.cpp151
-rw-r--r--src/syncmonitor.h106
6 files changed, 508 insertions, 0 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/keymap.cpp b/src/keymap.cpp
index 0901cfb..dcb63a8 100644
--- a/src/keymap.cpp
+++ b/src/keymap.cpp
@@ -35,6 +35,7 @@ QStringList KeyMap::knownActions()
QStringLiteral("flag"),
QStringLiteral("focus_query"),
QStringLiteral("complete_query"),
+ QStringLiteral("select_all"),
QStringLiteral("toggle_html"),
QStringLiteral("load_remote"),
QStringLiteral("message_details"),
@@ -72,6 +73,9 @@ 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") },
{ 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..792ba3f 100644
--- a/src/mainwindow.cpp
+++ b/src/mainwindow.cpp
@@ -325,6 +325,7 @@ 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);
// Beside the sync status rather than as a widget competing with it: the two
@@ -430,6 +431,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 +498,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,
@@ -659,6 +679,14 @@ void MainWindow::registerActions()
m_queryEdit->setFocus();
m_queryCompleter->triggerCompletion();
});
+ 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 +708,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 +761,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 +840,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 +864,7 @@ void MainWindow::showShortcutReference()
auto *layout = new QVBoxLayout(&dialog);
layout->addWidget(label);
+ layout->addWidget(selectionNote);
layout->addWidget(note);
layout->addStretch();
layout->addWidget(buttons);
@@ -973,12 +1039,94 @@ void MainWindow::onQueryFinished(int total, quint64 generation)
m_statusLabel->setText(tr("%n thread(s)", "", total));
}
+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);
+
+ // 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,
const QModelIndex &)
{
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 +1143,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());
@@ -1084,6 +1240,12 @@ 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.
@@ -1142,6 +1304,50 @@ 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_syncProgress->setVisible(true);
+ 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;
+ return;
+ }
+
+ m_syncProgress->setVisible(false);
+
+ // 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) {
+ m_statusLabel->setText(
+ tr("Background sync completed. Press Enter in the query bar to "
+ "refresh."));
+ }
+}
+
void MainWindow::setSyncBusy(bool busy)
{
m_syncProgress->setVisible(busy);
diff --git a/src/mainwindow.h b/src/mainwindow.h
index d1f7b1c..66044dc 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
@@ -95,10 +103,24 @@ 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);
+ /// 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);
@@ -153,6 +175,7 @@ private:
/// says "working, duration unknown", which is the truth.
void setSyncBusy(bool busy);
+
/// 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,11 +214,24 @@ 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;
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;
@@ -230,6 +266,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
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;
+};