adblocksettingwidget.cpp 18.2 KB
Newer Older
1 2 3 4
/* ============================================================
*
* This file is a part of the rekonq project
*
Laurent Montel's avatar
Laurent Montel committed
5
* Copyright (c) 2013-2018 Montel Laurent <montel@kde.org>
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
* based on code from rekonq
* Copyright (C) 2010-2012 by Andrea Diamantini <adjam7 at gmail dot com>
*
*
* 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) version 3 or any later version
* accepted by the membership of KDE e.V. (or its successor approved
* by the membership of KDE e.V.), which shall act as a proxy
* defined in Section 14 of version 3 of the license.
*
* 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
Laurent Montel's avatar
Laurent Montel committed
24
* along with this program.  If not, see <https://www.gnu.org/licenses/>.
25 26 27 28 29 30
*
* ============================================================ */

// Self Includes
#include "adblocksettingwidget.h"
#include "ui_settings_adblock.h"
Laurent Montel's avatar
Laurent Montel committed
31
#include "globalsettings_webengineurlinterceptoradblock.h"
32
#include "adblockaddsubscriptiondialog.h"
Laurent Montel's avatar
Laurent Montel committed
33
#include "adblockinterceptor_debug.h"
34

Laurent Montel's avatar
Laurent Montel committed
35
#include "adblockmanager.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#include "adblockshowlistdialog.h"
#include "adblockutil.h"
#include "PimCommon/ConfigureImmutableWidgetUtils"
using namespace PimCommon::ConfigureImmutableWidgetUtils;

#include "PimCommon/PimUtil"

// KDE Includes
#include <KSharedConfig>

#include <QIcon>

#include <KMessageBox>
#include <KLocalizedString>
#include <QWhatsThisClickedEvent>

// Qt Includes
#include <QWhatsThis>
#include <QListWidgetItem>
#include <QFile>
#include <QPointer>
#include <QTextStream>
#include <QStandardPaths>
#include <QRegularExpression>
60
#include <QDir>
61
#include <KRun>
Laurent Montel's avatar
Laurent Montel committed
62
#include <adblocksubscription.h>
63 64 65 66 67 68 69 70 71 72 73 74 75

using namespace AdBlock;
AdBlockSettingWidget::AdBlockSettingWidget(QWidget *parent)
    : QWidget(parent)
    , mChanged(false)
{
    mUi = new Ui::adblock;
    mUi->setupUi(this);

    mUi->hintLabel->setText(i18n("<qt>Filter expression (e.g. <tt>http://www.example.com/ad/*</tt>, <a href=\"filterhelp\">more information</a>):"));
    connect(mUi->hintLabel, &QLabel::linkActivated, this, &AdBlockSettingWidget::slotInfoLinkActivated);
    mUi->hintLabel->setContextMenuPolicy(Qt::NoContextMenu);

Laurent Montel's avatar
Laurent Montel committed
76
    mUi->manualFiltersListWidget->setSelectionMode(QAbstractItemView::ExtendedSelection);
77 78 79 80 81 82 83 84 85

    mUi->searchLine->setListWidget(mUi->manualFiltersListWidget);

    mUi->insertButton->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
    connect(mUi->insertButton, &QToolButton::clicked, this, &AdBlockSettingWidget::insertRule);

    mUi->removeButton->setIcon(QIcon::fromTheme(QStringLiteral("list-remove")));
    connect(mUi->removeButton, &QPushButton::clicked, this, &AdBlockSettingWidget::removeRule);
    connect(mUi->removeSubscription, &QPushButton::clicked, this, &AdBlockSettingWidget::slotRemoveSubscription);
Laurent Montel's avatar
Laurent Montel committed
86
    connect(mUi->manualFiltersListWidget, &QListWidget::itemChanged, this, &AdBlockSettingWidget::slotManualFiltersChanged);
Laurent Montel's avatar
Laurent Montel committed
87
    connect(mUi->manualFiltersListWidget, &QListWidget::itemSelectionChanged, this, &AdBlockSettingWidget::slotSelectionChanged);
88 89 90 91 92 93 94
    mUi->spinBox->setSuffix(ki18np(" day", " days"));

    mUi->removeSubscription->setEnabled(false);
    mUi->showList->setEnabled(false);
    // Q_EMIT changed signal
    connect(mUi->checkEnableAdblock, &QCheckBox::stateChanged, this, &AdBlockSettingWidget::hasChanged);
    connect(mUi->checkHideAds, &QCheckBox::stateChanged, this, &AdBlockSettingWidget::hasChanged);
Laurent Montel's avatar
Laurent Montel committed
95
    connect(mUi->spinBox, QOverload<int>::of(&KPluralHandlingSpinBox::valueChanged), this, &AdBlockSettingWidget::hasChanged);
96 97 98 99 100 101 102 103 104 105 106
    connect(mUi->addFilters, &QPushButton::clicked, this, &AdBlockSettingWidget::slotAddFilter);
    connect(mUi->showList, &QPushButton::clicked, this, &AdBlockSettingWidget::slotShowList);
    connect(mUi->editFilter, &QPushButton::clicked, this, &AdBlockSettingWidget::slotEditFilter);

    connect(mUi->automaticFiltersListWidget, &AdBlock::AdBlockListWidget::itemChanged, this, &AdBlockSettingWidget::hasChanged);
    connect(mUi->automaticFiltersListWidget, &AdBlock::AdBlockListWidget::currentItemChanged, this, &AdBlockSettingWidget::slotUpdateButtons);
    connect(mUi->automaticFiltersListWidget, &AdBlock::AdBlockListWidget::itemDoubleClicked, this, &AdBlockSettingWidget::slotAutomaticFilterDouble);

    connect(mUi->importFilters, &QPushButton::clicked, this, &AdBlockSettingWidget::slotImportFilters);
    connect(mUi->exportFilters, &QPushButton::clicked, this, &AdBlockSettingWidget::slotExportFilters);
    connect(mUi->addFilterLineEdit, &QLineEdit::textChanged, this, &AdBlockSettingWidget::slotManualFilterLineEditTextChanged);
Laurent Montel's avatar
Laurent Montel committed
107
    slotSelectionChanged();
108 109 110 111 112 113 114 115
    mUi->insertButton->setEnabled(false);
}

AdBlockSettingWidget::~AdBlockSettingWidget()
{
    delete mUi;
}

Laurent Montel's avatar
Laurent Montel committed
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
void AdBlockSettingWidget::slotManualFiltersChanged(QListWidgetItem *item)
{
    if (!mBlockUpdate) {
        const int offset = mUi->manualFiltersListWidget->row(item);
        if (offset >= 0) {
            const AdBlockRule *oldRule = mCustomSubscription->rule(mUi->manualFiltersListWidget->row(item));
            if (item->checkState() == Qt::Checked && !oldRule->isEnabled()) {
                const AdBlockRule *rule = mCustomSubscription->enableRule(offset);
            } else if (item->checkState() == Qt::Unchecked && oldRule->isEnabled()) {
                const AdBlockRule *rule = mCustomSubscription->disableRule(offset);
            } else if (mCustomSubscription->canEditRules()) {
                AdBlockRule *newRule = new AdBlockRule(item->text(), mCustomSubscription);
                const AdBlockRule *rule = mCustomSubscription->replaceRule(newRule, offset);
            }
            hasChanged();
        }
    }
}

135 136
void AdBlockSettingWidget::slotManualFilterLineEditTextChanged(const QString &text)
{
Laurent Montel's avatar
Laurent Montel committed
137
    mUi->insertButton->setEnabled(!text.trimmed().isEmpty());
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
}

void AdBlockSettingWidget::slotEditFilter()
{
    QListWidgetItem *item = mUi->manualFiltersListWidget->currentItem();
    if (item) {
        mUi->manualFiltersListWidget->editItem(item);
    }
}

void AdBlockSettingWidget::slotUpdateButtons()
{
    const bool enabled = mUi->automaticFiltersListWidget->currentItem();
    mUi->removeSubscription->setEnabled(enabled);
    mUi->showList->setEnabled(enabled);
}

void AdBlockSettingWidget::slotInfoLinkActivated(const QString &url)
{
    Q_UNUSED(url)

    const QString href = QStringLiteral("https://adblockplus.org/en/filters");
    const QString hintHelpString = i18n("<qt><p>Enter an expression to filter. Filters can be defined as either:"
                                        "<ul><li>a shell-style wildcard, e.g. <tt>http://www.example.com/ads*</tt>, "
                                        "the wildcards <tt>*?[]</tt> may be used</li>"
                                        "<li>a full regular expression by surrounding the string with '<tt>/</tt>', "
                                        "e.g. <tt>/\\/(ad|banner)\\./</tt></li></ul>"
                                        "<p>Any filter string can be preceded by '<tt>@@</tt>' to whitelist (allow) any matching URL, "
                                        "which takes priority over any blacklist (blocking) filter.<br><a href=\'%1\'>%2</a></qt>", href, i18n("More information"));

    QWhatsThis::showText(QCursor::pos(), hintHelpString, this);
}

bool AdBlockSettingWidget::event(QEvent *event)
{
    if (event->type() == QEvent::WhatsThisClicked) {
        QWhatsThisClickedEvent *clicked = static_cast<QWhatsThisClickedEvent *>(event);
        new KRun(QUrl(clicked->href()), this);
        return true;
    }
    return QWidget::event(event);
}

void AdBlockSettingWidget::insertRule()
{
    const QString rule = mUi->addFilterLineEdit->text();
    if (rule.isEmpty()) {
        return;
    }
    const int numberItem(mUi->manualFiltersListWidget->count());
    for (int i = 0; i < numberItem; ++i) {
        if (mUi->manualFiltersListWidget->item(i)->text() == rule) {
            mUi->addFilterLineEdit->clear();
            return;
        }
    }

    addManualFilter(rule);
    mUi->exportFilters->setEnabled(mUi->manualFiltersListWidget->count() > 0);
    mUi->addFilterLineEdit->clear();
    hasChanged();
}

void AdBlockSettingWidget::removeRule()
{
203
    const QList<QListWidgetItem *> select = mUi->manualFiltersListWidget->selectedItems();
204 205 206
    if (select.isEmpty()) {
        return;
    }
207
    if (KMessageBox::No == KMessageBox::warningYesNo(this,
Yuri Chornoivan's avatar
Yuri Chornoivan committed
208
                                                     i18np("Do you want to remove this rule?", "Do you want to remove these rules?", select.count()),
209
                                                     i18n("Remove"))) {
Laurent Montel's avatar
Laurent Montel committed
210
        return;
211
    }
212
    for (QListWidgetItem *item : select) {
213 214 215 216 217 218 219 220 221 222 223
        delete item;
    }
    mUi->exportFilters->setEnabled(mUi->manualFiltersListWidget->count() > 0);
    hasChanged();
}

void AdBlockSettingWidget::doResetToDefaultsOther()
{
    const bool bUseDefaults = AdBlock::AdBlockSettings::self()->useDefaults(true);
    loadWidget(mUi->checkEnableAdblock, AdBlock::AdBlockSettings::self()->adBlockEnabledItem());
    mUi->tabWidget->setEnabled(AdBlock::AdBlockSettings::self()->adBlockEnabled());
224
    loadWidget(mUi->checkHideAds, AdBlock::AdBlockSettings::self()->hideAdsEnabledItem());
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    loadWidget(mUi->spinBox, AdBlock::AdBlockSettings::self()->adBlockUpdateIntervalItem());
    AdBlock::AdBlockSettings::self()->useDefaults(bUseDefaults);
}

void AdBlockSettingWidget::doLoadFromGlobalSettings()
{
    mUi->manualFiltersListWidget->clear();
    mUi->automaticFiltersListWidget->clear();
    loadWidget(mUi->checkEnableAdblock, AdBlock::AdBlockSettings::self()->adBlockEnabledItem());

    // update enabled status
    mUi->tabWidget->setEnabled(AdBlock::AdBlockSettings::self()->adBlockEnabled());
    loadWidget(mUi->checkHideAds, AdBlock::AdBlockSettings::self()->hideAdsEnabledItem());
    loadWidget(mUi->spinBox, AdBlock::AdBlockSettings::self()->adBlockUpdateIntervalItem());
    // ------------------------------------------------------------------------------

    // automatic filters
Laurent Montel's avatar
Laurent Montel committed
242 243 244 245 246 247 248 249 250 251 252 253
    for (AdBlockSubscription *subscription : AdblockManager::self()->subscriptions()) {
        const QString url = subscription->url().toString();
        const QString name = subscription->title();
        if (!url.isEmpty()) {
            AdBlockListwidgetItem *subItem = new AdBlockListwidgetItem(mUi->automaticFiltersListWidget);
            subItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
            subItem->setSubscription(subscription);
            if (subscription->enabled()) {
                subItem->setCheckState(Qt::Checked);
            } else {
                subItem->setCheckState(Qt::Unchecked);
            }
254

Laurent Montel's avatar
Laurent Montel committed
255 256 257 258 259 260 261 262 263 264 265 266
            subItem->setData(UrlList, url);
            subItem->setText(name);
        } else { //Custom .
            mCustomSubscription = subscription;
            mBlockUpdate = true;
            for (AdBlockRule *rule : subscription->allRules()) {
                QListWidgetItem *subItem = new QListWidgetItem(mUi->manualFiltersListWidget);
                subItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEditable);
                subItem->setCheckState(rule->isEnabled() ? Qt::Checked : Qt::Unchecked);
                subItem->setText(rule->filter());
            }
            mBlockUpdate = false;
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
        }
    }

    // ------------------------------------------------------------------------------
    updateCheckBox();
}

void AdBlockSettingWidget::save()
{
    if (!mChanged) {
        return;
    }

    // General settings
    saveCheckBox(mUi->checkEnableAdblock, AdBlock::AdBlockSettings::self()->adBlockEnabledItem());
    saveCheckBox(mUi->checkHideAds, AdBlock::AdBlockSettings::self()->hideAdsEnabledItem());
    saveSpinBox(mUi->spinBox, AdBlock::AdBlockSettings::self()->adBlockUpdateIntervalItem());

Laurent Montel's avatar
Laurent Montel committed
285
    mCustomSubscription->saveSubscription();
286 287
    mChanged = false;
    Q_EMIT changed(false);
Laurent Montel's avatar
Laurent Montel committed
288
    AdBlock::AdBlockSettings::self()->save();
Laurent Montel's avatar
Laurent Montel committed
289
    AdBlock::AdblockManager::self()->save();
Laurent Montel's avatar
Laurent Montel committed
290
    AdBlock::AdblockManager::self()->reloadConfig();
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
}

void AdBlockSettingWidget::updateCheckBox()
{
    // update enabled status
    mUi->checkHideAds->setEnabled(mUi->checkEnableAdblock->isChecked());
    mUi->tabWidget->setEnabled(mUi->checkEnableAdblock->isChecked());
}

void AdBlockSettingWidget::hasChanged()
{
    updateCheckBox();
    mChanged = true;
    Q_EMIT changed(true);
    Q_EMIT settingsChanged();
}

bool AdBlockSettingWidget::changed() const
{
    return mChanged;
}

void AdBlockSettingWidget::slotAddFilter()
{
    QStringList excludeList;
    const int numberItem(mUi->automaticFiltersListWidget->count());
    excludeList.reserve(numberItem);
    for (int i = 0; i < numberItem; ++i) {
        excludeList << mUi->automaticFiltersListWidget->item(i)->text();
    }
    QPointer<AdBlock::AdBlockAddSubscriptionDialog> dlg = new AdBlock::AdBlockAddSubscriptionDialog(excludeList, this);
    if (dlg->exec()) {
        QString name;
        QString url;
        dlg->selectedList(name, url);
Laurent Montel's avatar
Laurent Montel committed
326 327 328 329 330 331 332 333 334 335
        if (AdBlockSubscription *subscription = AdblockManager::self()->addSubscription(name, url)) {
            AdBlockListwidgetItem *subItem = new AdBlockListwidgetItem(mUi->automaticFiltersListWidget);
            subItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled);
            subItem->setCheckState(Qt::Checked);
            subItem->setText(name);
            subItem->setData(UrlList, url);
            subItem->setData(PathList, QString());
            subItem->setSubscription(subscription);
            hasChanged();
        }
336 337 338 339 340 341 342 343 344
    }
    delete dlg;
}

void AdBlockSettingWidget::slotRemoveSubscription()
{
    QListWidgetItem *item = mUi->automaticFiltersListWidget->currentItem();
    if (item) {
        if (KMessageBox::questionYesNo(this, i18n("Do you want to delete list \"%1\"?", item->text()), i18n("Delete current list")) == KMessageBox::Yes) {
Laurent Montel's avatar
Laurent Montel committed
345 346 347 348 349
            AdBlockListwidgetItem *subItem = dynamic_cast<AdBlockListwidgetItem *>(item);
            if (subItem) {
                if (AdblockManager::self()->removeSubscription(subItem->subscription())) {
                    hasChanged();
                    delete subItem;
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
                }
            }
        }
    }
}

void AdBlockSettingWidget::slotShowList()
{
    showAutomaticFilterList(mUi->automaticFiltersListWidget->currentItem());
}

void AdBlockSettingWidget::showAutomaticFilterList(QListWidgetItem *item)
{
    if (item) {
        QPointer<AdBlockShowListDialog> dlg = new AdBlockShowListDialog(true, this);
        dlg->setListName(item->text());
        dlg->setAdBlockListPath(item->data(PathList).toString(), item->data(UrlList).toString());
        connect(dlg.data(), &AdBlockShowListDialog::deleteList, this, &AdBlockSettingWidget::slotDeleteList);
        dlg->exec();
        delete dlg;
    }
}

void AdBlockSettingWidget::slotDeleteList(const QString &listName)
{
Laurent Montel's avatar
Laurent Montel committed
375
    AdBlockListwidgetItem *item = dynamic_cast<AdBlockListwidgetItem *>(mUi->automaticFiltersListWidget->currentItem());
376
    if (item && item->text() == listName) {
Laurent Montel's avatar
Laurent Montel committed
377 378 379
        if (AdblockManager::self()->removeSubscription(item->subscription())) {
            delete item;
            hasChanged();
380 381 382 383 384 385 386
        }
    }
}

void AdBlockSettingWidget::slotImportFilters()
{
    const QString filter = i18n("All Files (*)");
387
    const QString result = PimCommon::Util::loadToFile(filter, this, QUrl(), i18n("Import Filters"));
388 389 390 391 392 393 394 395 396 397 398 399
    if (result.isEmpty()) {
        return;
    }
    const QStringList listFilter = result.split(QLatin1Char('\n'));
    QStringList excludeFilter;
    const int numberOfElements(mUi->manualFiltersListWidget->count());
    excludeFilter.reserve(numberOfElements);
    for (int i = 0; i < numberOfElements; ++i) {
        QListWidgetItem *subItem = mUi->manualFiltersListWidget->item(i);
        excludeFilter.append(subItem->text());
    }

400
    for (const QString &element : listFilter) {
401 402 403 404 405 406 407 408 409 410 411 412
        if (element == QLatin1String("\n")) {
            continue;
        }
        if (excludeFilter.contains(element)) {
            continue;
        }
        addManualFilter(element);
    }
}

void AdBlockSettingWidget::addManualFilter(const QString &text, const QStringList &excludeRules)
{
Laurent Montel's avatar
Laurent Montel committed
413 414 415 416 417 418 419 420 421 422 423
    AdBlockRule *rule = new AdBlockRule(text, mCustomSubscription);
    if (excludeRules.contains(text)) {
        rule->setEnabled(false);
    }
    const int offset = mCustomSubscription->addRule(rule);
    if (offset >= 0) {
        QListWidgetItem *subItem = new QListWidgetItem(mUi->manualFiltersListWidget);
        subItem->setFlags(Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable | Qt::ItemIsDragEnabled | Qt::ItemIsEditable);
        subItem->setCheckState(excludeRules.contains(text) ? Qt::Unchecked : Qt::Checked);
        subItem->setText(text);
    }
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
}

void AdBlockSettingWidget::slotExportFilters()
{
    const QString filter = i18n("All Files (*)");
    QString exportFilters;
    const int numberOfElement(mUi->manualFiltersListWidget->count());
    for (int i = 0; i < numberOfElement; ++i) {
        QListWidgetItem *subItem = mUi->manualFiltersListWidget->item(i);
        const QString stringRule = subItem->text();
        if (!stringRule.isEmpty()) {
            exportFilters += stringRule + QLatin1Char('\n');
        }
    }
    PimCommon::Util::saveTextAs(exportFilters, filter, this, QUrl(), i18n("Export Filters"));
}

void AdBlockSettingWidget::slotAutomaticFilterDouble(QListWidgetItem *item)
{
    showAutomaticFilterList(item);
}
Laurent Montel's avatar
Laurent Montel committed
445

Laurent Montel's avatar
Laurent Montel committed
446 447 448 449 450 451 452 453
void AdBlockSettingWidget::slotSelectionChanged()
{
    const int numberOfElement(mUi->manualFiltersListWidget->selectedItems().count());
    mUi->exportFilters->setEnabled(numberOfElement > 0);
    mUi->editFilter->setEnabled(numberOfElement == 1);
    mUi->removeButton->setEnabled(numberOfElement > 0);
}

Laurent Montel's avatar
Laurent Montel committed
454 455 456 457 458 459 460 461 462 463 464 465 466 467
AdBlockListwidgetItem::AdBlockListwidgetItem(QListWidget *parent)
    : QListWidgetItem(parent)
{
}

AdBlockSubscription *AdBlockListwidgetItem::subscription() const
{
    return mSubscription;
}

void AdBlockListwidgetItem::setSubscription(AdBlockSubscription *subscription)
{
    mSubscription = subscription;
}
Laurent Montel's avatar
Laurent Montel committed
468