1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
|
/*
* 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 "tagrulesdialog.h"
#include <QButtonGroup>
#include <QCheckBox>
#include <QComboBox>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QLineEdit>
#include <QMessageBox>
#include <QPlainTextEdit>
#include <QPushButton>
#include <QRadioButton>
#include <QSpinBox>
#include <QTreeWidget>
#include <QVBoxLayout>
namespace {
/// Columns of the rule list.
enum Column { ColumnEnabled = 0, ColumnStage, ColumnId, ColumnTags,
ColumnCount };
QStringList splitTags(const QString &text)
{
QStringList out;
const QStringList parts = text.split(QLatin1Char(','));
for (const QString &part : parts) {
const QString trimmed = part.trimmed();
if (!trimmed.isEmpty())
out.append(trimmed);
}
return out;
}
struct FieldEntry { RuleTerm::Field field; const char *label; };
const FieldEntry kFields[] = {
{RuleTerm::From, QT_TR_NOOP("From")},
{RuleTerm::To, QT_TR_NOOP("To")},
{RuleTerm::Cc, QT_TR_NOOP("Cc")},
{RuleTerm::Subject, QT_TR_NOOP("Subject")},
{RuleTerm::Tag, QT_TR_NOOP("Tag")},
{RuleTerm::Folder, QT_TR_NOOP("Folder")},
{RuleTerm::Attachment, QT_TR_NOOP("Attachment")},
{RuleTerm::Date, QT_TR_NOOP("Date")},
};
} // namespace
TagRulesDialog::TagRulesDialog(QWidget *parent)
: QDialog(parent)
{
setWindowTitle(tr("Tagging rules"));
resize(760, 520);
m_rules.load();
m_working = m_rules.rules();
auto *layout = new QVBoxLayout(this);
auto *intro = new QLabel(
tr("Rules tag mail as it arrives, applied by the notmuch post-new "
"hook. Editing them here changes what the next sync does; it does "
"not retag mail you already have."),
this);
intro->setWordWrap(true);
layout->addWidget(intro);
m_warningLabel = new QLabel(this);
m_warningLabel->setWordWrap(true);
m_warningLabel->setVisible(false);
layout->addWidget(m_warningLabel);
m_list = new QTreeWidget(this);
m_list->setColumnCount(ColumnCount + 1);
m_list->setHeaderLabels({ tr("On"), tr("Stage"), tr("Rule"), tr("Tags"),
tr("Matches") });
m_list->setRootIsDecorated(false);
m_list->setUniformRowHeights(true);
layout->addWidget(m_list, 1);
auto *form = new QFormLayout;
m_id = new QLineEdit(this);
m_stage = new QSpinBox(this);
m_stage->setRange(0, 999);
m_enabled = new QCheckBox(tr("Applied on every sync"), this);
m_add = new QLineEdit(this);
m_add->setPlaceholderText(tr("comma separated"));
m_remove = new QLineEdit(this);
m_remove->setPlaceholderText(tr("comma separated"));
m_query = new QLineEdit(this);
// Query syntax is wire format, never translated. Only the prose is.
m_query->setPlaceholderText(QStringLiteral("from:sender@example.com"));
m_note = new QPlainTextEdit(this);
m_note->setMaximumHeight(70);
form->addRow(tr("Name"), m_id);
form->addRow(tr("Stage"), m_stage);
form->addRow(QString(), m_enabled);
form->addRow(tr("Add tags"), m_add);
form->addRow(tr("Remove tags"), m_remove);
m_builder = new QWidget(this);
auto *builderLayout = new QVBoxLayout(m_builder);
builderLayout->setContentsMargins(0, 0, 0, 0);
auto *matchRow = new QHBoxLayout;
m_matchAll = new QRadioButton(tr("Match &all"), m_builder);
m_matchAny = new QRadioButton(tr("Match a&ny"), m_builder);
m_matchAll->setChecked(true);
auto *matchGroup = new QButtonGroup(this);
matchGroup->addButton(m_matchAll);
matchGroup->addButton(m_matchAny);
m_textMode = new QCheckBox(tr("Edit as &text"), m_builder);
m_textMode->setToolTip(
tr("Edit the notmuch query directly. A rule too complex to show as "
"rows opens this way."));
matchRow->addWidget(m_matchAll);
matchRow->addWidget(m_matchAny);
matchRow->addStretch();
matchRow->addWidget(m_textMode);
builderLayout->addLayout(matchRow);
m_rowsLayout = new QVBoxLayout;
builderLayout->addLayout(m_rowsLayout);
m_exclusionsHeader = new QLabel(tr("But not"), m_builder);
builderLayout->addWidget(m_exclusionsHeader);
m_exclusionsLayout = new QVBoxLayout;
builderLayout->addLayout(m_exclusionsLayout);
m_addExclusion = new QPushButton(tr("Add e&xclusion"), m_builder);
builderLayout->addWidget(m_addExclusion, 0, Qt::AlignLeft);
form->addRow(tr("Match"), m_builder);
form->addRow(tr("Query"), m_query);
// The query line shows what the rows compile to. Read-only in builder
// mode: it is what actually ships to the hook, and watching it change is
// what makes the rows trustworthy.
m_query->setReadOnly(true);
connect(m_matchAll, &QRadioButton::toggled,
this, &TagRulesDialog::syncQueryLine);
connect(m_addExclusion, &QPushButton::clicked, this, [this] {
addRow(true);
syncQueryLine();
});
form->addRow(tr("Note"), m_note);
layout->addLayout(form);
auto *buttons = new QHBoxLayout;
auto *addButton = new QPushButton(tr("&New"), this);
auto *copyButton = new QPushButton(tr("&Copy"), this);
auto *deleteButton = new QPushButton(tr("&Delete"), this);
auto *refreshButton = new QPushButton(tr("Count &matches"), this);
refreshButton->setToolTip(
tr("Count the messages each rule's query matches across all mail. "
"This does not tag anything."));
buttons->addWidget(addButton);
buttons->addWidget(copyButton);
buttons->addWidget(deleteButton);
buttons->addStretch();
buttons->addWidget(refreshButton);
layout->addLayout(buttons);
auto *box = new QDialogButtonBox(QDialogButtonBox::Save
| QDialogButtonBox::Cancel,
this);
m_saveButton = box->button(QDialogButtonBox::Save);
layout->addWidget(box);
connect(m_list, &QTreeWidget::currentItemChanged,
this, &TagRulesDialog::onSelectionChanged);
connect(addButton, &QPushButton::clicked,
this, &TagRulesDialog::onAddRule);
connect(copyButton, &QPushButton::clicked,
this, &TagRulesDialog::onCopyRule);
connect(deleteButton, &QPushButton::clicked,
this, &TagRulesDialog::onDeleteRule);
connect(refreshButton, &QPushButton::clicked,
this, &TagRulesDialog::countsRequested);
connect(box, &QDialogButtonBox::accepted,
this, &TagRulesDialog::onSave);
connect(box, &QDialogButtonBox::rejected, this, &QDialog::reject);
// Edits land on the working copy as they are made, so switching rows does
// not silently discard what was typed.
connect(m_id, &QLineEdit::editingFinished,
this, &TagRulesDialog::applyEditsToCurrentRule);
connect(m_add, &QLineEdit::editingFinished,
this, &TagRulesDialog::applyEditsToCurrentRule);
connect(m_remove, &QLineEdit::editingFinished,
this, &TagRulesDialog::applyEditsToCurrentRule);
connect(m_query, &QLineEdit::editingFinished,
this, &TagRulesDialog::applyEditsToCurrentRule);
connect(m_stage, &QSpinBox::editingFinished,
this, &TagRulesDialog::applyEditsToCurrentRule);
connect(m_enabled, &QCheckBox::toggled,
this, &TagRulesDialog::applyEditsToCurrentRule);
// QPlainTextEdit has no editingFinished: it is a multi-line editor, where
// Return inserts a newline rather than committing. Without this the note
// would reach the working copy only for whichever row happened to be
// current when Save was pressed, so a note typed on one rule and then
// followed by a click on another would be silently discarded.
connect(m_note, &QPlainTextEdit::textChanged,
this, &TagRulesDialog::applyEditsToCurrentRule);
addRow(false);
updateExclusionsVisibility();
reloadList();
showWarnings();
}
void TagRulesDialog::showWarnings()
{
const QStringList warnings = m_rules.warnings();
if (warnings.isEmpty()) {
m_warningLabel->setVisible(false);
return;
}
m_warningLabel->setText(
tr("%n rule(s) could not be read and were skipped: %1", "",
warnings.size()).arg(warnings.join(QStringLiteral("; "))));
m_warningLabel->setVisible(true);
}
void TagRulesDialog::fillItem(QTreeWidgetItem *item, const TagRule &rule) const
{
item->setCheckState(ColumnEnabled,
rule.enabled ? Qt::Checked : Qt::Unchecked);
item->setText(ColumnStage, QString::number(rule.stage));
item->setText(ColumnId, rule.id);
QStringList tags;
for (const QString &tag : rule.add)
tags.append(QStringLiteral("+") + tag);
for (const QString &tag : rule.remove)
tags.append(QStringLiteral("-") + tag);
item->setText(ColumnTags, tags.join(QStringLiteral(" ")));
}
void TagRulesDialog::reloadList()
{
// Guards the setCurrentItem below. Selecting a row emits
// currentItemChanged, and onSelectionChanged() would load that rule into
// the form; the counts column is also rebuilt from nothing here, so any
// count already shown is dropped rather than left against the wrong row.
m_reloading = true;
m_list->clear();
for (const TagRule &rule : m_working) {
auto *item = new QTreeWidgetItem(m_list);
fillItem(item, rule);
}
m_list->resizeColumnToContents(ColumnEnabled);
m_list->resizeColumnToContents(ColumnStage);
m_reloading = false;
if (!m_working.isEmpty())
m_list->setCurrentItem(m_list->topLevelItem(0));
}
int TagRulesDialog::currentIndex() const
{
return m_list->currentItem()
? m_list->indexOfTopLevelItem(m_list->currentItem())
: -1;
}
void TagRulesDialog::onSelectionChanged()
{
const int index = currentIndex();
if (index < 0 || index >= m_working.size())
return;
const TagRule &rule = m_working.at(index);
// The note's textChanged fires from setPlainText below, which would then
// write the rule just loaded back over the rule now current. Harmless when
// they are the same rule, destructive when the selection is what changed.
const QSignalBlocker blockNote(m_note);
m_id->setText(rule.id);
m_stage->setValue(rule.stage);
m_enabled->setChecked(rule.enabled);
m_add->setText(rule.add.join(QStringLiteral(", ")));
m_remove->setText(rule.remove.join(QStringLiteral(", ")));
m_query->setText(rule.query);
m_note->setPlainText(rule.note);
}
void TagRulesDialog::applyEditsToCurrentRule()
{
if (m_reloading)
return;
const int index = currentIndex();
if (index < 0 || index >= m_working.size())
return;
TagRule &rule = m_working[index];
rule.id = m_id->text().trimmed();
rule.stage = m_stage->value();
rule.enabled = m_enabled->isChecked();
rule.add = splitTags(m_add->text());
rule.remove = splitTags(m_remove->text());
rule.query = m_query->text().trimmed();
rule.note = m_note->toPlainText();
fillItem(m_list->topLevelItem(index), rule);
}
void TagRulesDialog::onAddRule()
{
// Flushed first: reloadList() rebuilds every row from m_working, so an
// edit still sitting in the form would be painted away by its own reload.
applyEditsToCurrentRule();
TagRule rule;
rule.id = QStringLiteral("new-rule");
rule.query = QStringLiteral("from:sender@example.com");
rule.add = { QStringLiteral("tag") };
m_working.append(rule);
reloadList();
m_list->setCurrentItem(m_list->topLevelItem(m_working.size() - 1));
}
void TagRulesDialog::onCopyRule()
{
applyEditsToCurrentRule();
const int index = currentIndex();
if (index < 0 || index >= m_working.size())
return;
TagRule copy = m_working.at(index);
copy.id += QStringLiteral("-copy");
m_working.insert(index + 1, copy);
reloadList();
m_list->setCurrentItem(m_list->topLevelItem(index + 1));
}
void TagRulesDialog::onDeleteRule()
{
const int index = currentIndex();
if (index < 0 || index >= m_working.size())
return;
m_working.removeAt(index);
reloadList();
}
QStringList TagRulesDialog::countQueries() const
{
QStringList queries;
for (const TagRule &rule : m_working)
queries.append(rule.query);
return queries;
}
void TagRulesDialog::setCounts(const QVector<int> &counts)
{
for (int i = 0; i < counts.size() && i < m_list->topLevelItemCount(); ++i) {
// -1 is the worker's "this query could not be run", which for a rule
// means the query is malformed. Saying so beats showing a number.
m_list->topLevelItem(i)->setText(
ColumnCount,
counts.at(i) < 0 ? tr("invalid")
: QString::number(counts.at(i)));
}
m_list->resizeColumnToContents(ColumnCount);
}
void TagRulesDialog::onSave()
{
applyEditsToCurrentRule();
m_rules.setRules(m_working);
if (!m_rules.save()) {
QMessageBox::warning(this, tr("Tagging rules"),
tr("Could not write %1.")
.arg(TagRules::defaultPath()));
return;
}
accept();
}
TagRulesDialog::Row *TagRulesDialog::addRow(bool exclusion)
{
Row row;
row.container = new QWidget(m_builder);
auto *layout = new QHBoxLayout(row.container);
layout->setContentsMargins(0, 0, 0, 0);
row.field = new QComboBox(row.container);
for (const FieldEntry &entry : kFields)
row.field->addItem(tr(entry.label), int(entry.field));
row.op = new QComboBox(row.container);
row.value = new QLineEdit(row.container);
auto *plus = new QPushButton(QStringLiteral("+"), row.container);
auto *minus = new QPushButton(QStringLiteral("-"), row.container);
plus->setFixedWidth(30);
minus->setFixedWidth(30);
layout->addWidget(row.field);
layout->addWidget(row.op);
layout->addWidget(row.value, 1);
layout->addWidget(plus);
layout->addWidget(minus);
QList<Row> &rows = exclusion ? m_exclusionRows : m_rows;
QVBoxLayout *target = exclusion ? m_exclusionsLayout : m_rowsLayout;
rows.append(row);
target->addWidget(row.container);
connect(row.field, &QComboBox::currentIndexChanged, this,
[this, exclusion](int) {
populateOperators(exclusion);
syncQueryLine();
});
connect(row.op, &QComboBox::currentIndexChanged,
this, [this](int) { syncQueryLine(); });
connect(row.value, &QLineEdit::textEdited,
this, [this](const QString &) { syncQueryLine(); });
connect(plus, &QPushButton::clicked, this, [this, exclusion] {
addRow(exclusion);
syncQueryLine();
});
QWidget *container = row.container;
connect(minus, &QPushButton::clicked, this, [this, exclusion, container] {
const QList<Row> &list = exclusion ? m_exclusionRows : m_rows;
for (int i = 0; i < list.size(); ++i) {
if (list.at(i).container == container) {
removeRow(exclusion, i);
break;
}
}
syncQueryLine();
});
populateOperators(exclusion);
updateExclusionsVisibility();
return &rows.last();
}
void TagRulesDialog::removeRow(bool exclusion, int index)
{
QList<Row> &rows = exclusion ? m_exclusionRows : m_rows;
if (index < 0 || index >= rows.size())
return;
// The positive section keeps at least one row: a rule with no rows has an
// empty query, which is reachable by clearing the value rather than by
// deleting the last row out from under the user.
if (!exclusion && rows.size() == 1) {
rows[0].value->clear();
return;
}
delete rows.at(index).container;
rows.removeAt(index);
updateExclusionsVisibility();
}
void TagRulesDialog::updateExclusionsVisibility()
{
// Most rules have no exclusions, so an empty block on every rule is noise.
const bool any = !m_exclusionRows.isEmpty();
m_exclusionsHeader->setVisible(any);
}
void TagRulesDialog::populateOperators(bool exclusion)
{
const QList<Row> &rows = exclusion ? m_exclusionRows : m_rows;
for (const Row &row : rows) {
const auto field = RuleTerm::Field(row.field->currentData().toInt());
const QString had = row.op->currentText();
QSignalBlocker block(row.op);
row.op->clear();
switch (field) {
case RuleTerm::Tag:
case RuleTerm::Folder:
row.op->addItem(tr("is"), int(RuleTerm::Is));
row.op->addItem(tr("is not"), int(RuleTerm::IsNot));
break;
case RuleTerm::Attachment:
row.op->addItem(tr("has"), int(RuleTerm::Has));
row.op->addItem(tr("has not"), int(RuleTerm::HasNot));
break;
case RuleTerm::Date:
row.op->addItem(tr("before"), int(RuleTerm::Before));
row.op->addItem(tr("after"), int(RuleTerm::After));
break;
default:
row.op->addItem(tr("contains"), int(RuleTerm::Contains));
row.op->addItem(tr("contains not"), int(RuleTerm::ContainsNot));
row.op->addItem(tr("is"), int(RuleTerm::Is));
row.op->addItem(tr("is not"), int(RuleTerm::IsNot));
break;
}
const int restored = row.op->findText(had);
if (restored >= 0)
row.op->setCurrentIndex(restored);
}
}
void TagRulesDialog::syncQueryLine()
{
RuleQuery query;
query.parsed = true;
query.join = m_matchAny->isChecked() ? RuleQuery::Any : RuleQuery::All;
for (const Row &row : m_rows) {
const QString value = row.value->text().trimmed();
if (value.isEmpty())
continue;
query.terms.append({RuleTerm::Field(row.field->currentData().toInt()),
RuleTerm::Op(row.op->currentData().toInt()),
value});
}
for (const Row &row : m_exclusionRows) {
const QString value = row.value->text().trimmed();
if (value.isEmpty())
continue;
query.exclusions.append(
{RuleTerm::Field(row.field->currentData().toInt()),
RuleTerm::Op(row.op->currentData().toInt()),
value});
}
m_query->setText(query.compile());
}
|