searchpatternedit.cpp 24.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*

  Author: Marc Mutz <mutz@kde.org>

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  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 "searchpatternedit.h"
#include "widgethandler/rulewidgethandlermanager.h"
using MailCommon::RuleWidgetHandlerManager;
#include "mailcommon_debug.h"

25
#include <Libkdepim/LineEditCatchReturnKey>
26 27
#include <KLocalizedString>
#include <QPushButton>
28
#include <QLineEdit>
29
#include <QIcon>
Daniel Vrátil's avatar
Daniel Vrátil committed
30
#include <KComboBox>
31 32 33 34 35 36 37 38 39 40 41 42 43
#include <QButtonGroup>
#include <QByteArray>
#include <QHBoxLayout>
#include <QRadioButton>
#include <QStackedWidget>

// Definition of special rule field strings
// Note: Also see SearchRule::matches() and ruleFieldToEnglish() if
//       you change the following i18n-ized strings!
// Note: The index of the values in the following array has to correspond to
//       the value of the entries in the enum in SearchRuleWidget.

#undef I18N_NOOP
Daniel Vrátil's avatar
Daniel Vrátil committed
44
#define I18N_NOOP(t) nullptr, t
45 46 47 48 49 50 51 52 53 54 55 56 57

using namespace MailCommon;

static const struct {
    const char *internalName;
    const char *context;
    const char *displayName;

    QString getLocalizedDisplayName() const
    {
        return i18nc(context, displayName);
    }
} SpecialRuleFields[] = {
Laurent Montel's avatar
Laurent Montel committed
58 59 60 61 62
    { "<message>", I18N_NOOP("Complete Message")       },
    { "<body>", I18N_NOOP("Body of Message")          },
    { "<any header>", I18N_NOOP("Anywhere in Headers")    },
    { "<recipients>", I18N_NOOP("All Recipients")    },
    { "<size>", I18N_NOOP("Size in Bytes") },
63
    { "<age in days>", I18N_NOOP("Age in Days")   },
Laurent Montel's avatar
Laurent Montel committed
64 65
    { "<status>", I18N_NOOP("Message Status")        },
    { "<tag>", I18N_NOOP("Message Tag") },
66
    { "Subject", I18NC_NOOP("Subject of an email.", "Subject")  },
Laurent Montel's avatar
Laurent Montel committed
67
    { "From", I18N_NOOP("From")  },
68
    { "To", I18NC_NOOP("Receiver of an email.", "To")  },
Laurent Montel's avatar
Laurent Montel committed
69 70 71
    { "CC", I18N_NOOP("CC")  },
    { "Reply-To", I18N_NOOP("Reply To")  },
    { "Organization", I18N_NOOP("Organization")  },
72 73
    { "<date>", I18N_NOOP("Date")  },
    { "<encryption>", I18N_NOOP("Encryption") }
74
};
Laurent Montel's avatar
Laurent Montel committed
75 76
static const int SpecialRuleFieldsCount
    = sizeof(SpecialRuleFields) / sizeof(*SpecialRuleFields);
77 78 79 80 81 82 83

//=============================================================================
//
// class SearchRuleWidget
//
//=============================================================================

Laurent Montel's avatar
Laurent Montel committed
84 85
SearchRuleWidget::SearchRuleWidget(QWidget *parent, SearchRule::Ptr aRule, SearchPatternEdit::SearchPatternEditOptions options, SearchPatternEdit::SearchModeType modeType)
    : QWidget(parent)
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
{
    initFieldList(options);
    initWidget(modeType);

    if (aRule) {
        setRule(aRule);
    } else {
        reset();
    }
}

void SearchRuleWidget::setPatternEditOptions(SearchPatternEdit::SearchPatternEditOptions options)
{
    SearchRule::Ptr srule = rule();
    QByteArray currentText = srule->field();

    initFieldList(options);

    mRuleField->clear();
    mRuleField->addItems(mFilterFieldList);
    KCompletion *comp = mRuleField->completionObject();
    comp->clear();
    comp->insertItems(mFilterFieldList);
    mRuleField->setMaxCount(mRuleField->count());
    mRuleField->adjustSize();

    const bool headersOnly = (options & MailCommon::SearchPatternEdit::HeadersOnly);
    const bool notShowSize = (options & MailCommon::SearchPatternEdit::NotShowSize);
    const bool notShowDate = (options & MailCommon::SearchPatternEdit::NotShowDate);
    const bool notShowAbsoluteDates = (options & MailCommon::SearchPatternEdit::NotShowAbsoluteDate);
    const bool notShowTags = (options & MailCommon::SearchPatternEdit::NotShowTags);

    if (headersOnly && (currentText != "<message>") && (currentText != "<body>")) {
        mRuleField->setItemText(0, QString::fromLatin1(currentText));
    } else {
        mRuleField->setItemText(0, QString());
    }

    if (notShowSize && (currentText != "<size>")) {
        mRuleField->setItemText(0, QString::fromLatin1(currentText));
    } else {
        mRuleField->setItemText(0, QString());
    }

    if (notShowDate && (currentText != "<date>")) {
        mRuleField->setItemText(0, QString::fromLatin1(currentText));
    } else {
        mRuleField->setItemText(0, QString());
    }

    if (notShowAbsoluteDates && (currentText != "<age in days>")) {
        mRuleField->setItemText(0, QString::fromLatin1(currentText));
    } else {
        mRuleField->setItemText(0, QString());
    }
    if (notShowTags && (currentText != "<tag>")) {
        mRuleField->setItemText(0, QString::fromLatin1(currentText));
    } else {
        mRuleField->setItemText(0, QString());
    }
}

void SearchRuleWidget::initWidget(SearchPatternEdit::SearchModeType modeType)
{
    QHBoxLayout *hlay = new QHBoxLayout(this);
151
    hlay->setContentsMargins(0, 0, 0, 0);
152 153

    // initialize the header field combo box
Daniel Vrátil's avatar
Daniel Vrátil committed
154 155
    mRuleField = new KComboBox(this);
    mRuleField->setMinimumWidth(50);
156 157
    mRuleField->setObjectName(QStringLiteral("mRuleField"));
    mRuleField->setEditable(true);
158 159
    QLineEdit *edit = new QLineEdit;
    new KPIM::LineEditCatchReturnKey(edit, this);
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
    edit->setPlaceholderText(i18n("Choose or type your own criteria"));
    mRuleField->setToolTip(i18n("Choose or type your own criteria"));
    edit->setClearButtonEnabled(true);
    mRuleField->setLineEdit(edit);

    mRuleField->addItems(mFilterFieldList);
    KCompletion *comp = mRuleField->completionObject();
    comp->setIgnoreCase(true);
    comp->insertItems(mFilterFieldList);
    comp->setCompletionMode(KCompletion::CompletionPopupAuto);

    // don't show sliders when popping up this menu
    mRuleField->setMaxCount(mRuleField->count());
    mRuleField->adjustSize();
    hlay->addWidget(mRuleField);

    // initialize the function/value widget stack
    mFunctionStack = new QStackedWidget(this);
    //Don't expand the widget in vertical direction
    mFunctionStack->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed);

    hlay->addWidget(mFunctionStack);

    mValueStack = new QStackedWidget(this);
    hlay->addWidget(mValueStack);
    hlay->setStretchFactor(mValueStack, 10);

    mAdd = new QPushButton(this);
    mAdd->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
    mAdd->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
    hlay->addWidget(mAdd);

    mRemove = new QPushButton(this);
    mRemove->setIcon(QIcon::fromTheme(QStringLiteral("list-remove")));
    mRemove->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
    hlay->addWidget(mRemove);

Laurent Montel's avatar
Laurent Montel committed
197
    RuleWidgetHandlerManager::instance()->setIsAkonadiSearch(modeType == SearchPatternEdit::BalooMode);
198 199 200 201 202 203

    RuleWidgetHandlerManager::instance()->createWidgets(mFunctionStack, mValueStack, this);

    // redirect focus to the header field combo box
    setFocusProxy(mRuleField);

204
#if QT_VERSION < QT_VERSION_CHECK(5, 14, 0)
Daniel Vrátil's avatar
Daniel Vrátil committed
205
    connect(mRuleField, QOverload<const QString &>::of(&QComboBox::activated),
Laurent Montel's avatar
Laurent Montel committed
206
            this, &SearchRuleWidget::slotRuleFieldChanged);
207 208 209 210
#else
    connect(mRuleField, &QComboBox::textActivated,
            this, &SearchRuleWidget::slotRuleFieldChanged);
#endif
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
    connect(mRuleField, &QComboBox::editTextChanged,
            this, &SearchRuleWidget::slotRuleFieldChanged);
    connect(mRuleField, &QComboBox::editTextChanged,
            this, &SearchRuleWidget::fieldChanged);

    connect(mAdd, &QAbstractButton::clicked,
            this, &SearchRuleWidget::slotAddWidget);
    connect(mRemove, &QAbstractButton::clicked,
            this, &SearchRuleWidget::slotRemoveWidget);
}

void SearchRuleWidget::updateAddRemoveButton(bool addButtonEnabled, bool removeButtonEnabled)
{
    mAdd->setEnabled(addButtonEnabled);
    mRemove->setEnabled(removeButtonEnabled);
}

void SearchRuleWidget::slotAddWidget()
{
    Q_EMIT addWidget(this);
}

void SearchRuleWidget::slotRemoveWidget()
{
    Q_EMIT removeWidget(this);
}

void SearchRuleWidget::setRule(SearchRule::Ptr aRule)
{
    Q_ASSERT(aRule);

    qCDebug(MAILCOMMON_LOG) << "(" << aRule->asString() << ")";

    //--------------set the field
    int i = indexOfRuleField(aRule->field());

    mRuleField->blockSignals(true);

    if (i < 0) {   // not found -> user defined field
        mRuleField->setItemText(0, QString::fromLatin1(aRule->field()));
        i = 0;
    } else { // found in the list of predefined fields
        mRuleField->setItemText(0, QString());
    }

    mRuleField->setCurrentIndex(i);
    mRuleField->blockSignals(false);

    RuleWidgetHandlerManager::instance()->setRule(mFunctionStack, mValueStack, aRule);
}

SearchRule::Ptr SearchRuleWidget::rule() const
{
    const QByteArray ruleField = ruleFieldToEnglish(mRuleField->currentText());

Laurent Montel's avatar
Laurent Montel committed
266 267
    const SearchRule::Function function
        = RuleWidgetHandlerManager::instance()->function(ruleField, mFunctionStack);
268

Laurent Montel's avatar
Laurent Montel committed
269 270
    const QString value
        = RuleWidgetHandlerManager::instance()->value(ruleField, mFunctionStack, mValueStack);
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288

    return SearchRule::createInstance(ruleField, function, value);
}

void SearchRuleWidget::reset()
{
    mRuleField->blockSignals(true);
    mRuleField->setItemText(0, QString());
    mRuleField->setCurrentIndex(0);
    mRuleField->blockSignals(false);

    RuleWidgetHandlerManager::instance()->reset(mFunctionStack, mValueStack);
}

void SearchRuleWidget::slotFunctionChanged()
{
    const QByteArray ruleField = ruleFieldToEnglish(mRuleField->currentText());
    RuleWidgetHandlerManager::instance()->update(ruleField, mFunctionStack, mValueStack);
Laurent Montel's avatar
Laurent Montel committed
289 290
    const QString prettyValue
        = RuleWidgetHandlerManager::instance()->prettyValue(ruleField, mFunctionStack, mValueStack);
291 292 293 294 295 296 297 298

    Q_EMIT contentsChanged(prettyValue);
}

void SearchRuleWidget::slotValueChanged()
{
    const QByteArray ruleField = ruleFieldToEnglish(mRuleField->currentText());

Laurent Montel's avatar
Laurent Montel committed
299 300
    const QString prettyValue
        = RuleWidgetHandlerManager::instance()->prettyValue(ruleField, mFunctionStack, mValueStack);
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

    Q_EMIT contentsChanged(prettyValue);
}

void SearchRuleWidget::slotReturnPressed()
{
    Q_EMIT returnPressed();
}

QByteArray SearchRuleWidget::ruleFieldToEnglish(const QString &i18nVal)
{
    for (int i = 0; i < SpecialRuleFieldsCount; ++i) {
        if (i18nVal == SpecialRuleFields[i].getLocalizedDisplayName()) {
            return SpecialRuleFields[i].internalName;
        }
    }
    return i18nVal.toLatin1();
}

int SearchRuleWidget::ruleFieldToId(const QString &i18nVal)
{
    for (int i = 0; i < SpecialRuleFieldsCount; ++i) {
        if (i18nVal == SpecialRuleFields[i].getLocalizedDisplayName()) {
            return i;
        }
    }
    return -1; // no pseudo header
}

static QString displayNameFromInternalName(const QString &internal)
{
    for (int i = 0; i < SpecialRuleFieldsCount; ++i) {
        if (internal == QLatin1String(SpecialRuleFields[i].internalName)) {
            return SpecialRuleFields[i].getLocalizedDisplayName();
        }
    }
    return QLatin1String(internal.toLatin1());
}

int SearchRuleWidget::indexOfRuleField(const QByteArray &aName) const
{
    if (aName.isEmpty()) {
        return -1;
    }

    const QString i18n_aName = displayNameFromInternalName(QLatin1String(aName));
    const int nbRuleField = mRuleField->count();
    for (int i = 1; i < nbRuleField; ++i) {
        if (mRuleField->itemText(i) == i18n_aName) {
            return i;
        }
    }

    return -1;
}

void SearchRuleWidget::initFieldList(SearchPatternEdit::SearchPatternEditOptions options)
{
    const bool headersOnly = (options & MailCommon::SearchPatternEdit::HeadersOnly);
    const bool notShowAbsoluteDates = (options & MailCommon::SearchPatternEdit::NotShowAbsoluteDate);
    const bool notShowSize = (options & MailCommon::SearchPatternEdit::NotShowSize);
    const bool notShowDate = (options & MailCommon::SearchPatternEdit::NotShowDate);
    const bool notShowTags = (options & MailCommon::SearchPatternEdit::NotShowTags);

    mFilterFieldList.clear();
    mFilterFieldList.append(QString());   // empty entry for user input

    if (!headersOnly) {
        mFilterFieldList.append(SpecialRuleFields[Message].getLocalizedDisplayName());
        mFilterFieldList.append(SpecialRuleFields[Body].getLocalizedDisplayName());
    }
    mFilterFieldList.append(SpecialRuleFields[AnyHeader].getLocalizedDisplayName());
    mFilterFieldList.append(SpecialRuleFields[Recipients].getLocalizedDisplayName());
    if (!notShowSize) {
        mFilterFieldList.append(SpecialRuleFields[Size].getLocalizedDisplayName());
    }
    if (!notShowAbsoluteDates) {
        mFilterFieldList.append(SpecialRuleFields[AgeInDays].getLocalizedDisplayName());
    }

    mFilterFieldList.append(SpecialRuleFields[Subject].getLocalizedDisplayName());
    mFilterFieldList.append(SpecialRuleFields[From].getLocalizedDisplayName());
    mFilterFieldList.append(SpecialRuleFields[To].getLocalizedDisplayName());
    mFilterFieldList.append(SpecialRuleFields[CC].getLocalizedDisplayName());
    mFilterFieldList.append(SpecialRuleFields[Status].getLocalizedDisplayName());
    if (!notShowTags) {
        mFilterFieldList.append(SpecialRuleFields[Tag].getLocalizedDisplayName());
    }
    mFilterFieldList.append(i18n(SpecialRuleFields[ReplyTo].displayName));
    mFilterFieldList.append(i18n(SpecialRuleFields[Organization].displayName));

    if (!notShowDate) {
        mFilterFieldList.append(i18n(SpecialRuleFields[Date].displayName));
    }

396 397
    mFilterFieldList.append(i18n(SpecialRuleFields[Encryption].displayName));

398 399
    // these others only represent message headers and you can add to
    // them as you like
Laurent Montel's avatar
Laurent Montel committed
400 401 402 403 404 405
    mFilterFieldList.append(QStringLiteral("List-Id"));
    mFilterFieldList.append(QStringLiteral("Resent-From"));
    mFilterFieldList.append(QStringLiteral("X-Loop"));
    mFilterFieldList.append(QStringLiteral("X-Mailing-List"));
    mFilterFieldList.append(QStringLiteral("X-Spam-Flag"));
    mFilterFieldList.append(QStringLiteral("X-Spam-Status"));
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
}

void SearchRuleWidget::slotRuleFieldChanged(const QString &field)
{
    RuleWidgetHandlerManager::instance()->update(
        ruleFieldToEnglish(field), mFunctionStack, mValueStack);
}

//=============================================================================
//
// class KMFilterActionWidgetLister (the filter action editor)
//
//=============================================================================

SearchRuleWidgetLister::SearchRuleWidgetLister(QWidget *parent, SearchPatternEdit::SearchPatternEditOptions options, SearchPatternEdit::SearchModeType modeType)
421
    : KWidgetLister(false, 1, SearchPattern::filterRulesMaximumSize(), parent)
422
{
Laurent Montel's avatar
Laurent Montel committed
423
    mRuleList = nullptr;
424 425 426 427 428 429 430 431 432 433 434 435

    mTypeMode = modeType;
    mOptions = options;
}

SearchRuleWidgetLister::~SearchRuleWidgetLister()
{
}

void SearchRuleWidgetLister::setPatternEditOptions(SearchPatternEdit::SearchPatternEditOptions options)
{
    mOptions = options;
436 437
    const auto lst = widgets();
    for (QWidget *w : lst) {
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
        qobject_cast<SearchRuleWidget *>(w)->setPatternEditOptions(options);
    }
}

void SearchRuleWidgetLister::setRuleList(QList<SearchRule::Ptr> *aList)
{
    Q_ASSERT(aList);

    if (mRuleList && mRuleList != aList) {
        regenerateRuleListFromWidgets();
    }

    mRuleList = aList;

    if (!widgets().isEmpty()) {   // move this below next 'if'?
Laurent Montel's avatar
Laurent Montel committed
453
        widgets().constFirst()->blockSignals(true);
454 455 456 457
    }

    if (aList->isEmpty()) {
        slotClear();
Laurent Montel's avatar
Laurent Montel committed
458
        widgets().constFirst()->blockSignals(false);
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
        return;
    }

    int superfluousItems = (int)mRuleList->count() - widgetsMaximum();
    if (superfluousItems > 0) {
        qCDebug(MAILCOMMON_LOG) << "Clipping rule list to" << widgetsMaximum() << "items!";

        for (; superfluousItems; superfluousItems--) {
            mRuleList->removeLast();
        }
    }

    // set the right number of widgets
    setNumberOfShownWidgetsTo(qMax((int)mRuleList->count(), widgetsMinimum()));

    // load the actions into the widgets
    QList<QWidget *> widgetList = widgets();
    QList<SearchRule::Ptr>::const_iterator rIt;
    QList<SearchRule::Ptr>::const_iterator rItEnd(mRuleList->constEnd());
    QList<QWidget *>::const_iterator wIt = widgetList.constBegin();
    QList<QWidget *>::const_iterator wItEnd = widgetList.constEnd();
    for (rIt = mRuleList->constBegin();
Laurent Montel's avatar
Laurent Montel committed
481
         rIt != rItEnd && wIt != wItEnd; ++rIt, ++wIt) {
482 483 484 485 486 487 488
        qobject_cast<SearchRuleWidget *>(*wIt)->setRule((*rIt));
    }
    for (; wIt != wItEnd; ++wIt) {
        qobject_cast<SearchRuleWidget *>(*wIt)->reset();
    }

    Q_ASSERT(!widgets().isEmpty());
Laurent Montel's avatar
Laurent Montel committed
489
    widgets().constFirst()->blockSignals(false);
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
    updateAddRemoveButton();
}

void SearchRuleWidgetLister::slotAddWidget(QWidget *w)
{
    addWidgetAfterThisWidget(w);
    updateAddRemoveButton();
}

void SearchRuleWidgetLister::slotRemoveWidget(QWidget *w)
{
    removeWidget(w);
    updateAddRemoveButton();
}

void SearchRuleWidgetLister::reconnectWidget(SearchRuleWidget *w)
{
    connect(w, &SearchRuleWidget::addWidget,
            this, &SearchRuleWidgetLister::slotAddWidget, Qt::UniqueConnection);
    connect(w, &SearchRuleWidget::removeWidget,
            this, &SearchRuleWidgetLister::slotRemoveWidget, Qt::UniqueConnection);
}

void SearchRuleWidgetLister::updateAddRemoveButton()
{
    QList<QWidget *> widgetList = widgets();
    const int numberOfWidget(widgetList.count());
    bool addButtonEnabled = false;
    bool removeButtonEnabled = false;
    if (numberOfWidget <= widgetsMinimum()) {
        addButtonEnabled = true;
        removeButtonEnabled = false;
    } else if (numberOfWidget >= widgetsMaximum()) {
        addButtonEnabled = false;
        removeButtonEnabled = true;
    } else {
        addButtonEnabled = true;
        removeButtonEnabled = true;
    }
    QList<QWidget *>::ConstIterator wIt = widgetList.constBegin();
    QList<QWidget *>::ConstIterator wEnd = widgetList.constEnd();
    for (; wIt != wEnd; ++wIt) {
        SearchRuleWidget *w = qobject_cast<SearchRuleWidget *>(*wIt);
        w->updateAddRemoveButton(addButtonEnabled, removeButtonEnabled);
    }
}

void SearchRuleWidgetLister::reset()
{
    if (mRuleList) {
        regenerateRuleListFromWidgets();
    }

Laurent Montel's avatar
Laurent Montel committed
543
    mRuleList = nullptr;
544 545 546 547 548 549
    slotClear();
    updateAddRemoveButton();
}

QWidget *SearchRuleWidgetLister::createWidget(QWidget *parent)
{
Laurent Montel's avatar
Laurent Montel committed
550 551
    SearchRuleWidget *w
        = new SearchRuleWidget(parent, SearchRule::Ptr(), mOptions, mTypeMode);
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
    reconnectWidget(w);
    return w;
}

void SearchRuleWidgetLister::clearWidget(QWidget *aWidget)
{
    if (aWidget) {
        SearchRuleWidget *w = static_cast<SearchRuleWidget *>(aWidget);
        w->reset();
        reconnectWidget(w);
        updateAddRemoveButton();
    }
}

void SearchRuleWidgetLister::regenerateRuleListFromWidgets()
{
    if (!mRuleList) {
        return;
    }

    mRuleList->clear();

574 575
    const auto lst = widgets();
    for (const QWidget *w : lst) {
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
        SearchRule::Ptr r = qobject_cast<const SearchRuleWidget *>(w)->rule();
        if (r && !r->isEmpty()) {
            mRuleList->append(r);
        }
    }
    updateAddRemoveButton();
}

//=============================================================================
//
// class SearchPatternEdit
//
//=============================================================================

SearchPatternEdit::SearchPatternEdit(QWidget *parent, SearchPatternEditOptions options, SearchModeType modeType)
Laurent Montel's avatar
Laurent Montel committed
591 592
    : QWidget(parent)
    , mAllMessageRBtn(nullptr)
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
{
    setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    setObjectName(QStringLiteral("SearchPatternEdit"));
    initLayout(options, modeType);
}

SearchPatternEdit::~SearchPatternEdit()
{
}

void SearchPatternEdit::updateSearchPattern()
{
    mRuleLister->regenerateRuleListFromWidgets();
}

void SearchPatternEdit::setPatternEditOptions(SearchPatternEdit::SearchPatternEditOptions options)
{
    mRuleLister->setPatternEditOptions(options);
}

void SearchPatternEdit::initLayout(SearchPatternEditOptions options, SearchModeType modeType)
{
    QVBoxLayout *layout = new QVBoxLayout(this);
616
    layout->setContentsMargins(0, 0, 0, 0);
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647

    const bool matchAllMessages = (options & MailCommon::SearchPatternEdit::MatchAllMessages);
    //------------the radio buttons
    mAllRBtn = new QRadioButton(i18n("Match a&ll of the following"), this);
    mAnyRBtn = new QRadioButton(i18n("Match an&y of the following"), this);
    if (matchAllMessages) {
        mAllMessageRBtn = new QRadioButton(i18n("Match all messages"), this);
    }

    mAllRBtn->setObjectName(QStringLiteral("mAllRBtn"));
    mAllRBtn->setChecked(true);
    mAnyRBtn->setObjectName(QStringLiteral("mAnyRBtn"));
    mAnyRBtn->setChecked(false);
    if (matchAllMessages) {
        mAllMessageRBtn->setObjectName(QStringLiteral("mAllMessageRBtn"));
        mAllMessageRBtn->setChecked(false);
    }
    layout->addWidget(mAllRBtn);
    layout->addWidget(mAnyRBtn);
    if (matchAllMessages) {
        layout->addWidget(mAllMessageRBtn);
    }

    QButtonGroup *bg = new QButtonGroup(this);
    bg->addButton(mAllRBtn);
    bg->addButton(mAnyRBtn);
    if (matchAllMessages) {
        bg->addButton(mAllMessageRBtn);
    }

    //------------connect a few signals
Laurent Montel's avatar
Laurent Montel committed
648
    connect(bg, QOverload<QAbstractButton *>::of(&QButtonGroup::buttonClicked),
Laurent Montel's avatar
Laurent Montel committed
649
            this, &SearchPatternEdit::slotRadioClicked);
650 651

    //------------the list of SearchRuleWidget's
Laurent Montel's avatar
Laurent Montel committed
652 653
    mRuleLister
        = new SearchRuleWidgetLister(
Laurent Montel's avatar
Laurent Montel committed
654
              this, options, modeType);
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672

    mRuleLister->slotClear();

    if (!mRuleLister->widgets().isEmpty()) {
        const int numberOfWidget(mRuleLister->widgets().count());
        for (int i = 0; i < numberOfWidget; ++i) {
            SearchRuleWidget *srw = static_cast<SearchRuleWidget *>(mRuleLister->widgets().at(i));
            connect(srw, &SearchRuleWidget::fieldChanged,
                    this, &SearchPatternEdit::slotAutoNameHack);
            connect(srw, &SearchRuleWidget::contentsChanged,
                    this, &SearchPatternEdit::slotAutoNameHack);
            connect(srw, &SearchRuleWidget::returnPressed,
                    this, &SearchPatternEdit::returnPressed);
        }
    } else {
        qCDebug(MAILCOMMON_LOG) << "No first SearchRuleWidget, though slotClear() has been called!";
    }

Laurent Montel's avatar
Laurent Montel committed
673
    connect(mRuleLister, QOverload<QWidget *>::of(&SearchRuleWidgetLister::widgetAdded),
Laurent Montel's avatar
Laurent Montel committed
674 675
            this, &SearchPatternEdit::slotRuleAdded);
    connect(mRuleLister, QOverload<>::of(&SearchRuleWidgetLister::widgetRemoved), this, &SearchPatternEdit::patternChanged);
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
    connect(mRuleLister, &KPIM::KWidgetLister::clearWidgets, this, &SearchPatternEdit::patternChanged);

    layout->addWidget(mRuleLister);
}

void SearchPatternEdit::setSearchPattern(SearchPattern *aPattern)
{
    Q_ASSERT(aPattern);

    mRuleLister->setRuleList(aPattern);

    mPattern = aPattern;

    blockSignals(true);
    if (mPattern->op() == SearchPattern::OpOr) {
        mAnyRBtn->setChecked(true);
    } else if (mPattern->op() == SearchPattern::OpAnd) {
        mAllRBtn->setChecked(true);
    } else if (mAllMessageRBtn && (mPattern->op() == SearchPattern::OpAll)) {
        mAllMessageRBtn->setChecked(true);
    }
    mRuleLister->setEnabled(mPattern->op() != SearchPattern::OpAll);
    blockSignals(false);

    setEnabled(true);
    Q_EMIT patternChanged();
}

void SearchPatternEdit::reset()
{
    mRuleLister->reset();

    blockSignals(true);
    mAllRBtn->setChecked(true);
    blockSignals(false);

    setEnabled(false);
    Q_EMIT patternChanged();
}

void SearchPatternEdit::slotRadioClicked(QAbstractButton *aRBtn)
{
    if (mPattern) {
        if (aRBtn == mAllRBtn) {
            mPattern->setOp(SearchPattern::OpAnd);
        } else if (aRBtn == mAnyRBtn) {
            mPattern->setOp(SearchPattern::OpOr);
        } else if (aRBtn == mAllMessageRBtn) {
            mPattern->setOp(SearchPattern::OpAll);
        }
        mRuleLister->setEnabled(mPattern->op() != SearchPattern::OpAll);
        Q_EMIT patternChanged();
    }
}

void SearchPatternEdit::slotAutoNameHack()
{
    mRuleLister->regenerateRuleListFromWidgets();
    Q_EMIT maybeNameChanged();
    Q_EMIT patternChanged();
}

void SearchPatternEdit::slotRuleAdded(QWidget *newRuleWidget)
{
    SearchRuleWidget *srw = static_cast<SearchRuleWidget *>(newRuleWidget);
    connect(srw, &SearchRuleWidget::fieldChanged, this, &SearchPatternEdit::slotAutoNameHack);
    connect(srw, &SearchRuleWidget::contentsChanged, this, &SearchPatternEdit::slotAutoNameHack);
    connect(srw, &SearchRuleWidget::returnPressed, this, &SearchPatternEdit::returnPressed);
    Q_EMIT patternChanged();
}