cppclasswizard.cpp 9.86 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
5
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
7
8
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
26
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
con's avatar
con committed
27
**
28
**************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
31
32
#include "cppclasswizard.h"
#include "cppeditorconstants.h"

33
34
35
36
#include <cpptools/cpptoolsconstants.h>
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>

con's avatar
con committed
37
38
#include <utils/codegeneration.h>
#include <utils/newclasswidget.h>
hjk's avatar
hjk committed
39
#include <utils/qtcassert.h>
con's avatar
con committed
40
41

#include <QtCore/QDebug>
hjk's avatar
hjk committed
42
43
#include <QtCore/QDir>
#include <QtCore/QTextStream>
44
#include <QtCore/QSettings>
hjk's avatar
hjk committed
45

con's avatar
con committed
46
#include <QtGui/QVBoxLayout>
47
48
49
50
#include <QtGui/QHBoxLayout>
#include <QtGui/QPushButton>
#include <QtGui/QToolButton>
#include <QtGui/QSpacerItem>
con's avatar
con committed
51
52
53
54
55
56
57
#include <QtGui/QWizard>

using namespace CppEditor;
using namespace CppEditor::Internal;

// ========= ClassNamePage =========

58
ClassNamePage::ClassNamePage(QWidget *parent) :
con's avatar
con committed
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
    QWizardPage(parent),
    m_isValid(false)
{
    setTitle(tr("Enter class name"));
    setSubTitle(tr("The header and source file names will be derived from the class name"));

    m_newClassWidget = new Core::Utils::NewClassWidget;
    // Order, set extensions first before suggested name is derived
    m_newClassWidget->setBaseClassInputVisible(true);
    m_newClassWidget->setBaseClassChoices(QStringList() << QString()
            << QLatin1String("QObject")
            << QLatin1String("QWidget")
            << QLatin1String("QMainWindow"));
    m_newClassWidget->setBaseClassEditable(true);
    m_newClassWidget->setFormInputVisible(false);
    m_newClassWidget->setNamespacesEnabled(true);
75
    m_newClassWidget->setAllowDirectories(true);
con's avatar
con committed
76

77
    connect(m_newClassWidget, SIGNAL(validChanged()), this, SLOT(slotValidChanged()));
con's avatar
con committed
78

79
    QVBoxLayout *pageLayout = new QVBoxLayout(this);   
con's avatar
con committed
80
    pageLayout->addWidget(m_newClassWidget);
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
    QSpacerItem *vSpacer = new QSpacerItem(0, 0, QSizePolicy::Ignored, QSizePolicy::Expanding);
    pageLayout->addItem(vSpacer);
    QHBoxLayout *buttonLayout = new QHBoxLayout;
    pageLayout->addLayout(buttonLayout);
    QSpacerItem *hSpacer = new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Ignored);
    buttonLayout->addItem(hSpacer);
    QToolButton *settingsButton = new QToolButton;
    settingsButton->setText(tr("Configure..."));
    connect(settingsButton, SIGNAL(clicked()), this, SLOT(slotSettings()));
    buttonLayout->addWidget(settingsButton);
    initParameters();
}

// Retrieve settings of CppTools plugin.
static inline bool lowerCaseFiles(const Core::ICore *core)
{
97
98
99
100
101
    QString lowerCaseSettingsKey = QLatin1String(CppTools::Constants::CPPTOOLS_SETTINGSGROUP);
    lowerCaseSettingsKey += QLatin1Char('/');
    lowerCaseSettingsKey += QLatin1String(CppTools::Constants::LOWERCASE_CPPFILES_KEY);
    const bool lowerCaseDefault = CppTools::Constants::lowerCaseFilesDefault;
    return core->settings()->value(lowerCaseSettingsKey, QVariant(lowerCaseDefault)).toBool();
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
}

// Set up new class widget from settings
void ClassNamePage::initParameters()
{
    Core::ICore *core = Core::ICore::instance();
    const Core::MimeDatabase *mdb = core->mimeDatabase();
    m_newClassWidget->setHeaderExtension(mdb->preferredSuffixByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)));
    m_newClassWidget->setSourceExtension(mdb->preferredSuffixByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)));
    m_newClassWidget->setLowerCaseFiles(lowerCaseFiles(core));
}

void ClassNamePage::slotSettings()
{
    const QString id = QLatin1String(CppTools::Constants::CPP_SETTINGS_ID);
    const QString cat = QLatin1String(CppTools::Constants::CPP_SETTINGS_CATEGORY);
    if (Core::ICore::instance()->showOptionsDialog(cat, id, this)) {
        initParameters();
        m_newClassWidget->triggerUpdateFileNames();
    }
con's avatar
con committed
122
123
124
125
126
127
128
129
130
131
132
}

void ClassNamePage::slotValidChanged()
{
    const bool validNow = m_newClassWidget->isValid();
    if (m_isValid != validNow) {
        m_isValid = validNow;
        emit completeChanged();
    }
}

133
CppClassWizardDialog::CppClassWizardDialog(QWidget *parent) :
con's avatar
con committed
134
    QWizard(parent),
135
    m_classNamePage(new ClassNamePage(this))
con's avatar
con committed
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
{
    Core::BaseFileWizard::setupWizard(this);
    setWindowTitle(tr("C++ Class Wizard"));
    addPage(m_classNamePage);
}

void CppClassWizardDialog::setPath(const QString &path)
{
    m_classNamePage->newClassWidget()->setPath(path);
}

CppClassWizardParameters  CppClassWizardDialog::parameters() const
{
    CppClassWizardParameters rc;
    const Core::Utils::NewClassWidget *ncw = m_classNamePage->newClassWidget();
    rc.className = ncw->className();
    rc.headerFile = ncw->headerFileName();
    rc.sourceFile = ncw->sourceFileName();
    rc.baseClass = ncw->baseClassName();
    rc.path = ncw->path();
    return rc;
}

// ========= CppClassWizard =========

CppClassWizard::CppClassWizard(const Core::BaseFileWizardParameters &parameters,
162
163
                               QObject *parent)
  : Core::BaseFileWizard(parameters, parent)
con's avatar
con committed
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
{
}

QString CppClassWizard::sourceSuffix() const
{
    return preferredSuffix(QLatin1String(Constants::CPP_SOURCE_MIMETYPE));
}

QString CppClassWizard::headerSuffix() const
{
    return preferredSuffix(QLatin1String(Constants::CPP_HEADER_MIMETYPE));
}

QWizard *CppClassWizard::createWizardDialog(QWidget *parent,
                                            const QString &defaultPath,
                                            const WizardPageList &extensionPages) const
{
181
    CppClassWizardDialog *wizard = new CppClassWizardDialog(parent);
con's avatar
con committed
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
    foreach (QWizardPage *p, extensionPages)
        wizard->addPage(p);
    wizard->setPath(defaultPath);
    return wizard;
}

Core::GeneratedFiles CppClassWizard::generateFiles(const QWizard *w, QString *errorMessage) const
{
    const CppClassWizardDialog *wizard = qobject_cast<const CppClassWizardDialog *>(w);
    const CppClassWizardParameters params = wizard->parameters();

    const QString sourceFileName = Core::BaseFileWizard::buildFileName(params.path, params.sourceFile, sourceSuffix());
    const QString headerFileName = Core::BaseFileWizard::buildFileName(params.path, params.headerFile, headerSuffix());

    Core::GeneratedFile sourceFile(sourceFileName);
    sourceFile.setEditorKind(QLatin1String(Constants::CPPEDITOR_KIND));

    Core::GeneratedFile headerFile(headerFileName);
    headerFile.setEditorKind(QLatin1String(Constants::CPPEDITOR_KIND));

    QString header, source;
    if (!generateHeaderAndSource(params, &header, &source)) {
        *errorMessage = tr("Error while generating file contents.");
        return Core::GeneratedFiles();
    }
    headerFile.setContents(header);
    sourceFile.setContents(source);
    return Core::GeneratedFiles() << headerFile << sourceFile;
}


bool CppClassWizard::generateHeaderAndSource(const CppClassWizardParameters &params,
                                             QString *header, QString *source)
{
    // TODO:
    //  Quite a bit of this code has been copied from FormClassWizardParameters::generateCpp.
    //  Maybe more of it could be merged into Core::Utils.

    const QString indent = QString(4, QLatin1Char(' '));

    // Do we have namespaces?
    QStringList namespaceList = params.className.split(QLatin1String("::"));
    if (namespaceList.empty()) // Paranoia!
        return false;

    const QString unqualifiedClassName = namespaceList.takeLast();
228
    const QString guard = Core::Utils::headerGuard(params.headerFile);
con's avatar
con committed
229
230
231
232
233
234
235

    // == Header file ==
    QTextStream headerStr(header);
    headerStr << "#ifndef " << guard
              << "\n#define " <<  guard << '\n' << '\n';

    const QRegExp qtClassExpr(QLatin1String("^Q[A-Z3].+"));
hjk's avatar
hjk committed
236
    QTC_ASSERT(qtClassExpr.isValid(), /**/);
con's avatar
con committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
    const bool superIsQtClass = qtClassExpr.exactMatch(params.baseClass);
    if (superIsQtClass) {
        Core::Utils::writeIncludeFileDirective(params.baseClass, true, headerStr);
        headerStr << '\n';
    }

    const QString namespaceIndent = Core::Utils::writeOpeningNameSpaces(namespaceList, 0, headerStr);

    // Class declaration
    headerStr << namespaceIndent << "class " << unqualifiedClassName;
    if (!params.baseClass.isEmpty())
        headerStr << " : public " << params.baseClass << "\n";
    else
        headerStr << "\n";
    headerStr << namespaceIndent << "{\n";
    headerStr << namespaceIndent << "public:\n"
              << namespaceIndent << indent << unqualifiedClassName << "();\n";
    headerStr << namespaceIndent << "};\n\n";

    Core::Utils::writeClosingNameSpaces(namespaceList, 0, headerStr);
    headerStr << "#endif // "<<  guard << '\n';


    // == Source file ==
    QTextStream sourceStr(source);
    Core::Utils::writeIncludeFileDirective(params.headerFile, false, sourceStr);
    Core::Utils::writeOpeningNameSpaces(namespaceList, 0, sourceStr);

    // Constructor
    sourceStr << '\n' << namespaceIndent << unqualifiedClassName << "::" << unqualifiedClassName << "()\n";
    sourceStr << namespaceIndent << "{\n" << namespaceIndent << "}\n";

    Core::Utils::writeClosingNameSpaces(namespaceList, indent, sourceStr);
    return true;
}