cppfilesettingspage.cpp 13 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
hjk's avatar
hjk committed
3
4
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** 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
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** 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.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
con's avatar
con committed
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29
30
31
32
33
34

#include "cppfilesettingspage.h"
#include "cpptoolsconstants.h"
#include "ui_cppfilesettingspage.h"

#include <coreplugin/icore.h>
35
#include <coreplugin/editormanager/editormanager.h>
36
#include <coreplugin/mimedatabase.h>
37
38
#include <cppeditor/cppeditorconstants.h>

39
40
#include <extensionsystem/pluginmanager.h>

41
#include <utils/environment.h>
42
43
#include <utils/fileutils.h>

44
45
46
47
48
49
50
51
52
#include <QSettings>
#include <QDebug>
#include <QFile>
#include <QFileInfo>
#include <QCoreApplication>
#include <QDate>
#include <QLocale>
#include <QTextCodec>
#include <QTextStream>
53

54
55
#include <QFileDialog>
#include <QMessageBox>
56

57
58
59
static const char headerSuffixKeyC[] = "HeaderSuffix";
static const char sourceSuffixKeyC[] = "SourceSuffix";
static const char licenseTemplatePathKeyC[] = "LicenseTemplate";
60
61
62
63
64
65
66
67

const char *licenseTemplateTemplate = QT_TRANSLATE_NOOP("CppTools::Internal::CppFileSettingsWidget",
"/**************************************************************************\n"
"** Qt Creator license header template\n"
"**   Special keywords: %USER% %DATE% %YEAR%\n"
"**   Environment variables: %$VARIABLE%\n"
"**   To protect a percent sign, use '%%'.\n"
"**************************************************************************/\n");
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82

namespace CppTools {
namespace Internal {

CppFileSettings::CppFileSettings() :
    lowerCaseFiles(false)
{
}

void CppFileSettings::toSettings(QSettings *s) const
{
    s->beginGroup(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP));
    s->setValue(QLatin1String(headerSuffixKeyC), headerSuffix);
    s->setValue(QLatin1String(sourceSuffixKeyC), sourceSuffix);
    s->setValue(QLatin1String(Constants::LOWERCASE_CPPFILES_KEY), lowerCaseFiles);
83
    s->setValue(QLatin1String(licenseTemplatePathKeyC), licenseTemplatePath);
84
85
86
87
88
89
90
91
    s->endGroup();
}

void CppFileSettings::fromSettings(QSettings *s)
{
    s->beginGroup(QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP));
    headerSuffix= s->value(QLatin1String(headerSuffixKeyC), QLatin1String("h")).toString();
    sourceSuffix = s->value(QLatin1String(sourceSuffixKeyC), QLatin1String("cpp")).toString();
92
93
    const bool lowerCaseDefault = Constants::lowerCaseFilesDefault;
    lowerCaseFiles = s->value(QLatin1String(Constants::LOWERCASE_CPPFILES_KEY), QVariant(lowerCaseDefault)).toBool();
94
    licenseTemplatePath = s->value(QLatin1String(licenseTemplatePathKeyC), QString()).toString();
95
96
97
    s->endGroup();
}

98
bool CppFileSettings::applySuffixesToMimeDB()
99
{
hjk's avatar
hjk committed
100
    Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
101
102
    return mdb->setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE), sourceSuffix)
            && mdb->setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE), headerSuffix);
103
104
105
106
107
108
}

bool CppFileSettings::equals(const CppFileSettings &rhs) const
{
    return lowerCaseFiles == rhs.lowerCaseFiles
           && headerSuffix == rhs.headerSuffix
109
110
111
112
113
           && sourceSuffix == rhs.sourceSuffix
           && licenseTemplatePath == rhs.licenseTemplatePath;
}

// Replacements of special license template keywords.
114
115
116
117
static bool keyWordReplacement(const QString &keyWord,
                               const QString &file,
                               const QString &className,
                               QString *value)
118
119
{
    if (keyWord == QLatin1String("%YEAR%")) {
120
121
122
        *value = QString::number(QDate::currentDate().year());
        return true;
    }
123
124
125
126
127
128
129
130
    if (keyWord == QLatin1String("%MONTH%")) {
        *value = QString::number(QDate::currentDate().month());
        return true;
    }
    if (keyWord == QLatin1String("%DAY%")) {
        *value = QString::number(QDate::currentDate().day());
        return true;
    }
131
132
133
134
135
136
137
    if (keyWord == QLatin1String("%CLASS%")) {
        *value = className;
        return true;
    }
    if (keyWord == QLatin1String("%FILENAME%")) {
        *value = QFileInfo(file).fileName();
        return true;
138
139
140
141
142
143
144
145
146
147
148
    }
    if (keyWord == QLatin1String("%DATE%")) {
        static QString format;
        // ensure a format with 4 year digits. Some have locales have 2.
        if (format.isEmpty()) {
            QLocale loc;
            format = loc.dateFormat(QLocale::ShortFormat);
            const QChar ypsilon = QLatin1Char('y');
            if (format.count(ypsilon) == 2)
                format.insert(format.indexOf(ypsilon), QString(2, ypsilon));
        }
149
150
        *value = QDate::currentDate().toString(format);
        return true;
151
152
    }
    if (keyWord == QLatin1String("%USER%")) {
153
        *value = Utils::Environment::systemEnvironment().userName();
154
        return true;
155
156
157
158
    }
    // Environment variables (for example '%$EMAIL%').
    if (keyWord.startsWith(QLatin1String("%$"))) {
        const QString varName = keyWord.mid(2, keyWord.size() - 3);
159
160
        *value = QString::fromLocal8Bit(qgetenv(varName.toLocal8Bit()));
        return true;
161
    }
162
    return false;
163
164
165
166
}

// Parse a license template, scan for %KEYWORD% and replace if known.
// Replace '%%' by '%'.
167
static void parseLicenseTemplatePlaceholders(QString *t, const QString &file, const QString &className)
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
{
    int pos = 0;
    const QChar placeHolder = QLatin1Char('%');
    do {
        const int placeHolderPos = t->indexOf(placeHolder, pos);
        if (placeHolderPos == -1)
            break;
        const int endPlaceHolderPos = t->indexOf(placeHolder, placeHolderPos + 1);
        if (endPlaceHolderPos == -1)
            break;
        if (endPlaceHolderPos == placeHolderPos + 1) { // '%%' -> '%'
            t->remove(placeHolderPos, 1);
            pos = placeHolderPos + 1;
        } else {
            const QString keyWord = t->mid(placeHolderPos, endPlaceHolderPos + 1 - placeHolderPos);
183
184
            QString replacement;
            if (keyWordReplacement(keyWord, file, className, &replacement)) {
185
186
                t->replace(placeHolderPos, keyWord.size(), replacement);
                pos = placeHolderPos + replacement.size();
187
188
189
            } else {
                // Leave invalid keywords as is.
                pos = endPlaceHolderPos + 1;
190
191
192
193
194
195
            }
        }
    } while (pos < t->size());
}

// Convenience that returns the formatted license template.
196
QString CppFileSettings::licenseTemplate(const QString &fileName, const QString &className)
197
198
{

hjk's avatar
hjk committed
199
    const QSettings *s = Core::ICore::settings();
200
201
202
203
204
205
206
207
208
209
210
    QString key = QLatin1String(Constants::CPPTOOLS_SETTINGSGROUP);
    key += QLatin1Char('/');
    key += QLatin1String(licenseTemplatePathKeyC);
    const QString path = s->value(key, QString()).toString();
    if (path.isEmpty())
        return QString();
    QFile file(path);
    if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) {
        qWarning("Unable to open the license template %s: %s", qPrintable(path), qPrintable(file.errorString()));
        return QString();
    }
211

212
    QTextCodec *codec = Core::EditorManager::instance()->defaultTextCodec();
213
214
215
216
217
    QTextStream licenseStream(&file);
    licenseStream.setCodec(codec);
    licenseStream.setAutoDetectUnicode(true);
    QString license = licenseStream.readAll();

218
    parseLicenseTemplatePlaceholders(&license, fileName, className);
219
220
221
222
223
224
    // Ensure exactly one additional new line separating stuff
    const QChar newLine = QLatin1Char('\n');
    if (!license.endsWith(newLine))
        license += newLine;
    license += newLine;
    return license;
225
226
227
228
229
230
}

// ------------------ CppFileSettingsWidget

CppFileSettingsWidget::CppFileSettingsWidget(QWidget *parent) :
    QWidget(parent),
231
    m_ui(new Internal::Ui::CppFileSettingsPage)
232
233
{
    m_ui->setupUi(this);
hjk's avatar
hjk committed
234
    const Core::MimeDatabase *mdb = Core::ICore::mimeDatabase();
235
236
237
238
239
240
241
242
    // populate suffix combos
    if (const Core::MimeType sourceMt = mdb->findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)))
        foreach (const QString &suffix, sourceMt.suffixes())
            m_ui->sourceSuffixComboBox->addItem(suffix);

    if (const Core::MimeType headerMt = mdb->findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)))
        foreach (const QString &suffix, headerMt.suffixes())
            m_ui->headerSuffixComboBox->addItem(suffix);
243
    m_ui->licenseTemplatePathChooser->setExpectedKind(Utils::PathChooser::File);
244
    m_ui->licenseTemplatePathChooser->addButton(tr("Edit..."), this, SLOT(slotEdit()));
245
246
247
248
249
250
251
}

CppFileSettingsWidget::~CppFileSettingsWidget()
{
    delete m_ui;
}

252
253
254
255
256
257
258
259
260
261
QString CppFileSettingsWidget::licenseTemplatePath() const
{
    return m_ui->licenseTemplatePathChooser->path();
}

void CppFileSettingsWidget::setLicenseTemplatePath(const QString &lp)
{
    m_ui->licenseTemplatePathChooser->setPath(lp);
}

262
263
264
265
266
267
CppFileSettings CppFileSettingsWidget::settings() const
{
    CppFileSettings rc;
    rc.lowerCaseFiles = m_ui->lowerCaseFileNamesCheckBox->isChecked();
    rc.headerSuffix = m_ui->headerSuffixComboBox->currentText();
    rc.sourceSuffix = m_ui->sourceSuffixComboBox->currentText();
268
    rc.licenseTemplatePath = licenseTemplatePath();
269
270
271
    return rc;
}

272
273
274
275
276
QString CppFileSettingsWidget::searchKeywords() const
{
    QString rc;
    QTextStream(&rc) << m_ui->headerSuffixLabel->text()
            << ' ' << m_ui->sourceSuffixLabel->text()
277
278
            << ' ' << m_ui->lowerCaseFileNamesCheckBox->text()
            << ' ' << m_ui->licenseTemplateLabel->text();
279
280
281
282
    rc.remove(QLatin1Char('&'));
    return rc;
}

283
284
285
286
287
288
289
290
291
292
293
static inline void setComboText(QComboBox *cb, const QString &text, int defaultIndex = 0)
{
    const int index = cb->findText(text);
    cb->setCurrentIndex(index == -1 ? defaultIndex: index);
}

void CppFileSettingsWidget::setSettings(const CppFileSettings &s)
{
    m_ui->lowerCaseFileNamesCheckBox->setChecked(s.lowerCaseFiles);
    setComboText(m_ui->headerSuffixComboBox, s.headerSuffix);
    setComboText(m_ui->sourceSuffixComboBox, s.sourceSuffix);
294
295
296
297
298
299
    setLicenseTemplatePath(s.licenseTemplatePath);
}

void CppFileSettingsWidget::slotEdit()
{
    QString path = licenseTemplatePath();
300
301
302
303
304
305
306
307
308
309
    if (path.isEmpty()) {
        // Pick a file name and write new template, edit with C++
        path = QFileDialog::getSaveFileName(this, tr("Choose Location for New License Template File"));
        if (path.isEmpty())
            return;
        Utils::FileSaver saver(path, QIODevice::Text);
        saver.write(tr(licenseTemplateTemplate).toUtf8());
        if (!saver.finalize(this))
            return;
        setLicenseTemplatePath(path);
310
    }
311
    // Edit (now) existing file with C++
hjk's avatar
hjk committed
312
313
    Core::EditorManager::openEditor(path, CppEditor::Constants::CPPEDITOR_ID,
                                    Core::EditorManager::ModeSwitch);
314
315
316
}

// --------------- CppFileSettingsPage
317
318
319
320
CppFileSettingsPage::CppFileSettingsPage(QSharedPointer<CppFileSettings> &settings,
                                         QObject *parent) :
    Core::IOptionsPage(parent),
    m_settings(settings)
321
{
hjk's avatar
hjk committed
322
    setId(Constants::CPP_FILE_SETTINGS_ID);
323
    setDisplayName(QCoreApplication::translate("CppTools", Constants::CPP_FILE_SETTINGS_NAME));
hjk's avatar
hjk committed
324
    setCategory(Constants::CPP_SETTINGS_CATEGORY);
325
326
    setDisplayCategory(QCoreApplication::translate("CppTools", Constants::CPP_SETTINGS_TR_CATEGORY));
    setCategoryIcon(QLatin1String(Constants::SETTINGS_CATEGORY_CPP_ICON));
327
328
}

329
330
331
332
QWidget *CppFileSettingsPage::createPage(QWidget *parent)
{

    m_widget = new CppFileSettingsWidget(parent);
333
    m_widget->setSettings(*m_settings);
334
335
    if (m_searchKeywords.isEmpty())
        m_searchKeywords = m_widget->searchKeywords();
336
337
338
339
340
341
342
    return m_widget;
}

void CppFileSettingsPage::apply()
{
    if (m_widget) {
        const CppFileSettings newSettings = m_widget->settings();
343
344
        if (newSettings != *m_settings) {
            *m_settings = newSettings;
hjk's avatar
hjk committed
345
            m_settings->toSettings(Core::ICore::settings());
346
            m_settings->applySuffixesToMimeDB();
347
348
349
350
        }
    }
}

351
352
353
354
355
bool CppFileSettingsPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

356
357
} // namespace Internal
} // namespace CppTools