summaryrefslogtreecommitdiffstats
path: root/src/qt3support/text/q3simplerichtext.cpp
blob: 020b7dbadff98e39a88d95fd9e970d3899d60e6f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
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
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
228
229
230
231
232
233
234
235
236
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
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
420
421
/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt3Support module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "q3simplerichtext.h"

#ifndef QT_NO_RICHTEXT
#include "q3richtext_p.h"
#include "qapplication.h"

QT_BEGIN_NAMESPACE

class Q3SimpleRichTextData
{
public:
    Q3TextDocument *doc;
    QFont font;
    int cachedWidth;
    bool cachedWidthWithPainter;
    void adjustSize();
};

// Pull this private function in from qglobal.cpp
Q_CORE_EXPORT unsigned int qt_int_sqrt(unsigned int n);

void Q3SimpleRichTextData::adjustSize() {
    QFontMetrics fm(font);
    int mw =  fm.width(QString(QLatin1Char('x'))) * 80;
    int w = mw;
    doc->doLayout(0,w);
    if (doc->widthUsed() != 0) {
        w = qt_int_sqrt(5 * doc->height() * doc->widthUsed() / 3);
        doc->doLayout(0, qMin(w, mw));

        if (w*3 < 5*doc->height()) {
            w = qt_int_sqrt(2 * doc->height() * doc->widthUsed());
            doc->doLayout(0,qMin(w, mw));
        }
    }
    cachedWidth = doc->width();
    cachedWidthWithPainter = false;
}

/*!
    \class Q3SimpleRichText
    \brief The Q3SimpleRichText class provides a small displayable piece of rich text.

    \compat

    This class encapsulates simple rich text usage in which a string
    is interpreted as rich text and can be drawn. This is particularly
    useful if you want to display some rich text in a custom widget. A
    Q3StyleSheet is needed to interpret the tags and format the rich
    text. Qt provides a default HTML-like style sheet, but you may
    define custom style sheets.

    Once created, the rich text object can be queried for its width(),
    height(), and the actual width used (see widthUsed()). Most
    importantly, it can be drawn on any given QPainter with draw().
    Q3SimpleRichText can also be used to implement hypertext or active
    text facilities by using anchorAt(). A hit test through inText()
    makes it possible to use simple rich text for text objects in
    editable drawing canvases.

    Once constructed from a string the contents cannot be changed,
    only resized. If the contents change, just throw the rich text
    object away and make a new one with the new contents.

    For large documents use QTextEdit or QTextBrowser. For very small
    items of rich text you can use a QLabel.

    If you are using Q3SimpleRichText to print in high resolution you
    should call setWidth(QPainter, int) so that the content will be
    laid out properly on the page.
*/

/*!
    Constructs a Q3SimpleRichText from the rich text string \a text and
    the font \a fnt.

    The font is used as a basis for the text rendering. When using
    rich text rendering on a widget \e w, you would normally specify
    the widget's font, for example:

    \snippet doc/src/snippets/code/src_qt3support_text_q3simplerichtext.cpp 0

    \a context is the optional context of the rich text object. This
    becomes important if \a text contains relative references, for
    example within image tags. Q3SimpleRichText always uses the default
    mime source factory (see \l{Q3MimeSourceFactory::defaultFactory()})
    to resolve those references. The context will then be used to
    calculate the absolute path. See
    Q3MimeSourceFactory::makeAbsolute() for details.

    The \a sheet is an optional style sheet. If it is 0, the default
    style sheet will be used (see \l{Q3StyleSheet::defaultSheet()}).
*/

Q3SimpleRichText::Q3SimpleRichText(const QString& text, const QFont& fnt,
                                  const QString& context, const Q3StyleSheet* sheet)
{
    d = new Q3SimpleRichTextData;
    d->cachedWidth = -1;
    d->cachedWidthWithPainter = false;
    d->font = fnt;
    d->doc = new Q3TextDocument(0);
    d->doc->setTextFormat(Qt::RichText);
    d->doc->setLeftMargin(0);
    d->doc->setRightMargin(0);
    d->doc->setFormatter(new Q3TextFormatterBreakWords);
    d->doc->setStyleSheet((Q3StyleSheet*)sheet);
    d->doc->setDefaultFormat(fnt, QColor());
    d->doc->setText(text, context);
}


/*!
    Constructs a Q3SimpleRichText from the rich text string \a text and
    the font \a fnt.

    This is a slightly more complex constructor for Q3SimpleRichText
    that takes an additional mime source factory \a factory, a page
    break parameter \a pageBreak and a bool \a linkUnderline. \a
    linkColor is only provided for compatibility, but has no effect,
    as QPalette::link() color is used now.

    \a context is the optional context of the rich text object. This
    becomes important if \a text contains relative references, for
    example within image tags. Q3SimpleRichText always uses the default
    mime source factory (see \l{Q3MimeSourceFactory::defaultFactory()})
    to resolve those references. The context will then be used to
    calculate the absolute path. See
    Q3MimeSourceFactory::makeAbsolute() for details.

    The \a sheet is an optional style sheet. If it is 0, the default
    style sheet will be used (see \l{Q3StyleSheet::defaultSheet()}).

    This constructor is useful for creating a Q3SimpleRichText object
    suitable for printing. Set \a pageBreak to be the height of the
    contents area of the pages.
*/

Q3SimpleRichText::Q3SimpleRichText(const QString& text, const QFont& fnt,
                                  const QString& context, const Q3StyleSheet* sheet,
                                  const Q3MimeSourceFactory* factory, int pageBreak,
                                  const QColor& /*linkColor*/, bool linkUnderline)
{
    d = new Q3SimpleRichTextData;
    d->cachedWidth = -1;
    d->cachedWidthWithPainter = false;
    d->font = fnt;
    d->doc = new Q3TextDocument(0);
    d->doc->setTextFormat(Qt::RichText);
    d->doc->setFormatter(new Q3TextFormatterBreakWords);
    d->doc->setStyleSheet((Q3StyleSheet*)sheet);
    d->doc->setDefaultFormat(fnt, QColor());
    d->doc->flow()->setPageSize(pageBreak);
    d->doc->setPageBreakEnabled(true);
#ifndef QT_NO_MIME
    d->doc->setMimeSourceFactory((Q3MimeSourceFactory*)factory);
#endif
    d->doc->setUnderlineLinks(linkUnderline);
    d->doc->setText(text, context);
}

/*!
    Destroys the rich text object, freeing memory.
*/

Q3SimpleRichText::~Q3SimpleRichText()
{
    delete d->doc;
    delete d;
}

/*!
    \overload

    Sets the width of the rich text object to \a w pixels.

    \sa height(), adjustSize()
*/

void Q3SimpleRichText::setWidth(int w)
{
    if (w == d->cachedWidth && !d->cachedWidthWithPainter)
        return;
    d->doc->formatter()->setAllowBreakInWords(d->doc->isPageBreakEnabled());
    d->cachedWidth = w;
    d->cachedWidthWithPainter = false;
    d->doc->doLayout(0, w);
}

/*!
    Sets the width of the rich text object to \a w pixels,
    recalculating the layout as if it were to be drawn with painter \a
    p.

    Passing a painter is useful when you intend drawing on devices
    other than the screen, for example a QPrinter.

    \sa height(), adjustSize()
*/

void Q3SimpleRichText::setWidth(QPainter *p, int w)
{
    if (w == d->cachedWidth  && d->cachedWidthWithPainter)
        return;
    d->doc->formatter()->setAllowBreakInWords(d->doc->isPageBreakEnabled() ||
                       (p && p->device() &&
                     p->device()->devType() == QInternal::Printer));
    p->save();
    d->cachedWidth = w;
    d->cachedWidthWithPainter = true;
    d->doc->doLayout(p, w);
    p->restore();
}

/*!
    Returns the set width of the rich text object in pixels.

    \sa widthUsed()
*/

int Q3SimpleRichText::width() const
{
    if (d->cachedWidth < 0)
        d->adjustSize();
    return d->doc->width();
}

/*!
    Returns the width in pixels that is actually used by the rich text
    object. This can be smaller or wider than the set width.

    It may be wider, for example, if the text contains images or
    non-breakable words that are already wider than the available
    space. It's smaller when the object only consists of lines that do
    not fill the width completely.

    \sa width()
*/

int Q3SimpleRichText::widthUsed() const
{
    if (d->cachedWidth < 0)
        d->adjustSize();
    return d->doc->widthUsed();
}

/*!
    Returns the height of the rich text object in pixels.

    \sa setWidth()
*/

int Q3SimpleRichText::height() const
{
    if (d->cachedWidth < 0)
        d->adjustSize();
    return d->doc->height();
}

/*!
    Adjusts the rich text object to a reasonable size.

    \sa setWidth()
*/

void Q3SimpleRichText::adjustSize()
{
    d->adjustSize();
}

/*!
    Draws the formatted text with painter \a p, at position (\a x, \a
    y), clipped to \a clipRect. The clipping rectangle is given in the
    rich text object's coordinates translated by (\a x, \a y). Passing
    an null rectangle results in no clipping. Colors from the color
    group \a cg are used as needed, and if not 0, *\a{paper} is
    used as the background brush.

    Note that the display code is highly optimized to reduce flicker,
    so passing a brush for \a paper is preferable to simply clearing
    the area to be painted and then calling this without a brush.
*/

void Q3SimpleRichText::draw(QPainter *p, int x, int y, const QRect& clipRect,
                            const QColorGroup &cg, const QBrush* paper) const
{
    p->save();
    if (d->cachedWidth < 0)
        d->adjustSize();
    QRect r = clipRect;
    if (!r.isNull())
        r.moveBy(-x, -y);

    if (paper)
        d->doc->setPaper(new QBrush(*paper));
    QPalette pal2 = cg;
    if (d->doc->paper())
        pal2.setBrush(QPalette::Base, *d->doc->paper());

    if (!clipRect.isNull())
        p->setClipRect(clipRect);
    p->translate(x, y);
    d->doc->draw(p, r, pal2, paper);
    p->translate(-x, -y);
    p->restore();
}


/*! \fn void Q3SimpleRichText::draw(QPainter *p, int x, int y, const QRegion& clipRegion,
  const QColorGroup &cg, const QBrush* paper) const

  Use the version with clipRect instead of this \a clipRegion version,
  since this region version has problems with larger documents on some
  platforms (on X11 regions internally are represented with 16-bit
  coordinates).
*/



/*!
    Returns the context of the rich text object. If no context has
    been specified in the constructor, an empty string is returned. The
    context is the path to use to look up relative links, such as
    image tags and anchor references.
*/

QString Q3SimpleRichText::context() const
{
    return d->doc->context();
}

/*!
    Returns the anchor at the requested position, \a pos. An empty
    string is returned if no anchor is specified for this position.
*/

QString Q3SimpleRichText::anchorAt(const QPoint& pos) const
{
    if (d->cachedWidth < 0)
        d->adjustSize();
    Q3TextCursor c(d->doc);
    c.place(pos, d->doc->firstParagraph(), true);
    return c.paragraph()->at(c.index())->anchorHref();
}

/*!
    Returns true if \a pos is within a text line of the rich text
    object; otherwise returns false.
*/

bool Q3SimpleRichText::inText(const QPoint& pos) const
{
    if (d->cachedWidth < 0)
        d->adjustSize();
    if (pos.y()  > d->doc->height())
        return false;
    Q3TextCursor c(d->doc);
    c.place(pos, d->doc->firstParagraph());
    return c.totalOffsetX() + c.paragraph()->at(c.index())->x +
        c.paragraph()->at(c.index())->format()->width(c.paragraph()->at(c.index())->c) > pos.x();
}

/*!
    Sets the default font for the rich text object to \a f
*/

void Q3SimpleRichText::setDefaultFont(const QFont &f)
{
    if (d->font == f)
        return;
    d->font = f;
    d->cachedWidth = -1;
    d->cachedWidthWithPainter = false;
    d->doc->setDefaultFormat(f, QColor());
    d->doc->setText(d->doc->originalText(), d->doc->context());
}

QT_END_NAMESPACE

#endif //QT_NO_RICHTEXT
an> suffix += cmSystemTools::UpperCase(config); } else { suffix += "NOCONFIG"; } // Generate the per-config target information. this->GenerateImportTargetsConfig(os, config, suffix, missingTargets); } void cmExportFileGenerator::PopulateInterfaceProperty( const std::string& propName, cmGeneratorTarget* target, ImportPropertyMap& properties) { const char* input = target->GetProperty(propName); if (input) { properties[propName] = input; } } void cmExportFileGenerator::PopulateInterfaceProperty( const std::string& propName, const std::string& outputName, cmGeneratorTarget* target, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { const char* input = target->GetProperty(propName); if (input) { if (!*input) { // Set to empty properties[outputName].clear(); return; } std::string prepro = cmGeneratorExpression::Preprocess(input, preprocessRule); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets); properties[outputName] = prepro; } } } void cmExportFileGenerator::GenerateRequiredCMakeVersion( std::ostream& os, const char* versionString) { /* clang-format off */ os << "if(CMAKE_VERSION VERSION_LESS " << versionString << ")\n" " message(FATAL_ERROR \"This file relies on consumers using " "CMake " << versionString << " or greater.\")\n" "endif()\n\n"; /* clang-format on */ } bool cmExportFileGenerator::PopulateInterfaceLinkLibrariesProperty( cmGeneratorTarget* target, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { if (!target->IsLinkable()) { return false; } const char* input = target->GetProperty("INTERFACE_LINK_LIBRARIES"); if (input) { std::string prepro = cmGeneratorExpression::Preprocess(input, preprocessRule); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions( prepro, target, missingTargets, ReplaceFreeTargets); properties["INTERFACE_LINK_LIBRARIES"] = prepro; return true; } } return false; } static bool isSubDirectory(std::string const& a, std::string const& b) { return (cmSystemTools::ComparePath(a, b) || cmSystemTools::IsSubDirectory(a, b)); } static bool checkInterfaceDirs(const std::string& prepro, cmGeneratorTarget* target, const std::string& prop) { std::string const& installDir = target->Makefile->GetSafeDefinition("CMAKE_INSTALL_PREFIX"); std::string const& topSourceDir = target->GetLocalGenerator()->GetSourceDirectory(); std::string const& topBinaryDir = target->GetLocalGenerator()->GetBinaryDirectory(); std::vector<std::string> parts; cmGeneratorExpression::Split(prepro, parts); const bool inSourceBuild = topSourceDir == topBinaryDir; bool hadFatalError = false; for (std::string const& li : parts) { size_t genexPos = cmGeneratorExpression::Find(li); if (genexPos == 0) { continue; } MessageType messageType = MessageType::FATAL_ERROR; std::ostringstream e; if (genexPos != std::string::npos) { if (prop == "INTERFACE_INCLUDE_DIRECTORIES") { switch (target->GetPolicyStatusCMP0041()) { case cmPolicies::WARN: messageType = MessageType::WARNING; e << cmPolicies::GetPolicyWarning(cmPolicies::CMP0041) << "\n"; break; case cmPolicies::OLD: continue; case cmPolicies::REQUIRED_IF_USED: case cmPolicies::REQUIRED_ALWAYS: case cmPolicies::NEW: hadFatalError = true; break; // Issue fatal message. } } else { hadFatalError = true; } } if (cmHasLiteralPrefix(li, "${_IMPORT_PREFIX}")) { continue; } if (!cmSystemTools::FileIsFullPath(li)) { /* clang-format off */ e << "Target \"" << target->GetName() << "\" " << prop << " property contains relative path:\n" " \"" << li << "\""; /* clang-format on */ target->GetLocalGenerator()->IssueMessage(messageType, e.str()); } bool inBinary = isSubDirectory(li, topBinaryDir); bool inSource = isSubDirectory(li, topSourceDir); if (isSubDirectory(li, installDir)) { // The include directory is inside the install tree. If the // install tree is not inside the source tree or build tree then // fall through to the checks below that the include directory is not // also inside the source tree or build tree. bool shouldContinue = (!inBinary || isSubDirectory(installDir, topBinaryDir)) && (!inSource || isSubDirectory(installDir, topSourceDir)); if (prop == "INTERFACE_INCLUDE_DIRECTORIES") { if (!shouldContinue) { switch (target->GetPolicyStatusCMP0052()) { case cmPolicies::WARN: { std::ostringstream s; s << cmPolicies::GetPolicyWarning(cmPolicies::CMP0052) << "\n"; s << "Directory:\n \"" << li << "\"\nin " "INTERFACE_INCLUDE_DIRECTORIES of target \"" << target->GetName() << "\" is a subdirectory of the install " "directory:\n \"" << installDir << "\"\nhowever it is also " "a subdirectory of the " << (inBinary ? "build" : "source") << " tree:\n \"" << (inBinary ? topBinaryDir : topSourceDir) << "\"" << std::endl; target->GetLocalGenerator()->IssueMessage( MessageType::AUTHOR_WARNING, s.str()); CM_FALLTHROUGH; } case cmPolicies::OLD: shouldContinue = true; break; case cmPolicies::REQUIRED_ALWAYS: case cmPolicies::REQUIRED_IF_USED: case cmPolicies::NEW: break; } } } if (shouldContinue) { continue; } } if (inBinary) { /* clang-format off */ e << "Target \"" << target->GetName() << "\" " << prop << " property contains path:\n" " \"" << li << "\"\nwhich is prefixed in the build directory."; /* clang-format on */ target->GetLocalGenerator()->IssueMessage(messageType, e.str()); } if (!inSourceBuild) { if (inSource) { e << "Target \"" << target->GetName() << "\" " << prop << " property contains path:\n" " \"" << li << "\"\nwhich is prefixed in the source directory."; target->GetLocalGenerator()->IssueMessage(messageType, e.str()); } } } return !hadFatalError; } static void prefixItems(std::string& exportDirs) { std::vector<std::string> entries; cmGeneratorExpression::Split(exportDirs, entries); exportDirs.clear(); const char* sep = ""; for (std::string const& e : entries) { exportDirs += sep; sep = ";"; if (!cmSystemTools::FileIsFullPath(e) && e.find("${_IMPORT_PREFIX}") == std::string::npos) { exportDirs += "${_IMPORT_PREFIX}/"; } exportDirs += e; } } void cmExportFileGenerator::PopulateSourcesInterface( cmTargetExport* tei, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { cmGeneratorTarget* gt = tei->Target; assert(preprocessRule == cmGeneratorExpression::InstallInterface); const char* propName = "INTERFACE_SOURCES"; const char* input = gt->GetProperty(propName); if (!input) { return; } if (!*input) { properties[propName].clear(); return; } std::string prepro = cmGeneratorExpression::Preprocess(input, preprocessRule, true); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets); if (!checkInterfaceDirs(prepro, gt, propName)) { return; } properties[propName] = prepro; } } void cmExportFileGenerator::PopulateIncludeDirectoriesInterface( cmTargetExport* tei, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { cmGeneratorTarget* target = tei->Target; assert(preprocessRule == cmGeneratorExpression::InstallInterface); const char* propName = "INTERFACE_INCLUDE_DIRECTORIES"; const char* input = target->GetProperty(propName); cmGeneratorExpression ge; std::string dirs = cmGeneratorExpression::Preprocess( tei->InterfaceIncludeDirectories, preprocessRule, true); this->ReplaceInstallPrefix(dirs); std::unique_ptr<cmCompiledGeneratorExpression> cge = ge.Parse(dirs); std::string exportDirs = cge->Evaluate(target->GetLocalGenerator(), "", false, target); if (cge->GetHadContextSensitiveCondition()) { cmLocalGenerator* lg = target->GetLocalGenerator(); std::ostringstream e; e << "Target \"" << target->GetName() << "\" is installed with " "INCLUDES DESTINATION set to a context sensitive path. Paths which " "depend on the configuration, policy values or the link interface " "are " "not supported. Consider using target_include_directories instead."; lg->IssueMessage(MessageType::FATAL_ERROR, e.str()); return; } if (!input && exportDirs.empty()) { return; } if ((input && !*input) && exportDirs.empty()) { // Set to empty properties[propName].clear(); return; } prefixItems(exportDirs); std::string includes = (input ? input : ""); const char* sep = input ? ";" : ""; includes += sep + exportDirs; std::string prepro = cmGeneratorExpression::Preprocess(includes, preprocessRule, true); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets); if (!checkInterfaceDirs(prepro, target, propName)) { return; } properties[propName] = prepro; } } void cmExportFileGenerator::PopulateLinkDependsInterface( cmTargetExport* tei, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { cmGeneratorTarget* gt = tei->Target; assert(preprocessRule == cmGeneratorExpression::InstallInterface); const char* propName = "INTERFACE_LINK_DEPENDS"; const char* input = gt->GetProperty(propName); if (!input) { return; } if (!*input) { properties[propName].clear(); return; } std::string prepro = cmGeneratorExpression::Preprocess(input, preprocessRule, true); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets); if (!checkInterfaceDirs(prepro, gt, propName)) { return; } properties[propName] = prepro; } } void cmExportFileGenerator::PopulateLinkDirectoriesInterface( cmTargetExport* tei, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { cmGeneratorTarget* gt = tei->Target; assert(preprocessRule == cmGeneratorExpression::InstallInterface); const char* propName = "INTERFACE_LINK_DIRECTORIES"; const char* input = gt->GetProperty(propName); if (!input) { return; } if (!*input) { properties[propName].clear(); return; } std::string prepro = cmGeneratorExpression::Preprocess(input, preprocessRule, true); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions(prepro, gt, missingTargets); if (!checkInterfaceDirs(prepro, gt, propName)) { return; } properties[propName] = prepro; } } void cmExportFileGenerator::PopulateInterfaceProperty( const std::string& propName, cmGeneratorTarget* target, cmGeneratorExpression::PreprocessContext preprocessRule, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { this->PopulateInterfaceProperty(propName, propName, target, preprocessRule, properties, missingTargets); } void getPropertyContents(cmGeneratorTarget const* tgt, const std::string& prop, std::set<std::string>& ifaceProperties) { const char* p = tgt->GetProperty(prop); if (!p) { return; } std::vector<std::string> content; cmSystemTools::ExpandListArgument(p, content); ifaceProperties.insert(content.begin(), content.end()); } void getCompatibleInterfaceProperties(cmGeneratorTarget* target, std::set<std::string>& ifaceProperties, const std::string& config) { if (target->GetType() == cmStateEnums::OBJECT_LIBRARY) { // object libraries have no link information, so nothing to compute return; } cmComputeLinkInformation* info = target->GetLinkInformation(config); if (!info) { cmLocalGenerator* lg = target->GetLocalGenerator(); std::ostringstream e; e << "Exporting the target \"" << target->GetName() << "\" is not " "allowed since its linker language cannot be determined"; lg->IssueMessage(MessageType::FATAL_ERROR, e.str()); return; } const cmComputeLinkInformation::ItemVector& deps = info->GetItems(); for (auto const& dep : deps) { if (!dep.Target) { continue; } getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties); getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_STRING", ifaceProperties); getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MIN", ifaceProperties); getPropertyContents(dep.Target, "COMPATIBLE_INTERFACE_NUMBER_MAX", ifaceProperties); } } void cmExportFileGenerator::PopulateCompatibleInterfaceProperties( cmGeneratorTarget* gtarget, ImportPropertyMap& properties) { this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_BOOL", gtarget, properties); this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_STRING", gtarget, properties); this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MIN", gtarget, properties); this->PopulateInterfaceProperty("COMPATIBLE_INTERFACE_NUMBER_MAX", gtarget, properties); std::set<std::string> ifaceProperties; getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_BOOL", ifaceProperties); getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_STRING", ifaceProperties); getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MIN", ifaceProperties); getPropertyContents(gtarget, "COMPATIBLE_INTERFACE_NUMBER_MAX", ifaceProperties); if (gtarget->GetType() != cmStateEnums::INTERFACE_LIBRARY) { getCompatibleInterfaceProperties(gtarget, ifaceProperties, ""); std::vector<std::string> configNames; gtarget->Target->GetMakefile()->GetConfigurations(configNames); for (std::string const& cn : configNames) { getCompatibleInterfaceProperties(gtarget, ifaceProperties, cn); } } for (std::string const& ip : ifaceProperties) { this->PopulateInterfaceProperty("INTERFACE_" + ip, gtarget, properties); } } void cmExportFileGenerator::GenerateInterfaceProperties( const cmGeneratorTarget* target, std::ostream& os, const ImportPropertyMap& properties) { if (!properties.empty()) { std::string targetName = this->Namespace; targetName += target->GetExportName(); os << "set_target_properties(" << targetName << " PROPERTIES\n"; for (auto const& property : properties) { os << " " << property.first << " " << cmExportFileGeneratorEscape(property.second) << "\n"; } os << ")\n\n"; } } bool cmExportFileGenerator::AddTargetNamespace( std::string& input, cmGeneratorTarget* target, std::vector<std::string>& missingTargets) { cmGeneratorTarget::TargetOrString resolved = target->ResolveTargetReference(input); cmGeneratorTarget* tgt = resolved.Target; if (!tgt) { input = resolved.String; return false; } if (tgt->IsImported()) { input = tgt->GetName(); return true; } if (this->ExportedTargets.find(tgt) != this->ExportedTargets.end()) { input = this->Namespace + tgt->GetExportName(); } else { std::string namespacedTarget; this->HandleMissingTarget(namespacedTarget, missingTargets, target, tgt); if (!namespacedTarget.empty()) { input = namespacedTarget; } else { input = tgt->GetName(); } } return true; } void cmExportFileGenerator::ResolveTargetsInGeneratorExpressions( std::string& input, cmGeneratorTarget* target, std::vector<std::string>& missingTargets, FreeTargetsReplace replace) { if (replace == NoReplaceFreeTargets) { this->ResolveTargetsInGeneratorExpression(input, target, missingTargets); return; } std::vector<std::string> parts; cmGeneratorExpression::Split(input, parts); std::string sep; input.clear(); for (std::string& li : parts) { if (cmGeneratorExpression::Find(li) == std::string::npos) { this->AddTargetNamespace(li, target, missingTargets); } else { this->ResolveTargetsInGeneratorExpression(li, target, missingTargets); } input += sep + li; sep = ";"; } } void cmExportFileGenerator::ResolveTargetsInGeneratorExpression( std::string& input, cmGeneratorTarget* target, std::vector<std::string>& missingTargets) { std::string::size_type pos = 0; std::string::size_type lastPos = pos; while ((pos = input.find("$<TARGET_PROPERTY:", lastPos)) != std::string::npos) { std::string::size_type nameStartPos = pos + sizeof("$<TARGET_PROPERTY:") - 1; std::string::size_type closePos = input.find('>', nameStartPos); std::string::size_type commaPos = input.find(',', nameStartPos); std::string::size_type nextOpenPos = input.find("$<", nameStartPos); if (commaPos == std::string::npos // Implied 'this' target || closePos == std::string::npos // Incomplete expression. || closePos < commaPos // Implied 'this' target || nextOpenPos < commaPos) // Non-literal { lastPos = nameStartPos; continue; } std::string targetName = input.substr(nameStartPos, commaPos - nameStartPos); if (this->AddTargetNamespace(targetName, target, missingTargets)) { input.replace(nameStartPos, commaPos - nameStartPos, targetName); } lastPos = nameStartPos + targetName.size() + 1; } std::string errorString; pos = 0; lastPos = pos; while ((pos = input.find("$<TARGET_NAME:", lastPos)) != std::string::npos) { std::string::size_type nameStartPos = pos + sizeof("$<TARGET_NAME:") - 1; std::string::size_type endPos = input.find('>', nameStartPos); if (endPos == std::string::npos) { errorString = "$<TARGET_NAME:...> expression incomplete"; break; } std::string targetName = input.substr(nameStartPos, endPos - nameStartPos); if (targetName.find("$<") != std::string::npos) { errorString = "$<TARGET_NAME:...> requires its parameter to be a " "literal."; break; } if (!this->AddTargetNamespace(targetName, target, missingTargets)) { errorString = "$<TARGET_NAME:...> requires its parameter to be a " "reachable target."; break; } input.replace(pos, endPos - pos + 1, targetName); lastPos = endPos; } pos = 0; lastPos = pos; while (errorString.empty() && (pos = input.find("$<LINK_ONLY:", lastPos)) != std::string::npos) { std::string::size_type nameStartPos = pos + sizeof("$<LINK_ONLY:") - 1; std::string::size_type endPos = input.find('>', nameStartPos); if (endPos == std::string::npos) { errorString = "$<LINK_ONLY:...> expression incomplete"; break; } std::string libName = input.substr(nameStartPos, endPos - nameStartPos); if (cmGeneratorExpression::IsValidTargetName(libName) && this->AddTargetNamespace(libName, target, missingTargets)) { input.replace(nameStartPos, endPos - nameStartPos, libName); } lastPos = nameStartPos + libName.size() + 1; } this->ReplaceInstallPrefix(input); if (!errorString.empty()) { target->GetLocalGenerator()->IssueMessage(MessageType::FATAL_ERROR, errorString); } } void cmExportFileGenerator::ReplaceInstallPrefix(std::string& /*unused*/) { // Do nothing } void cmExportFileGenerator::SetImportLinkInterface( const std::string& config, std::string const& suffix, cmGeneratorExpression::PreprocessContext preprocessRule, cmGeneratorTarget* target, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { // Add the transitive link dependencies for this configuration. cmLinkInterface const* iface = target->GetLinkInterface(config, target); if (!iface) { return; } if (iface->ImplementationIsInterface) { // Policy CMP0022 must not be NEW. this->SetImportLinkProperty(suffix, target, "IMPORTED_LINK_INTERFACE_LIBRARIES", iface->Libraries, properties, missingTargets); return; } const char* propContent; if (const char* prop_suffixed = target->GetProperty("LINK_INTERFACE_LIBRARIES" + suffix)) { propContent = prop_suffixed; } else if (const char* prop = target->GetProperty("LINK_INTERFACE_LIBRARIES")) { propContent = prop; } else { return; } const bool newCMP0022Behavior = target->GetPolicyStatusCMP0022() != cmPolicies::WARN && target->GetPolicyStatusCMP0022() != cmPolicies::OLD; if (newCMP0022Behavior && !this->ExportOld) { cmLocalGenerator* lg = target->GetLocalGenerator(); std::ostringstream e; e << "Target \"" << target->GetName() << "\" has policy CMP0022 enabled, " "but also has old-style LINK_INTERFACE_LIBRARIES properties " "populated, but it was exported without the " "EXPORT_LINK_INTERFACE_LIBRARIES to export the old-style properties"; lg->IssueMessage(MessageType::FATAL_ERROR, e.str()); return; } if (!*propContent) { properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix].clear(); return; } std::string prepro = cmGeneratorExpression::Preprocess(propContent, preprocessRule); if (!prepro.empty()) { this->ResolveTargetsInGeneratorExpressions(prepro, target, missingTargets, ReplaceFreeTargets); properties["IMPORTED_LINK_INTERFACE_LIBRARIES" + suffix] = prepro; } } void cmExportFileGenerator::SetImportDetailProperties( const std::string& config, std::string const& suffix, cmGeneratorTarget* target, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { // Get the makefile in which to lookup target information. cmMakefile* mf = target->Makefile; // Add the soname for unix shared libraries. if (target->GetType() == cmStateEnums::SHARED_LIBRARY || target->GetType() == cmStateEnums::MODULE_LIBRARY) { if (!target->IsDLLPlatform()) { std::string prop; std::string value; if (target->HasSOName(config)) { if (mf->IsOn("CMAKE_PLATFORM_HAS_INSTALLNAME")) { value = this->InstallNameDir(target, config); } prop = "IMPORTED_SONAME"; value += target->GetSOName(config); } else { prop = "IMPORTED_NO_SONAME"; value = "TRUE"; } prop += suffix; properties[prop] = value; } } // Add the transitive link dependencies for this configuration. if (cmLinkInterface const* iface = target->GetLinkInterface(config, target)) { this->SetImportLinkProperty(suffix, target, "IMPORTED_LINK_INTERFACE_LANGUAGES", iface->Languages, properties, missingTargets); std::vector<std::string> dummy; this->SetImportLinkProperty(suffix, target, "IMPORTED_LINK_DEPENDENT_LIBRARIES", iface->SharedDeps, properties, dummy); if (iface->Multiplicity > 0) { std::string prop = "IMPORTED_LINK_INTERFACE_MULTIPLICITY"; prop += suffix; std::ostringstream m; m << iface->Multiplicity; properties[prop] = m.str(); } } // Add information if this target is a managed target if (target->GetManagedType(config) != cmGeneratorTarget::ManagedType::Native) { std::string prop = "IMPORTED_COMMON_LANGUAGE_RUNTIME"; prop += suffix; std::string propval; if (auto* p = target->GetProperty("COMMON_LANGUAGE_RUNTIME")) { propval = p; } else if (target->IsCSharpOnly()) { // C# projects do not have the /clr flag, so we set the property // here to mark the target as (only) managed (i.e. no .lib file // to link to). Otherwise the COMMON_LANGUAGE_RUNTIME target // property would have to be set manually for C# targets to make // exporting/importing work. propval = "CSharp"; } properties[prop] = propval; } } static std::string const& asString(std::string const& l) { return l; } static std::string const& asString(cmLinkItem const& l) { return l.AsStr(); } template <typename T> void cmExportFileGenerator::SetImportLinkProperty( std::string const& suffix, cmGeneratorTarget* target, const std::string& propName, std::vector<T> const& entries, ImportPropertyMap& properties, std::vector<std::string>& missingTargets) { // Skip the property if there are no entries. if (entries.empty()) { return; } // Construct the property value. std::string link_entries; const char* sep = ""; for (T const& l : entries) { // Separate this from the previous entry. link_entries += sep; sep = ";"; std::string temp = asString(l); this->AddTargetNamespace(temp, target, missingTargets); link_entries += temp; } // Store the property. std::string prop = propName; prop += suffix; properties[prop] = link_entries; } void cmExportFileGenerator::GeneratePolicyHeaderCode(std::ostream& os) { // Protect that file against use with older CMake versions. /* clang-format off */ os << "# Generated by CMake\n\n"; os << "if(\"${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}\" LESS 2.5)\n" << " message(FATAL_ERROR \"CMake >= 2.6.0 required\")\n" << "endif()\n"; /* clang-format on */ // Isolate the file policy level. // We use 2.6 here instead of the current version because newer // versions of CMake should be able to export files imported by 2.6 // until the import format changes. /* clang-format off */ os << "cmake_policy(PUSH)\n" << "cmake_policy(VERSION 2.6)\n"; /* clang-format on */ } void cmExportFileGenerator::GeneratePolicyFooterCode(std::ostream& os) { os << "cmake_policy(POP)\n"; } void cmExportFileGenerator::GenerateImportHeaderCode(std::ostream& os, const std::string& config) { os << "#----------------------------------------------------------------\n" << "# Generated CMake target import file"; if (!config.empty()) { os << " for configuration \"" << config << "\".\n"; } else { os << ".\n"; } os << "#----------------------------------------------------------------\n" << "\n"; this->GenerateImportVersionCode(os); } void cmExportFileGenerator::GenerateImportFooterCode(std::ostream& os) { os << "# Commands beyond this point should not need to know the version.\n" << "set(CMAKE_IMPORT_FILE_VERSION)\n"; } void cmExportFileGenerator::GenerateImportVersionCode(std::ostream& os) { // Store an import file format version. This will let us change the // format later while still allowing old import files to work. /* clang-format off */ os << "# Commands may need to know the format version.\n" << "set(CMAKE_IMPORT_FILE_VERSION 1)\n" << "\n"; /* clang-format on */ } void cmExportFileGenerator::GenerateExpectedTargetsCode( std::ostream& os, const std::string& expectedTargets) { /* clang-format off */ os << "# Protect against multiple inclusion, which would fail when already " "imported targets are added once more.\n" "set(_targetsDefined)\n" "set(_targetsNotDefined)\n" "set(_expectedTargets)\n" "foreach(_expectedTarget " << expectedTargets << ")\n" " list(APPEND _expectedTargets ${_expectedTarget})\n" " if(NOT TARGET ${_expectedTarget})\n" " list(APPEND _targetsNotDefined ${_expectedTarget})\n" " endif()\n" " if(TARGET ${_expectedTarget})\n" " list(APPEND _targetsDefined ${_expectedTarget})\n" " endif()\n" "endforeach()\n" "if(\"${_targetsDefined}\" STREQUAL \"${_expectedTargets}\")\n" " unset(_targetsDefined)\n" " unset(_targetsNotDefined)\n" " unset(_expectedTargets)\n" " set(CMAKE_IMPORT_FILE_VERSION)\n" " cmake_policy(POP)\n" " return()\n" "endif()\n" "if(NOT \"${_targetsDefined}\" STREQUAL \"\")\n" " message(FATAL_ERROR \"Some (but not all) targets in this export " "set were already defined.\\nTargets Defined: ${_targetsDefined}\\n" "Targets not yet defined: ${_targetsNotDefined}\\n\")\n" "endif()\n" "unset(_targetsDefined)\n" "unset(_targetsNotDefined)\n" "unset(_expectedTargets)\n" "\n\n"; /* clang-format on */ } void cmExportFileGenerator::GenerateImportTargetCode( std::ostream& os, cmGeneratorTarget const* target, cmStateEnums::TargetType targetType) { // Construct the imported target name. std::string targetName = this->Namespace; targetName += target->GetExportName(); // Create the imported target. os << "# Create imported target " << targetName << "\n"; switch (targetType) { case cmStateEnums::EXECUTABLE: os << "add_executable(" << targetName << " IMPORTED)\n"; break; case cmStateEnums::STATIC_LIBRARY: os << "add_library(" << targetName << " STATIC IMPORTED)\n"; break; case cmStateEnums::SHARED_LIBRARY: os << "add_library(" << targetName << " SHARED IMPORTED)\n"; break; case cmStateEnums::MODULE_LIBRARY: os << "add_library(" << targetName << " MODULE IMPORTED)\n"; break; case cmStateEnums::UNKNOWN_LIBRARY: os << "add_library(" << targetName << " UNKNOWN IMPORTED)\n"; break; case cmStateEnums::OBJECT_LIBRARY: os << "add_library(" << targetName << " OBJECT IMPORTED)\n"; break; case cmStateEnums::INTERFACE_LIBRARY: os << "add_library(" << targetName << " INTERFACE IMPORTED)\n"; break; default: // should never happen break; } // Mark the imported executable if it has exports. if (target->IsExecutableWithExports()) { os << "set_property(TARGET " << targetName << " PROPERTY ENABLE_EXPORTS 1)\n"; } // Mark the imported library if it is a framework. if (target->IsFrameworkOnApple()) { os << "set_property(TARGET " << targetName << " PROPERTY FRAMEWORK 1)\n"; } // Mark the imported executable if it is an application bundle. if (target->IsAppBundleOnApple()) { os << "set_property(TARGET " << targetName << " PROPERTY MACOSX_BUNDLE 1)\n"; } if (target->IsCFBundleOnApple()) { os << "set_property(TARGET " << targetName << " PROPERTY BUNDLE 1)\n"; } os << "\n"; } void cmExportFileGenerator::GenerateImportPropertyCode( std::ostream& os, const std::string& config, cmGeneratorTarget const* target, ImportPropertyMap const& properties) { // Construct the imported target name. std::string targetName = this->Namespace; targetName += target->GetExportName(); // Set the import properties. os << "# Import target \"" << targetName << "\" for configuration \"" << config << "\"\n"; os << "set_property(TARGET " << targetName << " APPEND PROPERTY IMPORTED_CONFIGURATIONS "; if (!config.empty()) { os << cmSystemTools::UpperCase(config); } else { os << "NOCONFIG"; } os << ")\n"; os << "set_target_properties(" << targetName << " PROPERTIES\n"; for (auto const& property : properties) { os << " " << property.first << " " << cmExportFileGeneratorEscape(property.second) << "\n"; } os << " )\n" << "\n"; } void cmExportFileGenerator::GenerateMissingTargetsCheckCode( std::ostream& os, const std::vector<std::string>& missingTargets) { if (missingTargets.empty()) { /* clang-format off */ os << "# This file does not depend on other imported targets which have\n" "# been exported from the same project but in a separate " "export set.\n\n"; /* clang-format on */ return; } /* clang-format off */ os << "# Make sure the targets which have been exported in some other \n" "# export set exist.\n" "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n" "foreach(_target "; /* clang-format on */ std::set<std::string> emitted; for (std::string const& missingTarget : missingTargets) { if (emitted.insert(missingTarget).second) { os << "\"" << missingTarget << "\" "; } } /* clang-format off */ os << ")\n" " if(NOT TARGET \"${_target}\" )\n" " set(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets \"" "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets} ${_target}\")" "\n" " endif()\n" "endforeach()\n" "\n" "if(DEFINED ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n" " if(CMAKE_FIND_PACKAGE_NAME)\n" " set( ${CMAKE_FIND_PACKAGE_NAME}_FOUND FALSE)\n" " set( ${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE " "\"The following imported targets are " "referenced, but are missing: " "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n" " else()\n" " message(FATAL_ERROR \"The following imported targets are " "referenced, but are missing: " "${${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets}\")\n" " endif()\n" "endif()\n" "unset(${CMAKE_FIND_PACKAGE_NAME}_NOT_FOUND_MESSAGE_targets)\n" "\n"; /* clang-format on */ } void cmExportFileGenerator::GenerateImportedFileCheckLoop(std::ostream& os) { // Add code which verifies at cmake time that the file which is being // imported actually exists on disk. This should in theory always be theory // case, but still when packages are split into normal and development // packages this might get broken (e.g. the Config.cmake could be part of // the non-development package, something similar happened to me without // on SUSE with a mysql pkg-config file, which claimed everything is fine, // but the development package was not installed.). /* clang-format off */ os << "# Loop over all imported files and verify that they actually exist\n" "foreach(target ${_IMPORT_CHECK_TARGETS} )\n" " foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )\n" " if(NOT EXISTS \"${file}\" )\n" " message(FATAL_ERROR \"The imported target \\\"${target}\\\"" " references the file\n" " \\\"${file}\\\"\n" "but this file does not exist. Possible reasons include:\n" "* The file was deleted, renamed, or moved to another location.\n" "* An install or uninstall procedure did not complete successfully.\n" "* The installation package was faulty and contained\n" " \\\"${CMAKE_CURRENT_LIST_FILE}\\\"\n" "but not all the files it references.\n" "\")\n" " endif()\n" " endforeach()\n" " unset(_IMPORT_CHECK_FILES_FOR_${target})\n" "endforeach()\n" "unset(_IMPORT_CHECK_TARGETS)\n" "\n"; /* clang-format on */ } void cmExportFileGenerator::GenerateImportedFileChecksCode( std::ostream& os, cmGeneratorTarget* target, ImportPropertyMap const& properties, const std::set<std::string>& importedLocations) { // Construct the imported target name. std::string targetName = this->Namespace; targetName += target->GetExportName(); os << "list(APPEND _IMPORT_CHECK_TARGETS " << targetName << " )\n" "list(APPEND _IMPORT_CHECK_FILES_FOR_" << targetName << " "; for (std::string const& li : importedLocations) { ImportPropertyMap::const_iterator pi = properties.find(li); if (pi != properties.end()) { os << cmExportFileGeneratorEscape(pi->second) << " "; } } os << ")\n\n"; } bool cmExportFileGenerator::PopulateExportProperties( cmGeneratorTarget* gte, ImportPropertyMap& properties, std::string& errorMessage) { auto& targetProperties = gte->Target->GetProperties(); const auto& exportProperties = targetProperties.find("EXPORT_PROPERTIES"); if (exportProperties != targetProperties.end()) { std::vector<std::string> propsToExport; cmSystemTools::ExpandListArgument(exportProperties->second.GetValue(), propsToExport); for (auto& prop : propsToExport) { /* Black list reserved properties */ if (cmSystemTools::StringStartsWith(prop, "IMPORTED_") || cmSystemTools::StringStartsWith(prop, "INTERFACE_")) { std::ostringstream e; e << "Target \"" << gte->Target->GetName() << "\" contains property \"" << prop << "\" in EXPORT_PROPERTIES but IMPORTED_* and INTERFACE_* " << "properties are reserved."; errorMessage = e.str(); return false; } auto propertyValue = targetProperties.GetPropertyValue(prop); if (propertyValue == nullptr) { // Asked to export a property that isn't defined on the target. Do not // consider this an error, there's just nothing to export. continue; } std::string evaluatedValue = cmGeneratorExpression::Preprocess( propertyValue, cmGeneratorExpression::StripAllGeneratorExpressions); if (evaluatedValue != propertyValue) { std::ostringstream e; e << "Target \"" << gte->Target->GetName() << "\" contains property \"" << prop << "\" in EXPORT_PROPERTIES but this property contains a " << "generator expression. This is not allowed."; errorMessage = e.str(); return false; } properties[prop] = propertyValue; } } return true; }