aboutsummaryrefslogtreecommitdiffstats
path: root/src/tools/examplesscanner/helpextractor.cpp
blob: 3ce1b8d88438afed43c29f28e33a9e1f9e868415 (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
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** 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.
**
** 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, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/

#include "helpextractor.h"

#include <QtWidgets>
#include <QDebug>

HelpExtractor::HelpExtractor()
{
    initHelpEngine();
}

void HelpExtractor::initHelpEngine()
{
    helpRootUrl = QString("qthelp://com.trolltech.qt/qdoc/");
    //        .arg(QT_VERSION >> 16).arg((QT_VERSION >> 8) & 0xFF)
    //        .arg(QT_VERSION & 0xFF);

    // Store help collection file in cache dir of assistant
    QString cacheDir = QDesktopServices::storageLocation(QDesktopServices::DataLocation)
            + QLatin1String("/Trolltech/Assistant/");
    QString helpDataFile = QString(QLatin1String("qtdemo_%1.qhc")).arg(QLatin1String(QT_VERSION_STR));

    QDir dir;
    if (!dir.exists(cacheDir))
        dir.mkpath(cacheDir);

    // Create help engine (and new
    // helpDataFile if it does not exist):
    helpEngine = new QHelpEngineCore(cacheDir + helpDataFile);
    helpEngine->setupData();

    QString qtDocRoot = QLibraryInfo::location(QLibraryInfo::DocumentationPath) + QLatin1String("/qch");
    qtDocRoot = QDir(qtDocRoot).absolutePath();

    QStringList qchFiles;
    qchFiles << QLatin1String("/qt.qch")
             << QLatin1String("/designer.qch")
             << QLatin1String("/linguist.qch");

    QString oldDir = helpEngine->customValue(QLatin1String("docDir"), QString()).toString();
    if (oldDir != qtDocRoot) {
        foreach (const QString &qchFile, qchFiles)
            helpEngine->unregisterDocumentation(QHelpEngineCore::namespaceName(qtDocRoot + qchFile));
    }

    // If the data that the engine will work
    // on is not yet registered, do it now:
    foreach (const QString &qchFile, qchFiles)
        helpEngine->registerDocumentation(qtDocRoot + qchFile);

    helpEngine->setCustomValue(QLatin1String("docDir"), qtDocRoot);
}

void HelpExtractor::readXmlDocument()
{
    contentsDoc = new QDomDocument();
    QString errorStr;
    int errorLine;
    int errorColumn;

    QString qtDemoPath = QLibraryInfo::location(QLibraryInfo::DemosPath) + QLatin1String("/qtdemo");
    QFile file(qtDemoPath + "/xml/examples.xml");
    bool statusOK = contentsDoc->setContent(&file, true, &errorStr, &errorLine, &errorColumn);
    if (!statusOK) {
        qDebug() << QString::fromLatin1("DOM Parser: Could not read or find the contents document. Error at line %1, column %2:\n%3")
                    .arg(errorLine).arg(errorColumn).arg(errorStr);
        exit(-1);
    }
    //convertToSql(contentsDoc->documentElement());
    convertToAggregatableXml(contentsDoc->documentElement());
}


void HelpExtractor::convertToAggregatableXml(const QDomElement &documentElement)
{
    QDomDocument outDocument;
    QDomElement root = outDocument.createElement("instructionals");
    QDomElement demos = outDocument.createElement("demos");
    QDomElement examples = outDocument.createElement("examples");
    QDomElement tutorials = outDocument.createElement("tutorials");
    root.setAttribute("module", "Qt");
    root.appendChild(demos);
    root.appendChild(examples);
    root.appendChild(tutorials);
    outDocument.appendChild(root);

    QDomNode currentNode = documentElement.firstChild();
    QDomElement step, steps, instructional;
    int id = 0;
    while (!currentNode.isNull()){
        //qDebug() << '\t' << label;
        QDomNode sub = currentNode.firstChild();
        while (!sub.isNull()) {
            QDomElement element = sub.toElement();
            readInfoAboutExample(element);
            QString exampleName = element.attribute("name");
            StringHash exampleInfo = info[exampleName];

            // type = category - last char
            QString category = exampleInfo["category"];
            QString categoryName = sub.parentNode().toElement().attribute("name");
            QString type = category;
            type.chop(1);

            QString dirName = exampleInfo["dirname"];

            if (category != "tutorial" || (category == "tutorial" && category != lastCategory)) {
                instructional = outDocument.createElement(type);
                if (category == "tutorial" && category != lastCategory)
                    instructional.setAttribute("name", categoryName);
                else
                    instructional.setAttribute("name", exampleName);
            }

            QString projectPath = dirName + '/' + exampleInfo["filename"] + '/' + exampleInfo["filename"];

            bool qml = (exampleInfo["qml"] == "true");
            if (qml)
                projectPath += ".qmlproject";
            else
                projectPath += ".pro";


            if (category == "tutorials")
            {
                if (category != lastCategory) {
                    steps = outDocument.createElement("steps");
                    instructional.appendChild(steps);
                }

                step = outDocument.createElement("step");
                step.setAttribute("projectPath", projectPath);
                step.setAttribute("imageUrl", getImageUrl(exampleName));
                step.setAttribute("docUrl", resolveDocUrl(exampleName));
                steps.appendChild(step);
            }

            instructional.setAttribute("projectPath", projectPath);
            instructional.setAttribute("imageUrl", getImageUrl(exampleName));
            instructional.setAttribute("docUrl", resolveDocUrl(exampleName));
            instructional.setAttribute("difficulty", "?");
            QDomElement description = outDocument.createElement("description");
            QString descriptionText = loadDescription(exampleName);
            description.appendChild(outDocument.createCDATASection(descriptionText));
            QDomElement tags = outDocument.createElement("tags");
            // TODO
            QStringList tagList;
            tagList << type << exampleInfo["filename"].split('/');
            if (dirName != ".")
                tagList << dirName.split('/');
            if (qml)
                tagList << "qml" << "qt quick";
            QRegExp ttText("<tt>(.*)</tt>");
            ttText.setMinimal(true); // non-greedy
            int index = 0;
            QStringList keywords;
            while ((index = ttText.indexIn(descriptionText, index)) != -1) {
                keywords << descriptionText.mid(index+4, ttText.matchedLength()-9);
                index = index + ttText.matchedLength();
            }

            // Blacklist Checking...
            QStringList blackList;
            blackList << "license" << "trafikanten";
            foreach (const QString& keyword, keywords)
                if (!keyword.isEmpty())  {
                    bool skip = false;
                    foreach (const QString& blackListItem, blackList)
                        if (keyword.contains(blackListItem, Qt::CaseInsensitive)) {
                            skip = true;
                            break;
                        }
                    if (!skip)
                        tagList << keyword.simplified().toLower();
                }

            tags.appendChild(outDocument.createTextNode(tagList.join(",")));
            instructional.appendChild(description);
            instructional.appendChild(tags);

            if (category != "tutorials") {
                if (category == "demos")
                    demos.appendChild(instructional);
                else
                    examples.appendChild(instructional);
            } else if (lastCategory != "tutorials")
                tutorials.appendChild(instructional);

            id++;
            sub = sub.nextSibling();
            lastCategory = category;

        }
        currentNode = currentNode.nextSibling();
    }


    QFile outFile("../../../share/qtcreator/welcomescreen/examples_fallback.xml");

    QByteArray xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
    xml += outDocument.toByteArray();
    if (!outFile.open(QIODevice::WriteOnly))
        return;
    outFile.write(xml);
    //qDebug() << xml;
    outFile.close();

}

QString HelpExtractor::loadDescription(const QString &name)
{
    QByteArray ba = getHtml(name);
    QString errorMsg;
    int errorLine, errorColumn;

    QDomDocument exampleDoc;
    if (ba.isEmpty()) {
        qDebug() << "No documentation found for" << name << "Is the documentation built?";
    } else if (!exampleDoc.setContent(ba, false, &errorMsg, &errorLine, &errorColumn)) {
        qDebug() << "Error loading documentation for " << name << ": " << errorMsg << errorLine << errorColumn;
    }

    QDomNodeList paragraphs = exampleDoc.elementsByTagName("p");
    if (paragraphs.length() < 1)
        qDebug() << "- ExampleContent::loadDescription(): Could not load description:"
                 << info[name]["docfile"];
    QString description = QLatin1String("");
    for (int p = 0; p < int(paragraphs.length()); ++p) {
        description = extractTextFromParagraph(paragraphs.item(p));
        if (isSummaryOf(description, name)) {
            break;
        }
    }
    return description;
}

void HelpExtractor::readInfoAboutExample(const QDomElement &example)
{
    QString name = example.attribute("name");
    if (info.contains(name))
        qWarning() << "__WARNING: HelpExtractor::readInfoAboutExample: Demo/example with name"
                   << name << "appears twice in the xml-file!__";

    info[name]["filename"] = example.attribute("filename");
    QString dirName = example.parentNode().toElement().attribute("dirname");
    info[name]["dirname"] =  dirName;
    QString category;
    if (dirName.startsWith("tutorials"))
        category = "tutorials";
    else
        category = example.parentNode().toElement().tagName();

    if (category == "category")
        category = "examples";

    info[name]["category"] = category;
    info[name]["changedirectory"] = example.attribute("changedirectory");
    info[name]["image"] = example.attribute("image");
    info[name]["qml"] = example.attribute("qml");
}

QString HelpExtractor::resolveDocUrl(const QString &name)
{
    QString dirName = info[name]["dirname"];
    QString category = info[name]["category"];
    QString fileName = info[name]["filename"];

    if (category == "demos")
        return helpRootUrl + "demos-" + fileName.replace(QLatin1Char('/'), QLatin1Char('-')) + ".html";
    else
        return helpRootUrl + dirName.replace(QLatin1Char('/'), QLatin1Char('-')) + QLatin1Char('-') + fileName + ".html";
}


QString HelpExtractor::resolveImageUrl(const QString &name)
{
    return helpRootUrl + "images/" + name;
}

QByteArray HelpExtractor::getResource(const QString &name)
{
    return helpEngine->fileData(name);
}

QByteArray HelpExtractor::getHtml(const QString &name)
{
    return getResource(resolveDocUrl(name));
}

QByteArray HelpExtractor::getImage(const QString &name)
{
    QString imageName = this->info[name]["image"];
    QString category = this->info[name]["category"];
    QString fileName = this->info[name]["filename"];
    bool qml = (this->info[name]["qml"] == QLatin1String("true"));
    if (qml)
        fileName = QLatin1String("qml-") + fileName.split('/').last();

    if (imageName.isEmpty()){
        if (category == "demos")
            imageName = fileName + "-demo.png";
        else
            imageName = fileName + "-example.png";
        if ((getResource(resolveImageUrl(imageName))).isEmpty())
            imageName = fileName + ".png";
        if ((getResource(resolveImageUrl(imageName))).isEmpty())
            imageName = fileName + "example.png";
    }
    return getResource(resolveImageUrl(imageName));
}

QString HelpExtractor::getImageUrl(const QString &name)
{
    QString imageName = this->info[name]["image"];
    QString category = this->info[name]["category"];
    QString fileName = this->info[name]["filename"];
    bool qml = (this->info[name]["qml"] == QLatin1String("true"));
    if (qml)
        fileName = QLatin1String("qml-") + fileName.split('/').last();

    if (imageName.isEmpty()){
        if (category == "demos")
            imageName = fileName + "-demo.png";
        else
            imageName = fileName + "-example.png";
        if ((getResource(resolveImageUrl(imageName))).isEmpty())
            imageName = fileName + ".png";
        if ((getResource(resolveImageUrl(imageName))).isEmpty())
            imageName = fileName + "example.png";
        if ((getResource(resolveImageUrl(imageName))).isEmpty())
            return "";
    }
    return resolveImageUrl(imageName);
}

QString HelpExtractor::extractTextFromParagraph(const QDomNode &parentNode)
{
    QString description;
    QDomNode node = parentNode.firstChild();

    while (!node.isNull()) {
        QString beginTag;
        QString endTag;
        if (node.isText())
            description += node.nodeValue();
        else if (node.hasChildNodes()) {
            if (node.nodeName() == "b") {
                beginTag = "<b>";
                endTag = "</b>";
            } else if (node.nodeName() == "a") {
                beginTag = "<tt>";
                endTag = "</tt>";
            } else if (node.nodeName() == "i") {
                beginTag = "<i>";
                endTag = "</i>";
            } else if (node.nodeName() == "tt") {
                beginTag = "<tt>";
                endTag = "</tt>";
            }
            description += beginTag + extractTextFromParagraph(node) + endTag;
        }
        node = node.nextSibling();
    }

    return description;
}

bool HelpExtractor::isSummaryOf(const QString &text, const QString &example)
{
    return (!text.contains("[") &&
            text.indexOf(QRegExp(QString("(In )?((The|This) )?(%1 )?.*(tutorial|example|demo|application)").arg(example),
                                 Qt::CaseInsensitive)) != -1);
}