variablemanager.cpp 11.5 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
con's avatar
con committed
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
con's avatar
con committed
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
con's avatar
con committed
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
****************************************************************************/
hjk's avatar
hjk committed
29

con's avatar
con committed
30
#include "variablemanager.h"
Friedemann Kleint's avatar
Friedemann Kleint committed
31

Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
32
#include <utils/stringutils.h>
33

34
#include <QCoreApplication>
35
36
37
#include <QFileInfo>
#include <QMap>
#include <QDebug>
Friedemann Kleint's avatar
Friedemann Kleint committed
38

39
40
static const char kFilePathPostfix[] = ":FilePath";
static const char kPathPostfix[] = ":Path";
41
42
static const char kFileNamePostfix[] = ":FileName";
static const char kFileBaseNamePostfix[] = ":FileBaseName";
43

Friedemann Kleint's avatar
Friedemann Kleint committed
44
45
namespace Core {

hjk's avatar
hjk committed
46
47
class VMMapExpander : public Utils::AbstractQtcMacroExpander
{
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
48
49
50
public:
    virtual bool resolveMacro(const QString &name, QString *ret)
    {
51
        bool found;
Eike Ziller's avatar
Eike Ziller committed
52
        *ret = Core::VariableManager::value(name.toUtf8(), &found);
53
        return found;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
54
55
56
    }
};

hjk's avatar
hjk committed
57
class VariableManagerPrivate
Friedemann Kleint's avatar
Friedemann Kleint committed
58
59
{
public:
60
    QHash<QByteArray, VariableManager::StringFunction> m_map;
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
61
    VMMapExpander m_macroExpander;
hjk's avatar
hjk committed
62
    QMap<QByteArray, QString> m_descriptions;
Friedemann Kleint's avatar
Friedemann Kleint committed
63
};
con's avatar
con committed
64

hjk's avatar
hjk committed
65
66
/*!
    \class Core::VariableManager
67
68
69
    \brief The VariableManager class manages \QC wide variables, that a user
    can enter into many string settings. The variables are replaced by an actual value when the string
    is used, similar to how environment variables are expanded by a shell.
hjk's avatar
hjk committed
70

71
72
73
74
75
76
77
78
79
80
81
    \section1 Variables

    Variable names can be basically any string without dollar sign and braces,
    though it is recommended to only use 7-bit ASCII without special characters and whitespace.

    If there are several variables that contain different aspects of the same object,
    it is convention to give them the same prefix, followed by a colon and a postfix
    that describes the aspect.
    Examples of this are \c{CurrentDocument:FilePath} and \c{CurrentDocument:Selection}.

    When the variable manager is requested to replace variables in a string, it looks for
82
    variable names enclosed in %{ and }, like %{CurrentDocument:FilePath}.
83

84
85
86
    Environment variables are accessible using the %{Env:...} notation.
    For example, to access the SHELL environment variable, use %{Env:SHELL}.

87
88
    \note The names of the variables are stored as QByteArray. They are typically
    7-bit-clean. In cases where this is not possible, UTF-8 encoding is
hjk's avatar
hjk committed
89
    assumed.
90
91
92

    \section1 Providing Variable Values

93
94
    Plugins can register variables together with a description through registerVariable().
    A typical setup is to register variables in the Plugin::initialize() function.
95

96
97
98
    \code
    bool MyPlugin::initialize(const QStringList &arguments, QString *errorString)
    {
Tobias Hunger's avatar
Tobias Hunger committed
99
        [...]
100
101
102
103
        VariableManager::registerVariable(
            "MyVariable",
            tr("The current value of whatever I want."));
            []() -> QString {
Tobias Hunger's avatar
Tobias Hunger committed
104
105
106
                QString value;
                // do whatever is necessary to retrieve the value
                [...]
107
                return value;
Tobias Hunger's avatar
Tobias Hunger committed
108
            }
109
110
111
112
        );
        [...]
    }
    \endcode
113
114


115
116
117
    For variables that refer to a file, you should use the convenience function
    VariableManager::registerFileVariables().
    The functions take a variable prefix, like \c MyFileVariable,
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
    and automatically handle standardized postfixes like \c{:FilePath},
    \c{:Path} and \c{:FileBaseName}, resulting in the combined variables, such as
    \c{MyFileVariable:FilePath}.

    \section1 Providing and Expanding Parametrized Strings

    Though it is possible to just ask the variable manager for the value of some variable in your
    code, the preferred use case is to give the user the possibility to parametrize strings, for
    example for settings.

    (If you ever think about doing the former, think twice. It is much more efficient
    to just ask the plugin that provides the variable value directly, without going through
    string conversions, and through the variable manager which will do a large scale poll. To be
    more concrete, using the example from the Providing Variable Values section: instead of
    calling \c{VariableManager::value("MyVariable")}, it is much more efficient to just ask directly
    with \c{MyPlugin::variableValue()}.)

    \section2 User Interface

    If the string that you want to parametrize is settable by the user, through a QLineEdit or
    QTextEdit derived class, you should add a variable chooser to your UI, which allows adding
    variables to the string by browsing through a list. See Core::VariableChooser for more
    details.

    \section2 Expanding Strings

    Expanding variable values in strings is done by "macro expanders".
    Utils::AbstractMacroExpander is the base class for these, and the variable manager
    provides an implementation that expands \QC variables through
    VariableManager::macroExpander().

    There are several different ways to expand a string, covering the different use cases,
    listed here sorted by relevance:
    \list
Tobias Hunger's avatar
Tobias Hunger committed
152
153
154
    \li Using VariableManager::expandedString(). This is the most comfortable way to get a string
        with variable values expanded, but also the least flexible one. If this is sufficient for
        you, use it.
155
    \li Using the Utils::expandMacros() functions. These take a string and a macro expander (for which
Tobias Hunger's avatar
Tobias Hunger committed
156
157
158
159
        you would use the one provided by the variable manager). Mostly the same as
        VariableManager::expandedString(), but also has a variant that does the replacement inline
        instead of returning a new string.
    \li Using Utils::QtcProcess::expandMacros(). This expands the string while conforming to the
160
        quoting rules of the platform it is run on. Use this function with the variable manager's
Tobias Hunger's avatar
Tobias Hunger committed
161
162
163
164
165
        macro expander if your string will be passed as a command line parameter string to an
        external command.
    \li Writing your own macro expander that nests the variable manager's macro expander. And then
        doing one of the above. This allows you to expand additional "local" variables/macros,
        that do not come from the variable manager.
166
167
    \endlist

hjk's avatar
hjk committed
168
169
*/

hjk's avatar
hjk committed
170
static VariableManager *variableManagerInstance = 0;
Eike Ziller's avatar
Eike Ziller committed
171
static VariableManagerPrivate *d;
Friedemann Kleint's avatar
Friedemann Kleint committed
172

173
174
175
/*!
 * \internal
 */
Eike Ziller's avatar
Eike Ziller committed
176
VariableManager::VariableManager()
177
{
Eike Ziller's avatar
Eike Ziller committed
178
    d = new VariableManagerPrivate;
hjk's avatar
hjk committed
179
    variableManagerInstance = this;
180
181
}

182
183
184
/*!
 * \internal
 */
Friedemann Kleint's avatar
Friedemann Kleint committed
185
VariableManager::~VariableManager()
con's avatar
con committed
186
{
hjk's avatar
hjk committed
187
188
    variableManagerInstance = 0;
    delete d;
con's avatar
con committed
189
190
}

191
/*!
192
193
 * Returns the value of the given \a variable. If \a found is given, it is
 * set to true if the variable has a value at all, false if not.
194
 */
hjk's avatar
hjk committed
195
QString VariableManager::value(const QByteArray &variable, bool *found)
Friedemann Kleint's avatar
Friedemann Kleint committed
196
{
197
198
199
200
201
202
    if (variable.startsWith("Env:")) {
        QByteArray ba = qgetenv(variable.data() + 4);
        if (found)
            *found = !ba.isNull();
        return QString::fromLocal8Bit(ba);
    }
203
    if (found)
204
        *found = d->m_map.contains(variable);
205
206
    StringFunction f = d->m_map.value(variable);
    return f ? f() : QString();
Friedemann Kleint's avatar
Friedemann Kleint committed
207
208
}

209
210
211
212
213
214
215
/*!
 * Returns \a stringWithVariables with all variables replaced by their values.
 * See the VariableManager overview documentation for other ways to expand variables.
 *
 * \sa VariableManager
 * \sa macroExpander()
 */
216
217
218
219
220
QString VariableManager::expandedString(const QString &stringWithVariables)
{
    return Utils::expandMacros(stringWithVariables, macroExpander());
}

221
222
223
224
225
226
227
228
/*!
 * Returns a macro expander that is used to expand all variables from the variable manager
 * in a string.
 * See the VariableManager overview documentation for other ways to expand variables.
 *
 * \sa VariableManager
 * \sa expandedString()
 */
Oswald Buddenhagen's avatar
Oswald Buddenhagen committed
229
230
231
232
233
Utils::AbstractMacroExpander *VariableManager::macroExpander()
{
    return &d->m_macroExpander;
}

234
/*!
235
236
237
238
 * Makes the given string-valued \a variable known to the variable manager,
 * together with a localized \a description.
 *
 * \sa registerFileVariables(), registerIntVariable()
239
 */
240
241
void VariableManager::registerVariable(const QByteArray &variable,
    const QString &description, const StringFunction &value)
Friedemann Kleint's avatar
Friedemann Kleint committed
242
{
243
244
    d->m_descriptions.insert(variable, description);
    d->m_map.insert(variable, value);
Friedemann Kleint's avatar
Friedemann Kleint committed
245
}
246

247
/*!
248
249
 * Makes the given integral-valued \a variable known to the variable manager,
 * together with a localized \a description.
250
 *
251
 * \sa registerVariable(), registerFileVariables()
252
 */
253
254
void VariableManager::registerIntVariable(const QByteArray &variable,
    const QString &description, const VariableManager::IntFunction &value)
con's avatar
con committed
255
{
256
    const VariableManager::IntFunction valuecopy = value; // do not capture a reference in a lambda
257
    registerVariable(variable, description,
258
        [valuecopy]() { return QString::number(valuecopy ? valuecopy() : 0); });
con's avatar
con committed
259
260
}

261
/*!
262
 * Convenience function to register several variables with the same \a prefix, that have a file
263
264
265
266
267
268
 * as a value. Takes the prefix and registers variables like \c{prefix:FilePath} and
 * \c{prefix:Path}, with descriptions that start with the given \a heading.
 * For example \c{registerFileVariables("CurrentDocument", tr("Current Document"))} registers
 * variables such as \c{CurrentDocument:FilePath} with description
 * "Current Document: Full path including file name."
 */
269
270
void VariableManager::registerFileVariables(const QByteArray &prefix,
    const QString &heading, const StringFunction &base)
271
{
272
273
    registerVariable(prefix + kFilePathPostfix,
         QCoreApplication::translate("Core::VariableManager", "%1: Full path including file name.").arg(heading),
Orgad Shaneh's avatar
Orgad Shaneh committed
274
         [base]() { return QFileInfo(base()).filePath(); });
275

276
277
    registerVariable(prefix + kPathPostfix,
         QCoreApplication::translate("Core::VariableManager", "%1: Full path excluding file name.").arg(heading),
Orgad Shaneh's avatar
Orgad Shaneh committed
278
         [base]() { return QFileInfo(base()).path(); });
279

280
281
    registerVariable(prefix + kFileNamePostfix,
         QCoreApplication::translate("Core::VariableManager", "%1: File name without path.").arg(heading),
Orgad Shaneh's avatar
Orgad Shaneh committed
282
         [base]() { return QFileInfo(base()).fileName(); });
283

284
285
    registerVariable(prefix + kFileBaseNamePostfix,
         QCoreApplication::translate("Core::VariableManager", "%1: File base name without path and suffix.").arg(heading),
Orgad Shaneh's avatar
Orgad Shaneh committed
286
         [base]() { return QFileInfo(base()).baseName(); });
287
288
}

289
290
291
292
293
294
/*!
 * Returns all registered variable names.
 *
 * \sa registerVariable()
 * \sa registerFileVariables()
 */
Eike Ziller's avatar
Eike Ziller committed
295
QList<QByteArray> VariableManager::variables()
con's avatar
con committed
296
297
298
299
{
    return d->m_descriptions.keys();
}

300
301
302
/*!
 * Returns the description that was registered for the \a variable.
 */
Eike Ziller's avatar
Eike Ziller committed
303
QString VariableManager::variableDescription(const QByteArray &variable)
con's avatar
con committed
304
305
306
307
{
    return d->m_descriptions.value(variable);
}

Friedemann Kleint's avatar
Friedemann Kleint committed
308
} // namespace Core