cppinsertvirtualmethods.cpp 64.9 KB
Newer Older
1 2
/****************************************************************************
**
3 4
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
5 6 7 8 9 10 11
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
12 13 14
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
15
**
16 17 18 19 20 21 22
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
23 24 25 26 27 28
**
****************************************************************************/

#include "cppinsertvirtualmethods.h"
#include "cppquickfixassistant.h"

29
#include <coreplugin/coreicons.h>
30 31 32 33 34 35 36 37 38 39
#include <coreplugin/icore.h>
#include <cpptools/cppcodestylesettings.h>
#include <cpptools/cpptoolsreuse.h>
#include <cpptools/functionutils.h>
#include <cpptools/insertionpointlocator.h>
#include <texteditor/fontsettings.h>
#include <texteditor/texteditorsettings.h>

#include <cplusplus/CppRewriter.h>
#include <cplusplus/Overview.h>
40
#include <utils/changeset.h>
41
#include <utils/qtcassert.h>
42

43
#include <QAction>
44 45 46 47 48 49
#include <QCheckBox>
#include <QComboBox>
#include <QCoreApplication>
#include <QDialog>
#include <QDialogButtonBox>
#include <QGroupBox>
50
#include <QLineEdit>
51 52 53 54 55
#include <QPointer>
#include <QQueue>
#include <QSortFilterProxyModel>
#include <QStandardItemModel>
#include <QTextDocument>
56
#include <QToolButton>
57
#include <QTreeView>
58
#include <QVBoxLayout>
59

60 61 62 63 64 65 66 67 68 69
#ifdef WITH_TESTS

#include "cppeditorplugin.h"
#include "cppquickfix_test.h"

#include <QtTest>

#endif


70 71 72 73 74 75 76
using namespace CPlusPlus;
using namespace CppTools;
using namespace TextEditor;

namespace CppEditor {
namespace Internal {

77
class InsertVirtualMethodsModel;
78
class VirtualMethodsSettings;
79

80 81 82 83 84
class InsertVirtualMethodsDialog : public QDialog
{
    Q_OBJECT
public:
    enum CustomItemRoles {
85
        Reimplemented = Qt::UserRole
86 87 88 89 90 91 92 93 94 95
    };

    enum ImplementationMode {
        ModeOnlyDeclarations = 0x00000001,
        ModeInsideClass = 0x00000002,
        ModeOutsideClass = 0x00000004,
        ModeImplementationFile = 0x00000008
    };

    InsertVirtualMethodsDialog(QWidget *parent = 0);
96
    ~InsertVirtualMethodsDialog();
97 98
    void initGui();
    void initData();
99 100
    virtual void saveSettings();
    const VirtualMethodsSettings *settings() const;
101

102 103
    void setHasImplementationFile(bool file);
    void setHasReimplementedFunctions(bool functions);
104

105 106
    virtual bool gather();

107 108 109 110 111
protected:
    void setInsertOverrideReplacement(bool insert);
    void setOverrideReplacement(const QString &replacements);

private:
112
    void setHideReimplementedFunctions(bool hide);
113 114
    void updateOverrideReplacementsComboBox();

115 116
private:
    QTreeView *m_view;
117
    QLineEdit *m_filter;
118 119 120
    QCheckBox *m_hideReimplementedFunctions;
    QComboBox *m_insertMode;
    QCheckBox *m_virtualKeyword;
121 122 123
    QCheckBox *m_overrideReplacementCheckBox;
    QComboBox *m_overrideReplacementComboBox;
    QToolButton *m_clearUserAddedReplacementsButton;
124 125 126
    QDialogButtonBox *m_buttons;
    QList<bool> m_expansionStateNormal;
    QList<bool> m_expansionStateReimp;
127
    QStringList m_availableOverrideReplacements;
128 129 130
    bool m_hasImplementationFile;
    bool m_hasReimplementedFunctions;

131 132 133
protected:
    VirtualMethodsSettings *m_settings;

134 135 136 137
    void saveExpansionState();
    void restoreExpansionState();

public:
138
    InsertVirtualMethodsModel *classFunctionModel;
139 140 141 142 143 144
    QSortFilterProxyModel *classFunctionFilterModel;
};

} // namespace Internal
} // namespace CppEditor

145 146
Q_DECLARE_METATYPE(CppEditor::Internal::InsertVirtualMethodsDialog::ImplementationMode)

147 148
namespace {

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
class InsertVirtualMethodsItem
{
public:
    InsertVirtualMethodsItem(InsertVirtualMethodsItem *parent) :
        row(-1),
        m_parent(parent)
    {
    }

    virtual ~InsertVirtualMethodsItem()
    {
    }

    virtual QString description() const = 0;
    virtual Qt::ItemFlags flags() const = 0;
    virtual Qt::CheckState checkState() const = 0;

    InsertVirtualMethodsItem *parent() { return m_parent; }

    int row;

private:
    InsertVirtualMethodsItem *m_parent;
};

class FunctionItem;

class ClassItem : public InsertVirtualMethodsItem
{
public:
    ClassItem(const QString &className, const Class *clazz);
    ~ClassItem();

    QString description() const { return name; }
    Qt::ItemFlags flags() const;
    Qt::CheckState checkState() const;
185
    void removeFunction(int row);
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

    const Class *klass;
    const QString name;
    QList<FunctionItem *> functions;
};

class FunctionItem : public InsertVirtualMethodsItem
{
public:
    FunctionItem(const Function *func, const QString &functionName, ClassItem *parent);
    QString description() const;
    Qt::ItemFlags flags() const;
    Qt::CheckState checkState() const { return checked ? Qt::Checked : Qt::Unchecked; }

    const Function *function;
    InsertionPointLocator::AccessSpec accessSpec;
    bool reimplemented;
    bool alreadyFound;
    bool checked;
205
    FunctionItem *nextOverride;
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

private:
    QString name;
};

ClassItem::ClassItem(const QString &className, const Class *clazz) :
    InsertVirtualMethodsItem(0),
    klass(clazz),
    name(className)
{
}

ClassItem::~ClassItem()
{
    qDeleteAll(functions);
    functions.clear();
}

Qt::ItemFlags ClassItem::flags() const
{
    foreach (FunctionItem *func, functions) {
227
        if (!func->alreadyFound)
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
            return Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
    }

    return Qt::ItemIsSelectable;
}

Qt::CheckState ClassItem::checkState() const
{
    if (functions.isEmpty())
        return Qt::Unchecked;
    Qt::CheckState state = functions.first()->checkState();
    foreach (FunctionItem *function, functions) {
        Qt::CheckState functionState = function->checkState();
        if (functionState != state)
            return Qt::PartiallyChecked;
    }
    return state;
}

247 248 249 250 251 252 253 254 255
void ClassItem::removeFunction(int row)
{
    QTC_ASSERT(row >= 0 && row < functions.count(), return);
    functions.removeAt(row);
    // Update row number for all the following functions
    for (int r = row, total = functions.count(); r < total; ++r)
        functions[r]->row = r;
}

256 257 258 259 260
FunctionItem::FunctionItem(const Function *func, const QString &functionName, ClassItem *parent) :
    InsertVirtualMethodsItem(parent),
    function(func),
    reimplemented(false),
    alreadyFound(false),
261 262
    checked(false),
    nextOverride(this)
263 264 265 266 267 268 269 270 271 272 273
{
    name = functionName;
}

QString FunctionItem::description() const
{
    return name;
}

Qt::ItemFlags FunctionItem::flags() const
{
Orgad Shaneh's avatar
Orgad Shaneh committed
274
    Qt::ItemFlags res = Qt::NoItemFlags;
275
    if (!alreadyFound)
276 277 278 279
        res |= Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEnabled;
    return res;
}

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
QStringList defaultOverrideReplacements()
{
    return {
        QLatin1String("override"),
        QLatin1String("Q_DECL_OVERRIDE")
    };
}

QStringList sortedAndTrimmedStringListWithoutEmptyElements(const QStringList &list)
{
    QStringList result;
    foreach (const QString &replacement, list) {
        const QString trimmedReplacement = replacement.trimmed();
        if (!trimmedReplacement.isEmpty())
            result << trimmedReplacement;
    }
    result.sort();
    return result;
}

300 301 302 303 304
} // namespace

namespace CppEditor {
namespace Internal {

305
class VirtualMethodsSettings
306 307
{
public:
308
    void read()
309
    {
310 311 312 313 314 315 316 317 318 319
        QSettings *s = Core::ICore::settings();
        s->beginGroup(group());
        insertVirtualKeyword = s->value(insertVirtualKeywordKey(), false).toBool();
        hideReimplementedFunctions = s->value(hideReimplementedFunctionsKey(), false).toBool();
        insertOverrideReplacement = s->value(insertOverrideReplacementKey(), false).toBool();
        overrideReplacementIndex = s->value(overrideReplacementIndexKey(), 0).toInt();
        userAddedOverrideReplacements = s->value(userAddedOverrideReplacementsKey()).toStringList();
        implementationMode = static_cast<InsertVirtualMethodsDialog::ImplementationMode>(
                    s->value(implementationModeKey(), 1).toInt());
        s->endGroup();
320 321
    }

322
    void write() const
323
    {
324 325 326 327 328 329 330 331 332
        QSettings *s = Core::ICore::settings();
        s->beginGroup(group());
        s->setValue(insertVirtualKeywordKey(), insertVirtualKeyword);
        s->setValue(hideReimplementedFunctionsKey(), hideReimplementedFunctions);
        s->setValue(insertOverrideReplacementKey(), insertOverrideReplacement);
        s->setValue(overrideReplacementIndexKey(), overrideReplacementIndex);
        s->setValue(userAddedOverrideReplacementsKey(), userAddedOverrideReplacements);
        s->setValue(implementationModeKey(), implementationMode);
        s->endGroup();
333 334
    }

335 336 337 338 339 340 341 342
    QString overrideReplacement; // internal
    QStringList userAddedOverrideReplacements;
    InsertVirtualMethodsDialog::ImplementationMode implementationMode =
            InsertVirtualMethodsDialog::ModeOnlyDeclarations;
    int overrideReplacementIndex = 0;
    bool insertVirtualKeyword = false;
    bool hideReimplementedFunctions = false;
    bool insertOverrideReplacement = false;
343 344

private:
345 346 347 348 349 350 351 352
    typedef QLatin1String _;
    static QString group() { return _("QuickFix/InsertVirtualMethods"); }
    static QString insertVirtualKeywordKey() { return _("insertKeywordVirtual"); }
    static QString insertOverrideReplacementKey() { return _("insertOverrideReplacement"); }
    static QString overrideReplacementIndexKey() { return _("overrideReplacementIndex"); }
    static QString userAddedOverrideReplacementsKey() { return _("userAddedOverrideReplacements"); }
    static QString implementationModeKey() { return _("implementationMode"); }
    static QString hideReimplementedFunctionsKey() { return _("hideReimplementedFunctions"); }
353 354
};

355 356 357 358 359
class InsertVirtualMethodsModel : public QAbstractItemModel
{
public:
    InsertVirtualMethodsModel(QObject *parent = 0) : QAbstractItemModel(parent)
    {
360
        const FontSettings &fs = TextEditorSettings::fontSettings();
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
        formatReimpFunc = fs.formatFor(C_DISABLED_CODE);
    }

    ~InsertVirtualMethodsModel()
    {
        clear();
    }

    void clear()
    {
        beginResetModel();
        qDeleteAll(classes);
        classes.clear();
        endResetModel();
    }

    QModelIndex index(int row, int column, const QModelIndex &parent) const
    {
        if (column != 0)
            return QModelIndex();
        if (parent.isValid()) {
            ClassItem *classItem = static_cast<ClassItem *>(parent.internalPointer());
            return createIndex(row, column, classItem->functions.at(row));
        }
        return createIndex(row, column, classes.at(row));
    }

    QModelIndex parent(const QModelIndex &child) const
    {
        if (!child.isValid())
            return QModelIndex();
        InsertVirtualMethodsItem *parent = itemForIndex(child)->parent();
        return parent ? createIndex(parent->row, 0, parent) : QModelIndex();
    }

    int rowCount(const QModelIndex &parent) const
    {
        if (!parent.isValid())
            return classes.count();
        InsertVirtualMethodsItem *item = itemForIndex(parent);
        if (item->parent()) // function -> no children
            return 0;
        return static_cast<ClassItem *>(item)->functions.count();
    }

    int columnCount(const QModelIndex &) const
    {
        return 1;
    }

    void addClass(ClassItem *classItem)
    {
        int row = classes.count();
        classItem->row = row;
        beginInsertRows(QModelIndex(), row, row);
        classes.append(classItem);
        endInsertRows();
    }

420 421 422 423 424 425 426 427
    void removeFunction(FunctionItem *funcItem)
    {
        ClassItem *classItem = static_cast<ClassItem *>(funcItem->parent());
        beginRemoveRows(createIndex(classItem->row, 0, classItem), funcItem->row, funcItem->row);
        classItem->removeFunction(funcItem->row);
        endRemoveRows();
    }

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
    QVariant data(const QModelIndex &index, int role) const
    {
        if (!index.isValid())
            return QVariant();

        InsertVirtualMethodsItem *item = itemForIndex(index);
        switch (role) {
        case Qt::DisplayRole:
            return item->description();
        case Qt::CheckStateRole:
            return item->checkState();
        case Qt::ForegroundRole:
            if (item->parent() && static_cast<FunctionItem *>(item)->alreadyFound)
                return formatReimpFunc.foreground();
            break;
        case Qt::BackgroundRole:
            if (item->parent() && static_cast<FunctionItem *>(item)->alreadyFound) {
                const QColor background = formatReimpFunc.background();
                if (background.isValid())
                    return background;
            }
            break;
        case InsertVirtualMethodsDialog::Reimplemented:
            if (item->parent()) {
                FunctionItem *function = static_cast<FunctionItem *>(item);
453
                return QVariant(function->alreadyFound);
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
            }

        }
        return QVariant();
    }

    bool setData(const QModelIndex &index, const QVariant &value, int role)
    {
        if (!index.isValid())
            return false;

        InsertVirtualMethodsItem *item = itemForIndex(index);
        switch (role) {
        case Qt::CheckStateRole: {
            bool checked = value.toInt() == Qt::Checked;
            if (item->parent()) {
470 471 472 473 474 475 476 477 478 479
                FunctionItem *funcItem = static_cast<FunctionItem *>(item);
                while (funcItem->checked != checked) {
                    funcItem->checked = checked;
                    const QModelIndex funcIndex = createIndex(funcItem->row, 0, funcItem);
                    emit dataChanged(funcIndex, funcIndex);
                    const QModelIndex parentIndex =
                            createIndex(funcItem->parent()->row, 0, funcItem->parent());
                    emit dataChanged(parentIndex, parentIndex);
                    funcItem = funcItem->nextOverride;
                }
480 481 482
            } else {
                ClassItem *classItem = static_cast<ClassItem *>(item);
                foreach (FunctionItem *funcItem, classItem->functions) {
483 484 485 486
                    if (funcItem->alreadyFound || funcItem->checked == checked)
                        continue;
                    QModelIndex funcIndex = createIndex(funcItem->row, 0, funcItem);
                    setData(funcIndex, value, role);
487 488
                }
            }
Orgad Shaneh's avatar
Orgad Shaneh committed
489
            return true;
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        }
        }
        return QAbstractItemModel::setData(index, value, role);
    }

    Qt::ItemFlags flags(const QModelIndex &index) const
    {
        if (!index.isValid())
            return Qt::NoItemFlags;
        return itemForIndex(index)->flags();
    }

    QList<ClassItem *> classes;

private:
    Format formatReimpFunc;

    InsertVirtualMethodsItem *itemForIndex(const QModelIndex &index) const
    {
        return static_cast<InsertVirtualMethodsItem *>(index.internalPointer());
    }
};

513 514 515
class InsertVirtualMethodsOp : public CppQuickFixOperation
{
public:
516
    InsertVirtualMethodsOp(const CppQuickFixInterface &interface,
517 518 519 520 521 522 523 524 525 526 527 528 529
                           InsertVirtualMethodsDialog *factory)
        : CppQuickFixOperation(interface, 0)
        , m_factory(factory)
        , m_classAST(0)
        , m_valid(false)
        , m_cppFileName(QString::null)
        , m_insertPosDecl(0)
        , m_insertPosOutside(0)
        , m_functionCount(0)
    {
        setDescription(QCoreApplication::translate(
                           "CppEditor::QuickFix", "Insert Virtual Functions of Base Classes"));

530
        const QList<AST *> &path = interface.path();
531 532 533 534 535 536
        const int pathSize = path.size();
        if (pathSize < 2)
            return;

        // Determine if cursor is on a class or a base class
        if (SimpleNameAST *nameAST = path.at(pathSize - 1)->asSimpleName()) {
537
            if (!interface.isCursorOn(nameAST))
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
                return;

            if (!(m_classAST = path.at(pathSize - 2)->asClassSpecifier())) { // normal class
                int index = pathSize - 2;
                const BaseSpecifierAST *baseAST = path.at(index)->asBaseSpecifier();// simple bclass
                if (!baseAST) {
                    if (index > 0 && path.at(index)->asQualifiedName()) // namespaced base class
                        baseAST = path.at(--index)->asBaseSpecifier();
                }
                --index;
                if (baseAST && index >= 0)
                    m_classAST = path.at(index)->asClassSpecifier();
            }
        }
        if (!m_classAST || !m_classAST->base_clause_list)
            return;

        // Determine insert positions
556
        const int endOfClassAST = interface.currentFile()->endOf(m_classAST);
557 558 559 560 561
        m_insertPosDecl = endOfClassAST - 1; // Skip last "}"
        m_insertPosOutside = endOfClassAST + 1; // Step over ";"

        // Determine base classes
        QList<const Class *> baseClasses;
Nikolai Kosjar's avatar
Nikolai Kosjar committed
562 563 564
        QQueue<ClassOrNamespace *> baseClassQueue;
        QSet<ClassOrNamespace *> visitedBaseClasses;
        if (ClassOrNamespace *clazz = interface.context().lookupType(m_classAST->symbol))
565 566
            baseClassQueue.enqueue(clazz);
        while (!baseClassQueue.isEmpty()) {
Nikolai Kosjar's avatar
Nikolai Kosjar committed
567
            ClassOrNamespace *clazz = baseClassQueue.dequeue();
568
            visitedBaseClasses.insert(clazz);
Nikolai Kosjar's avatar
Nikolai Kosjar committed
569 570
            const QList<ClassOrNamespace *> bases = clazz->usings();
            foreach (ClassOrNamespace *baseClass, bases) {
571 572 573
                foreach (Symbol *symbol, baseClass->symbols()) {
                    Class *base = symbol->asClass();
                    if (base
574
                            && (clazz = interface.context().lookupType(symbol))
575 576 577 578 579 580 581 582 583 584 585 586 587
                            && !visitedBaseClasses.contains(clazz)
                            && !baseClasses.contains(base)) {
                        baseClasses.prepend(base);
                        baseClassQueue.enqueue(clazz);
                    }
                }
            }
        }

        // Determine virtual functions
        m_factory->classFunctionModel->clear();
        Overview printer = CppCodeStyleSettings::currentProjectCodeStyleOverview();
        printer.showFunctionSignatures = true;
588
        QHash<const Function *, FunctionItem *> virtualFunctions;
589
        foreach (const Class *clazz, baseClasses) {
590
            ClassItem *itemBase = new ClassItem(printer.prettyName(clazz->name()), clazz);
591
            for (Scope::iterator it = clazz->memberBegin(); it != clazz->memberEnd(); ++it) {
592 593 594 595 596 597 598
                if (const Function *func = (*it)->type()->asFunctionType()) {
                    // Filter virtual destructors
                    if (func->name()->asDestructorNameId())
                        continue;

                    const Function *firstVirtual = 0;
                    const bool isVirtual = FunctionUtils::isVirtualFunction(
599
                                func, interface.context(), &firstVirtual);
600 601 602
                    if (!isVirtual)
                        continue;

603 604 605 606 607 608 609 610 611 612 613 614
                    if (func->isFinal()) {
                        if (FunctionItem *first = virtualFunctions[firstVirtual]) {
                            FunctionItem *next = 0;
                            for (FunctionItem *removed = first; next != first; removed = next) {
                                next = removed->nextOverride;
                                m_factory->classFunctionModel->removeFunction(removed);
                                delete removed;
                            };
                            virtualFunctions.remove(firstVirtual);
                        }
                        continue;
                    }
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
                    // Filter OQbject's
                    //   - virtual const QMetaObject *metaObject() const;
                    //   - virtual void *qt_metacast(const char *);
                    //   - virtual int qt_metacall(QMetaObject::Call, int, void **);
                    if (printer.prettyName(firstVirtual->enclosingClass()->name())
                            == QLatin1String("QObject")) {
                        const QString funcName = printer.prettyName(func->name());
                        if (funcName == QLatin1String("metaObject")
                                || funcName == QLatin1String("qt_metacast")
                                || funcName == QLatin1String("qt_metacall")) {
                            continue;
                        }
                    }

                    // Do not implement existing functions inside target class
                    bool funcExistsInClass = false;
                    const Name *funcName = func->name();
                    for (Symbol *symbol = m_classAST->symbol->find(funcName->identifier());
                         symbol; symbol = symbol->next()) {
                        if (!symbol->name()
635
                                || !funcName->identifier()->match(symbol->identifier())) {
636 637
                            continue;
                        }
638
                        if (symbol->type().match(func->type())) {
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
                            funcExistsInClass = true;
                            break;
                        }
                    }

                    // Construct function item
                    const bool isReimplemented = (func != firstVirtual);
                    const bool isPureVirtual = func->isPureVirtual();
                    QString itemName = printer.prettyType(func->type(), func->name());
                    if (isPureVirtual)
                        itemName += QLatin1String(" = 0");
                    const QString itemReturnTypeString = printer.prettyType(func->returnType());
                    itemName += QLatin1String(" : ") + itemReturnTypeString;
                    if (isReimplemented)
                        itemName += QLatin1String(" (redeclared)");
654
                    FunctionItem *funcItem = new FunctionItem(func, itemName, itemBase);
655 656
                    if (isReimplemented) {
                        factory->setHasReimplementedFunctions(true);
657
                        funcItem->reimplemented = true;
658
                        funcItem->alreadyFound = funcExistsInClass;
659
                        if (FunctionItem *first = virtualFunctions[firstVirtual]) {
660 661 662 663 664 665 666 667 668
                            if (!first->alreadyFound) {
                                while (first->checked != isPureVirtual) {
                                    first->checked = isPureVirtual;
                                    first = first->nextOverride;
                                }
                            }
                            funcItem->checked = first->checked;
                            funcItem->nextOverride = first->nextOverride;
                            first->nextOverride = funcItem;
669 670 671
                        }
                    } else {
                        if (!funcExistsInClass) {
672
                            funcItem->checked = isPureVirtual;
673
                        } else {
674 675
                            funcItem->alreadyFound = true;
                            funcItem->checked = true;
676 677 678 679
                            factory->setHasReimplementedFunctions(true);
                        }
                    }

680 681 682
                    funcItem->accessSpec = acessSpec(*it);
                    funcItem->row = itemBase->functions.count();
                    itemBase->functions.append(funcItem);
683 684 685 686 687 688 689 690

                    virtualFunctions[func] = funcItem;

                    // update internal counters
                    if (!funcExistsInClass)
                        ++m_functionCount;
                }
            }
691 692 693 694

            if (itemBase->functions.isEmpty())
                delete itemBase;
            else
695
                m_factory->classFunctionModel->addClass(itemBase);
696
        }
697
        if (m_factory->classFunctionModel->classes.isEmpty() || m_functionCount == 0)
698 699 700
            return;

        bool isHeaderFile = false;
701
        m_cppFileName = correspondingHeaderOrSource(interface.fileName(), &isHeaderFile);
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 746 747 748 749
        m_factory->setHasImplementationFile(isHeaderFile && !m_cppFileName.isEmpty());

        m_valid = true;
    }

    bool isValid() const
    {
        return m_valid;
    }

    InsertionPointLocator::AccessSpec acessSpec(const Symbol *symbol)
    {
        const Function *func = symbol->type()->asFunctionType();
        if (!func)
            return InsertionPointLocator::Invalid;
        if (func->isSignal())
            return InsertionPointLocator::Signals;

        InsertionPointLocator::AccessSpec spec = InsertionPointLocator::Invalid;
        if (symbol->isPrivate())
            spec = InsertionPointLocator::Private;
        else if (symbol->isProtected())
            spec = InsertionPointLocator::Protected;
        else if (symbol->isPublic())
            spec = InsertionPointLocator::Public;
        else
            return InsertionPointLocator::Invalid;

        if (func->isSlot()) {
            switch (spec) {
            case InsertionPointLocator::Private:
                return InsertionPointLocator::PrivateSlot;
            case InsertionPointLocator::Protected:
                return InsertionPointLocator::ProtectedSlot;
            case InsertionPointLocator::Public:
                return InsertionPointLocator::PublicSlot;
            default:
                return spec;
            }
        }
        return spec;
    }

    void perform()
    {
        if (!m_factory->gather())
            return;

750
        m_factory->saveSettings();
751 752 753 754 755 756 757

        // Insert declarations (and definition if Inside-/OutsideClass)
        Overview printer = CppCodeStyleSettings::currentProjectCodeStyleOverview();
        printer.showFunctionSignatures = true;
        printer.showReturnTypes = true;
        printer.showArgumentNames = true;
        Utils::ChangeSet headerChangeSet;
758 759
        const CppRefactoringChanges refactoring(snapshot());
        const QString filename = currentFile()->fileName();
760
        const CppRefactoringFilePtr headerFile = refactoring.file(filename);
761
        const LookupContext targetContext(headerFile->cppDocument(), snapshot());
762 763

        const Class *targetClass = m_classAST->symbol;
Nikolai Kosjar's avatar
Nikolai Kosjar committed
764
        ClassOrNamespace *targetCoN = targetContext.lookupType(targetClass->enclosingScope());
765 766 767
        if (!targetCoN)
            targetCoN = targetContext.globalNamespace();
        UseMinimalNames useMinimalNames(targetCoN);
768
        Control *control = context().bindings()->control().data();
769 770
        foreach (ClassItem *classItem, m_factory->classFunctionModel->classes) {
            if (classItem->checkState() == Qt::Unchecked)
771 772 773 774
                continue;

            // Insert Declarations (+ definitions)
            QString lastAccessSpecString;
775
            bool first = true;
776 777
            foreach (FunctionItem *funcItem, classItem->functions) {
                if (funcItem->reimplemented || funcItem->alreadyFound || !funcItem->checked)
778 779
                    continue;

780 781 782 783 784 785 786 787
                if (first) {
                    // Add comment
                    const QString comment = QLatin1String("\n// ") +
                            printer.prettyName(classItem->klass->name()) +
                            QLatin1String(" interface\n");
                    headerChangeSet.insert(m_insertPosDecl, comment);
                    first = false;
                }
788 789 790
                // Construct declaration
                // setup rewriting to get minimally qualified names
                SubstitutionEnvironment env;
791
                env.setContext(context());
792
                env.switchScope(classItem->klass->enclosingScope());
793 794 795
                env.enter(&useMinimalNames);

                QString declaration;
796 797
                const FullySpecifiedType tn = rewriteType(funcItem->function->type(), &env, control);
                declaration += printer.prettyType(tn, funcItem->function->unqualifiedName());
798

799
                if (m_factory->settings()->insertVirtualKeyword)
800
                    declaration = QLatin1String("virtual ") + declaration;
801 802
                if (m_factory->settings()->insertOverrideReplacement) {
                    const QString overrideReplacement = m_factory->settings()->overrideReplacement;
803 804 805
                    if (!overrideReplacement.isEmpty())
                        declaration += QLatin1Char(' ') + overrideReplacement;
                }
806 807
                if (m_factory->settings()->implementationMode
                        & InsertVirtualMethodsDialog::ModeInsideClass) {
808
                    declaration += QLatin1String("\n{\n}\n");
809
                } else {
810
                    declaration += QLatin1String(";\n");
811
                }
812

813 814
                const QString accessSpecString =
                        InsertionPointLocator::accessSpecToString(funcItem->accessSpec);
815
                if (accessSpecString != lastAccessSpecString) {
816
                    declaration = accessSpecString + QLatin1String(":\n") + declaration;
817 818 819 820 821 822 823
                    if (!lastAccessSpecString.isEmpty()) // separate if not direct after the comment
                        declaration = QLatin1String("\n") + declaration;
                    lastAccessSpecString = accessSpecString;
                }
                headerChangeSet.insert(m_insertPosDecl, declaration);

                // Insert definition outside class
824 825
                if (m_factory->settings()->implementationMode
                        & InsertVirtualMethodsDialog::ModeOutsideClass) {
826
                    const QString name = printer.prettyName(targetClass->name()) +
827
                            QLatin1String("::") + printer.prettyName(funcItem->function->name());
828 829 830 831 832 833 834 835 836 837 838 839 840
                    const QString defText = printer.prettyType(tn, name) + QLatin1String("\n{\n}");
                    headerChangeSet.insert(m_insertPosOutside,  QLatin1String("\n\n") + defText);
                }
            }
        }

        // Write header file
        headerFile->setChangeSet(headerChangeSet);
        headerFile->appendIndentRange(Utils::ChangeSet::Range(m_insertPosDecl, m_insertPosDecl + 1));
        headerFile->setOpenEditor(true, m_insertPosDecl);
        headerFile->apply();

        // Insert in implementation file
841 842
        if (m_factory->settings()->implementationMode
                & InsertVirtualMethodsDialog::ModeImplementationFile) {
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
            const Symbol *symbol = headerFile->cppDocument()->lastVisibleSymbolAt(
                        targetClass->line(), targetClass->column());
            if (!symbol)
                return;
            const Class *clazz = symbol->asClass();
            if (!clazz)
                return;

            CppRefactoringFilePtr implementationFile = refactoring.file(m_cppFileName);
            Utils::ChangeSet implementationChangeSet;
            const int insertPos = qMax(0, implementationFile->document()->characterCount() - 1);

            // make target lookup context
            Document::Ptr implementationDoc = implementationFile->cppDocument();
            unsigned line, column;
            implementationDoc->translationUnit()->getPosition(insertPos, &line, &column);
            Scope *targetScope = implementationDoc->scopeAt(line, column);
860
            const LookupContext targetContext(implementationDoc, snapshot());
Nikolai Kosjar's avatar
Nikolai Kosjar committed
861
            ClassOrNamespace *targetCoN = targetContext.lookupType(targetScope);
862 863 864 865 866 867 868 869 870 871 872
            if (!targetCoN)
                targetCoN = targetContext.globalNamespace();

            // Loop through inserted declarations
            for (unsigned i = targetClass->memberCount(); i < clazz->memberCount(); ++i) {
                Declaration *decl = clazz->memberAt(i)->asDeclaration();
                if (!decl)
                    continue;

                // setup rewriting to get minimally qualified names
                SubstitutionEnvironment env;
873
                env.setContext(context());
874 875 876
                env.switchScope(decl->enclosingScope());
                UseMinimalNames q(targetCoN);
                env.enter(&q);
877
                Control *control = context().bindings()->control().data();
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932

                // rewrite the function type and name + create definition
                const FullySpecifiedType type = rewriteType(decl->type(), &env, control);
                const QString name = printer.prettyName(
                            LookupContext::minimalName(decl, targetCoN, control));
                const QString defText = printer.prettyType(type, name) + QLatin1String("\n{\n}");

                implementationChangeSet.insert(insertPos,  QLatin1String("\n\n") + defText);
            }

            implementationFile->setChangeSet(implementationChangeSet);
            implementationFile->appendIndentRange(Utils::ChangeSet::Range(insertPos, insertPos + 1));
            implementationFile->apply();
        }
    }

private:
    InsertVirtualMethodsDialog *m_factory;
    const ClassSpecifierAST *m_classAST;
    bool m_valid;
    QString m_cppFileName;
    int m_insertPosDecl;
    int m_insertPosOutside;
    unsigned m_functionCount;
};

class InsertVirtualMethodsFilterModel : public QSortFilterProxyModel
{
    Q_OBJECT
public:
    InsertVirtualMethodsFilterModel(QObject *parent = 0)
        : QSortFilterProxyModel(parent)
        , m_hideReimplemented(false)
    {}

    bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const
    {
        QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);

        // Handle base class
        if (!sourceParent.isValid()) {
            // check if any child is valid
            if (!sourceModel()->hasChildren(index))
                return false;
            if (!m_hideReimplemented)
                return true;

            for (int i = 0; i < sourceModel()->rowCount(index); ++i) {
                const QModelIndex child = sourceModel()->index(i, 0, index);
                if (!child.data(InsertVirtualMethodsDialog::Reimplemented).toBool())
                    return true;
            }
            return false;
        }

933 934
        if (!QSortFilterProxyModel::filterAcceptsRow(sourceRow, sourceParent))
            return false;
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
        if (m_hideReimplemented)
            return !index.data(InsertVirtualMethodsDialog::Reimplemented).toBool();
        return true;
    }

    bool hideReimplemented() const
    {
        return m_hideReimplemented;
    }

    void setHideReimplementedFunctions(bool show)
    {
        m_hideReimplemented = show;
        invalidateFilter();
    }

private:
    bool m_hideReimplemented;
};

InsertVirtualMethodsDialog::InsertVirtualMethodsDialog(QWidget *parent)
    : QDialog(parent)
    , m_view(0)
958
    , m_filter(0)
959 960 961
    , m_hideReimplementedFunctions(0)
    , m_insertMode(0)
    , m_virtualKeyword(0)
962 963 964
    , m_overrideReplacementCheckBox(0)
    , m_overrideReplacementComboBox(0)
    , m_clearUserAddedReplacementsButton(0)
965 966 967
    , m_buttons(0)
    , m_hasImplementationFile(false)
    , m_hasReimplementedFunctions(false)
968
    , m_settings(new VirtualMethodsSettings)
969
    , classFunctionModel(new InsertVirtualMethodsModel(this))
970 971 972
    , classFunctionFilterModel(new InsertVirtualMethodsFilterModel(this))
{
    classFunctionFilterModel->setSourceModel(classFunctionModel);
973
    classFunctionFilterModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
974 975
}

976 977 978 979 980
InsertVirtualMethodsDialog::~InsertVirtualMethodsDialog()
{
    delete m_settings;
}

981 982 983 984 985 986 987 988 989 990 991
void InsertVirtualMethodsDialog::initGui()
{
    if (m_view)
        return;

    setWindowTitle(tr("Insert Virtual Functions"));
    QVBoxLayout *globalVerticalLayout = new QVBoxLayout;

    // View
    QGroupBox *groupBoxView = new QGroupBox(tr("&Functions to insert:"), this);
    QVBoxLayout *groupBoxViewLayout = new QVBoxLayout(groupBoxView);
992 993 994 995
    m_filter = new QLineEdit(this);
    m_filter->setClearButtonEnabled(true);
    m_filter->setPlaceholderText(tr("Filter"));
    groupBoxViewLayout->addWidget(m_filter);
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    m_view = new QTreeView(this);
    m_view->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_view->setHeaderHidden(true);
    groupBoxViewLayout->addWidget(m_view);
    m_hideReimplementedFunctions =
            new QCheckBox(tr("&Hide reimplemented functions"), this);
    groupBoxViewLayout->addWidget(m_hideReimplementedFunctions);

    // Insertion options
    QGroupBox *groupBoxImplementation = new QGroupBox(tr("&Insertion options:"), this);
    QVBoxLayout *groupBoxImplementationLayout = new QVBoxLayout(groupBoxImplementation);
    m_insertMode = new QComboBox(this);
    m_insertMode->addItem(tr("Insert only declarations"), ModeOnlyDeclarations);
    m_insertMode->addItem(tr("Insert definitions inside class"), ModeInsideClass);
    m_insertMode->addItem(tr("Insert definitions outside class"), ModeOutsideClass);
    m_insertMode->addItem(tr("Insert definitions in implementation file"), ModeImplementationFile);
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
    m_virtualKeyword = new QCheckBox(tr("Add \"&virtual\" to function declaration"), this);
    m_overrideReplacementCheckBox = new QCheckBox(
                tr("Add \"override\" equivalent to function declaration:"), this);
    m_overrideReplacementComboBox = new QComboBox(this);
    QSizePolicy sizePolicy = m_overrideReplacementComboBox->sizePolicy();
    sizePolicy.setHorizontalPolicy(QSizePolicy::Expanding);
    m_overrideReplacementComboBox->setSizePolicy(sizePolicy);
    m_overrideReplacementComboBox->setEditable(true);
    connect(m_overrideReplacementCheckBox, &QCheckBox::clicked,
            m_overrideReplacementComboBox, &QComboBox::setEnabled);

    QAction *clearUserAddedReplacements = new QAction(this);
1024
    clearUserAddedReplacements->setIcon(Core::Icons::CLEAN_TOOLBAR.icon());
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    clearUserAddedReplacements->setText(tr("Clear Added \"override\" Equivalents"));
    connect(clearUserAddedReplacements, &QAction::triggered, [this]() {
       m_availableOverrideReplacements = defaultOverrideReplacements();
       updateOverrideReplacementsComboBox();
       m_clearUserAddedReplacementsButton->setEnabled(false);
    });
    m_clearUserAddedReplacementsButton = new QToolButton(this);
    m_clearUserAddedReplacementsButton->setDefaultAction(clearUserAddedReplacements);

    QHBoxLayout *overrideWidgetsLayout = new QHBoxLayout(this);
    overrideWidgetsLayout->setSpacing(0);
    overrideWidgetsLayout->setMargin(0);
    overrideWidgetsLayout->addWidget(m_overrideReplacementCheckBox);
    overrideWidgetsLayout->addWidget(m_overrideReplacementComboBox);
    overrideWidgetsLayout->addWidget(m_clearUserAddedReplacementsButton);
    QWidget *overrideWidgets = new QWidget(groupBoxImplementation);
    overrideWidgets->setLayout(overrideWidgetsLayout);

1043 1044
    groupBoxImplementationLayout->addWidget(m_insertMode);
    groupBoxImplementationLayout->addWidget(m_virtualKeyword);
1045
    groupBoxImplementationLayout->addWidget(overrideWidgets);
1046 1047 1048 1049 1050
    groupBoxImplementationLayout->addStretch(99);

    // Bottom button box
    m_buttons = new QDialogButtonBox(this);
    m_buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
1051 1052
    connect(m_buttons, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(m_buttons, &QDialogButtonBox::rejected, this, &QDialog::reject);
1053 1054 1055 1056 1057 1058

    globalVerticalLayout->addWidget(groupBoxView, 9);
    globalVerticalLayout->addWidget(groupBoxImplementation, 0);
    globalVerticalLayout->addWidget(m_buttons, 0);
    setLayout(globalVerticalLayout);

1059 1060
    connect(m_hideReimplementedFunctions, &QAbstractButton::toggled,
            this, &InsertVirtualMethodsDialog::setHideReimplementedFunctions);
1061 1062
    connect(m_filter, &QLineEdit::textChanged,
            classFunctionFilterModel, &QSortFilterProxyModel::setFilterWildcard);
1063 1064 1065 1066
}

void InsertVirtualMethodsDialog::initData()
{
1067
    m_settings->read();
1068
    m_filter->clear();
1069
    m_hideReimplementedFunctions->setChecked(m_settings->hideReimplementedFunctions);
1070 1071
    const QStringList alwaysPresentReplacements = defaultOverrideReplacements();
    m_availableOverrideReplacements = alwaysPresentReplacements;
1072
    m_availableOverrideReplacements += m_settings->userAddedOverrideReplacements;
1073 1074 1075 1076 1077

    m_view->setModel(classFunctionFilterModel);
    m_expansionStateNormal.clear();
    m_expansionStateReimp.clear();
    m_hideReimplementedFunctions->setEnabled(m_hasReimplementedFunctions);
1078 1079
    m_virtualKeyword->setChecked(m_settings->insertVirtualKeyword);
    m_insertMode->setCurrentIndex(m_insertMode->findData(m_settings->implementationMode));
1080

1081
    m_overrideReplacementCheckBox->setChecked(m_settings->insertOverrideReplacement);
1082 1083 1084
    updateOverrideReplacementsComboBox();
    const bool canClear = m_availableOverrideReplacements.size() > alwaysPresentReplacements.size();
    m_clearUserAddedReplacementsButton->setEnabled(canClear);
1085
    int overrideReplacementIndex = m_settings->overrideReplacementIndex;
1086 1087 1088 1089
    if (overrideReplacementIndex >= m_overrideReplacementComboBox->count())
        overrideReplacementIndex = 0;
    m_overrideReplacementComboBox->setCurrentIndex(overrideReplacementIndex);

1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    setHideReimplementedFunctions(m_hideReimplementedFunctions->isChecked());

    if (m_hasImplementationFile) {
        if (m_insertMode->count() == 3) {
            m_insertMode->addItem(tr("Insert definitions in implementation file"),
                                  ModeImplementationFile);
        }
    } else {
        if (m_insertMode->count() == 4)
            m_insertMode->removeItem(3);
    }
}

1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
void InsertVirtualMethodsDialog::saveSettings()
{
    m_settings->insertVirtualKeyword = m_virtualKeyword->isChecked();
    m_settings->implementationMode = static_cast<InsertVirtualMethodsDialog::ImplementationMode>(
                m_insertMode->itemData(m_insertMode->currentIndex()).toInt());
    m_settings->hideReimplementedFunctions = m_hideReimplementedFunctions->isChecked();
    m_settings->insertOverrideReplacement = m_overrideReplacementCheckBox->isChecked();
    m_settings->overrideReplacementIndex = m_overrideReplacementComboBox->currentIndex();
    if (m_overrideReplacementComboBox && m_overrideReplacementComboBox->isEnabled())
        m_settings->overrideReplacement = m_overrideReplacementComboBox->currentText().trimmed();
    QSet<QString> addedReplacements = m_availableOverrideReplacements.toSet();
    addedReplacements.insert(m_settings->overrideReplacement);
    addedReplacements.subtract(defaultOverrideReplacements().toSet());
    m_settings->userAddedOverrideReplacements =
            sortedAndTrimmedStringListWithoutEmptyElements(addedReplacements.toList());
    m_settings->write();
}

const VirtualMethodsSettings *InsertVirtualMethodsDialog::settings() const
{
    return m_settings;
}

1126 1127 1128 1129
bool InsertVirtualMethodsDialog::gather()
{
    initGui();
    initData();
1130
    m_filter->setFocus();
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

    // Expand the dialog a little bit
    adjustSize();
    resize(size() * 1.5);

    QPointer<InsertVirtualMethodsDialog> that(this);
    const int ret = exec();
    if (!that)
        return false;

    return (ret == QDialog::Accepted);
}

void InsertVirtualMethodsDialog::setHasImplementationFile(bool file)
{
    m_hasImplementationFile = file;
}

void InsertVirtualMethodsDialog::setHasReimplementedFunctions(bool functions)
{
    m_hasReimplementedFunctions = functions;
}

void InsertVirtualMethodsDialog::setHideReimplementedFunctions(bool hide)
{
    InsertVirtualMethodsFilterModel *model =
            qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);

    if (m_expansionStateNormal.isEmpty() && m_expansionStateReimp.isEmpty()) {
        model->setHideReimplementedFunctions(hide);
        m_view->expandAll();
        saveExpansionState();
        return;
    }

    if (model->hideReimplemented() == hide)
        return;

    saveExpansionState();
    model->setHideReimplementedFunctions(hide);
    restoreExpansionState();
}

1174 1175 1176 1177 1178 1179 1180
void InsertVirtualMethodsDialog::updateOverrideReplacementsComboBox()
{
    m_overrideReplacementComboBox->clear();
    foreach (const QString &replacement, m_availableOverrideReplacements)
        m_overrideReplacementComboBox->addItem(replacement);
}

1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
void InsertVirtualMethodsDialog::saveExpansionState()
{
    InsertVirtualMethodsFilterModel *model =
            qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);

    QList<bool> &state = model->hideReimplemented() ? m_expansionStateReimp
                                                    : m_expansionStateNormal;
    state.clear();
    for (int i = 0; i < model->rowCount(); ++i)
        state << m_view->isExpanded(model->index(i, 0));
}

void InsertVirtualMethodsDialog::restoreExpansionState()
{
    InsertVirtualMethodsFilterModel *model =
            qobject_cast<InsertVirtualMethodsFilterModel *>(classFunctionFilterModel);

    const QList<bool> &state = model->hideReimplemented() ? m_expansionStateReimp
                                                          : m_expansionStateNormal;
    const int stateCount = state.count();
    for (int i = 0; i < model->rowCount(); ++i) {
        if (i < stateCount && !state.at(i)) {
            m_view->collapse(model->index(i, 0));
            continue;
        }
        m_view->expand(model->index(i, 0));
    }
}

InsertVirtualMethods::InsertVirtualMethods(InsertVirtualMethodsDialog *dialog)
    : m_dialog(dialog)
{
    if (!dialog)
        m_dialog = new InsertVirtualMethodsDialog;
}

InsertVirtualMethods::~InsertVirtualMethods()
{
    m_dialog->deleteLater();
}

1222 1223
void InsertVirtualMethods::match(const CppQuickFixInterface &interface,
                                 QuickFixOperations &result)
1224 1225 1226
{
    InsertVirtualMethodsOp *op = new InsertVirtualMethodsOp(interface, m_dialog);
    if (op->isValid())
1227
        result.append(op);
1228 1229 1230 1231 1232 1233
    else
        delete op;
}

#ifdef WITH_TESTS

1234
namespace Tests {
1235 1236 1237

typedef QByteArray _;

1238
/// Stub dialog of InsertVirtualMethodsDialog that does not pop up anything.
1239 1240 1241
class InsertVirtualMethodsDialogTest : public InsertVirtualMethodsDialog
{
public:
1242 1243 1244
    InsertVirtualMethodsDialogTest(ImplementationMode mode,
                                   bool insertVirtualKeyword,
                                   bool insertOverrideKeyword,
1245 1246 1247
                                   QWidget *parent = 0)
        : InsertVirtualMethodsDialog(parent)
    {
1248 1249 1250 1251
        m_settings->implementationMode = mode;
        m_settings->insertVirtualKeyword = insertVirtualKeyword;
        m_settings->insertOverrideReplacement = insertOverrideKeyword;
        m_settings->overrideReplacement = QLatin1String("override");
1252 1253 1254
    }

    bool gather() { return true; }
1255
    void saveSettings() { }
1256 1257
};

1258 1259
} // namespace Tests

1260 1261
InsertVirtualMethods *InsertVirtualMethods::createTestFactory()
{
1262
    return new InsertVirtualMethods(new Tests::InsertVirtualMethodsDialogTest(
1263
                                        InsertVirtualMethodsDialog::ModeOutsideClass, true, false));
1264 1265 1266 1267 1268 1269
}

void CppEditorPlugin::test_quickfix_InsertVirtualMethods_data()
{
    QTest::addColumn<InsertVirtualMethodsDialog::ImplementationMode>("implementationMode");
    QTest::addColumn<bool>("insertVirtualKeyword");
1270
    QTest::addColumn<bool>("insertOverrideKeyword");
1271 1272 1273 1274 1275
    QTest::addColumn<QByteArray>("original");
    QTest::addColumn<QByteArray>("expected");

    // Check: Insert only declarations
    QTest::newRow("onlyDecl")
1276
        << InsertVirtualMethodsDialog::ModeOnlyDeclarations << true << false << _(
1277 1278 1279 1280 1281
        "class BaseA {\n"
        "public:\n"
        "    virtual int virtualFuncA() = 0;\n"
        "};\n\n"
        "class Derived : public Bas@eA {\n"
1282
        "};\n"
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
        ) << _(
        "class BaseA {\n"
        "public:\n"
        "    virtual int virtualFuncA() = 0;\n"
        "};\n\n"
        "class Derived : public BaseA {\n"
        "\n"
        "    // BaseA interface\n"
        "public:\n"
        "    virtual int virtualFuncA();\n"
        "};\n"
    );

1296
    // Check: Insert only declarations without virtual keyword but with override
1297
    QTest::newRow("onlyDeclWithoutVirtual")
1298
        << InsertVirtualMethodsDialog::ModeOnlyDeclarations << false << true << _(
1299 1300 1301 1302 1303
        "class BaseA {\n"
        "public:\n"
        "    virtual int virtualFuncA() = 0;\n"
        "};\n\n"
        "class Derived : public Bas@eA {\n"
1304
        "};\n"
1305 1306 1307 1308 1309 1310 1311 1312 1313
        ) << _(
        "class BaseA {\n"
        "public:\n"
        "    virtual int virtualFuncA() = 0;\n"
        "};\n\n"
        "class Derived : public BaseA {\n"
        "\n"
        "    // BaseA interface\n"
        "public:\n"
1314
        "    int virtualFuncA() override;\n"
1315 1316 1317 1318 1319
        "};\n"
    );

    // Check: Are access specifiers considered
    QTest::newRow("Access")
1320
        << InsertVirtualMethodsDialog::ModeOnlyDeclarations << true << false << _(
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
        "class BaseA {\n"
        "public:\n"
        "    virtual int a() = 0;\n"
        "protected:\n"
        "    virtual int b() = 0;\n"
        "private:\n"
        "    virtual int c() = 0;\n"
        "public slots:\n"
        "    virtual int d() = 0;\n"
        "protected slots:\n"
        "    virtual int e() = 0;\n"
        "private slots:\n"
        "    virtual int f() = 0;\n"
        "signals:\n"
        "    virtual int g() = 0;\n"
        "};\n\n"
        "class Der@ived : public BaseA {\n"
Nikolai Kosjar's avatar