cppfilesettingspage.cpp 12.1 KB
Newer Older
1
2
3
4
5
6
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
**
** Commercial Usage
**
** 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.
**
** GNU Lesser General Public License Usage
**
** 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.
**
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
27
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
41
42
#include <extensionsystem/pluginmanager.h>

#include <QtCore/QSettings>
#include <QtCore/QDebug>
43
#include <QtCore/QFile>
44
#include <QtCore/QCoreApplication>
45
46
#include <QtCore/QDate>
#include <QtCore/QLocale>
47
#include <QtCore/QTextStream>
48
49
50

#include <QtGui/QFileDialog>
#include <QtGui/QMessageBox>
51
52
53

static const char *headerSuffixKeyC = "HeaderSuffix";
static const char *sourceSuffixKeyC = "SourceSuffix";
54
55
56
57
58
59
60
61
62
static const char *licenseTemplatePathKeyC = "LicenseTemplate";

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");
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77

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);
78
    s->setValue(QLatin1String(licenseTemplatePathKeyC), licenseTemplatePath);
79
80
81
82
83
84
85
86
    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();
87
88
    const bool lowerCaseDefault = Constants::lowerCaseFilesDefault;
    lowerCaseFiles = s->value(QLatin1String(Constants::LOWERCASE_CPPFILES_KEY), QVariant(lowerCaseDefault)).toBool();
89
    licenseTemplatePath = s->value(QLatin1String(licenseTemplatePathKeyC), QString()).toString();
90
91
92
    s->endGroup();
}

93
bool CppFileSettings::applySuffixesToMimeDB()
94
95
{
    Core::MimeDatabase *mdb = Core::ICore::instance()->mimeDatabase();
96
97
    return mdb->setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE), sourceSuffix)
            && mdb->setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE), headerSuffix);
98
99
100
101
102
103
}

bool CppFileSettings::equals(const CppFileSettings &rhs) const
{
    return lowerCaseFiles == rhs.lowerCaseFiles
           && headerSuffix == rhs.headerSuffix
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
           && sourceSuffix == rhs.sourceSuffix
           && licenseTemplatePath == rhs.licenseTemplatePath;
}

// Replacements of special license template keywords.
static QString keyWordReplacement(const QString &keyWord)
{
    if (keyWord == QLatin1String("%YEAR%")) {
        return QString::number(QDate::currentDate().year());
    }
    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));
        }
        return QDate::currentDate().toString(format);
    }
    if (keyWord == QLatin1String("%USER%")) {
#ifdef Q_OS_WIN
        return QString::fromLocal8Bit(qgetenv("USERNAME"));
#else
        return QString::fromLocal8Bit(qgetenv("USER"));
#endif
    }
    // Environment variables (for example '%$EMAIL%').
    if (keyWord.startsWith(QLatin1String("%$"))) {
        const QString varName = keyWord.mid(2, keyWord.size() - 3);
        return QString::fromLocal8Bit(qgetenv(varName.toLocal8Bit()));
    }
    return QString();
}

// Parse a license template, scan for %KEYWORD% and replace if known.
// Replace '%%' by '%'.
static void parseLicenseTemplatePlaceholders(QString *t)
{
    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);
            const QString replacement = keyWordReplacement(keyWord);
            if (replacement.isEmpty()) {
                pos = endPlaceHolderPos + 1;
            } else {
                t->replace(placeHolderPos, keyWord.size(), replacement);
                pos = placeHolderPos + replacement.size();
            }
        }
    } while (pos < t->size());
}

// Convenience that returns the formatted license template.
QString CppFileSettings::licenseTemplate()
{

    const QSettings *s = Core::ICore::instance()->settings();
    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();
    }
    QString license = QString::fromUtf8(file.readAll());
    parseLicenseTemplatePlaceholders(&license);
    // Ensure exactly one additional new line separating stuff
    const QChar newLine = QLatin1Char('\n');
    if (!license.endsWith(newLine))
        license += newLine;
    license += newLine;
    return license;
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
}

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

CppFileSettingsWidget::CppFileSettingsWidget(QWidget *parent) :
    QWidget(parent),
    m_ui(new Ui::CppFileSettingsPage)
{
    m_ui->setupUi(this);
    const Core::MimeDatabase *mdb = Core::ICore::instance()->mimeDatabase();
    // 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);
212
    m_ui->licenseTemplatePathChooser->setExpectedKind(Utils::PathChooser::File);
213
    m_ui->licenseTemplatePathChooser->addButton(tr("Edit..."), this, SLOT(slotEdit()));
214
215
216
217
218
219
220
}

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

221
222
223
224
225
226
227
228
229
230
QString CppFileSettingsWidget::licenseTemplatePath() const
{
    return m_ui->licenseTemplatePathChooser->path();
}

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

231
232
233
234
235
236
CppFileSettings CppFileSettingsWidget::settings() const
{
    CppFileSettings rc;
    rc.lowerCaseFiles = m_ui->lowerCaseFileNamesCheckBox->isChecked();
    rc.headerSuffix = m_ui->headerSuffixComboBox->currentText();
    rc.sourceSuffix = m_ui->sourceSuffixComboBox->currentText();
237
    rc.licenseTemplatePath = licenseTemplatePath();
238
239
240
    return rc;
}

241
242
243
244
245
QString CppFileSettingsWidget::searchKeywords() const
{
    QString rc;
    QTextStream(&rc) << m_ui->headerSuffixLabel->text()
            << ' ' << m_ui->sourceSuffixLabel->text()
246
247
            << ' ' << m_ui->lowerCaseFileNamesCheckBox->text()
            << ' ' << m_ui->licenseTemplateLabel->text();
248
249
250
251
    rc.remove(QLatin1Char('&'));
    return rc;
}

252
253
254
255
256
257
258
259
260
261
262
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);
263
264
265
266
267
268
269
270
271
272
273
274
    setLicenseTemplatePath(s.licenseTemplatePath);
}

void CppFileSettingsWidget::slotEdit()
{
    QString path = licenseTemplatePath();
    // Edit existing file with C++
    if (!path.isEmpty()) {
        Core::EditorManager::instance()->openEditor(path, QLatin1String(CppEditor::Constants::CPPEDITOR_KIND));
        return;
    }
    // Pick a file name and write new template, edit with C++
275
    path = QFileDialog::getSaveFileName(this, tr("Choose a location for the new license template file"));
276
277
278
    if (path.isEmpty())
        return;
    QFile file(path);
279
    if (!file.open(QIODevice::WriteOnly|QIODevice::Text|QIODevice::Truncate)) {
280
281
282
283
284
285
286
287
        QMessageBox::warning(this, tr("Template write error"),
                             tr("Cannot write to %1: %2").arg(path, file.errorString()));
        return;
    }
    file.write(tr(licenseTemplateTemplate).toUtf8());
    file.close();
    setLicenseTemplatePath(path);
    Core::EditorManager::instance()->openEditor(path, QLatin1String(CppEditor::Constants::CPPEDITOR_KIND));
288
289
290
}

// --------------- CppFileSettingsPage
291
292
293
294
CppFileSettingsPage::CppFileSettingsPage(QSharedPointer<CppFileSettings> &settings,
                                         QObject *parent) :
    Core::IOptionsPage(parent),
    m_settings(settings)
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
{
}

CppFileSettingsPage::~CppFileSettingsPage()
{
}

QString CppFileSettingsPage::id() const
{
    return QLatin1String(Constants::CPP_SETTINGS_ID);
}

QString CppFileSettingsPage::trName() const
{
    return QCoreApplication::translate("CppTools", Constants::CPP_SETTINGS_ID);
}

QString CppFileSettingsPage::category() const
{
    return QLatin1String(Constants::CPP_SETTINGS_CATEGORY);
}

QString CppFileSettingsPage::trCategory() const
{
    return QCoreApplication::translate("CppTools", Constants::CPP_SETTINGS_CATEGORY);
}

QWidget *CppFileSettingsPage::createPage(QWidget *parent)
{

    m_widget = new CppFileSettingsWidget(parent);
326
    m_widget->setSettings(*m_settings);
327
328
    if (m_searchKeywords.isEmpty())
        m_searchKeywords = m_widget->searchKeywords();
329
330
331
332
333
334
335
    return m_widget;
}

void CppFileSettingsPage::apply()
{
    if (m_widget) {
        const CppFileSettings newSettings = m_widget->settings();
336
337
338
339
        if (newSettings != *m_settings) {
            *m_settings = newSettings;
            m_settings->toSettings(Core::ICore::instance()->settings());
            m_settings->applySuffixesToMimeDB();
340
341
342
343
        }
    }
}

344
345
346
347
348
bool CppFileSettingsPage::matches(const QString &s) const
{
    return m_searchKeywords.contains(s, Qt::CaseInsensitive);
}

349
350
351
}
}