File: templatesmodel.cpp

package info (click to toggle)
kdevelop 4%3A5.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 57,892 kB
  • sloc: cpp: 278,773; javascript: 3,558; python: 3,385; sh: 1,317; ansic: 689; xml: 273; php: 95; makefile: 40; lisp: 13; sed: 12
file content (411 lines) | stat: -rw-r--r-- 15,236 bytes parent folder | download
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
/*  This file is part of KDevelop
    Copyright 2007 Alexander Dymo <adymo@kdevelop.org>
    Copyright 2012 Miha Čančula <miha@noughmad.eu>

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public License
    along with this library; see the file COPYING.LIB.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
 */

#include "templatesmodel.h"

#include "templatepreviewicon.h"
#include <debug.h>
#include <interfaces/icore.h>

#include <KConfig>
#include <KTar>
#include <KZip>
#include <KConfigGroup>
#include <KLocalizedString>

#include <QMimeType>
#include <QMimeDatabase>
#include <QFileInfo>
#include <QDir>
#include <QStandardPaths>
#include <QTemporaryDir>

using namespace KDevelop;

class KDevelop::TemplatesModelPrivate
{
public:
    explicit TemplatesModelPrivate(const QString& typePrefix);

    QString typePrefix;

    QStringList searchPaths;

    QMap<QString, QStandardItem*> templateItems;

    /**
     * Extracts description files from all available template archives and saves them to a location
     * determined by descriptionResourceSuffix().
     **/
    void extractTemplateDescriptions();

    /**
     * Creates a model item for the template @p name in category @p category
     *
     * @param name the name of the new template
     * @param category the category of the new template
     * @param parent the parent item
     * @return the created item
     **/
    QStandardItem* createItem(const QString& name, const QString& category, QStandardItem* parent);

    enum ResourceType
    {
        Description,
        Template,
        Preview
    };
    QString resourceFilter(ResourceType type, const QString& suffix = QString()) const
    {
        QString filter = typePrefix;
        switch (type) {
        case Description:
            filter += QLatin1String("template_descriptions/");
            break;
        case Template:
            filter += QLatin1String("templates/");
            break;
        case Preview:
            filter += QLatin1String("template_previews/");
            break;
        }
        return filter + suffix;
    }
};

TemplatesModelPrivate::TemplatesModelPrivate(const QString& _typePrefix)
    : typePrefix(_typePrefix)
{
    if (!typePrefix.endsWith(QLatin1Char('/'))) {
        typePrefix.append(QLatin1Char('/'));
    }
}

TemplatesModel::TemplatesModel(const QString& typePrefix, QObject* parent)
    : QStandardItemModel(parent)
    , d_ptr(new TemplatesModelPrivate(typePrefix))
{
}

TemplatesModel::~TemplatesModel() = default;

void TemplatesModel::refresh()
{
    Q_D(TemplatesModel);

    clear();
    d->templateItems.clear();
    d->templateItems[QString()] = invisibleRootItem();
    d->extractTemplateDescriptions();

    QStringList templateArchives;
    for (const QString& archivePath : qAsConst(d->searchPaths)) {
        const QStringList files = QDir(archivePath).entryList(QDir::Files);
        for (const QString& file : files) {
            templateArchives.append(archivePath + file);
        }
    }

    QStringList templateDescriptions;
    const QStringList templatePaths =
    {QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') + d->resourceFilter(
         TemplatesModelPrivate::Description)};
    for (const QString& templateDescription : templatePaths) {
        const QStringList files = QDir(templateDescription).entryList(QDir::Files);
        for (const QString& file : files) {
            templateDescriptions.append(templateDescription + file);
        }
    }

    for (const QString& templateDescription : qAsConst(templateDescriptions)) {
        QFileInfo fi(templateDescription);
        bool archiveFound = false;
        for (const QString& templateArchive : qAsConst(templateArchives)) {
            if (QFileInfo(templateArchive).baseName() == fi.baseName()) {
                archiveFound = true;

                KConfig templateConfig(templateDescription);
                KConfigGroup general(&templateConfig, "General");
                QString name = general.readEntry("Name");
                QString category = general.readEntry("Category");
                QString comment = general.readEntry("Comment");
                TemplatePreviewIcon icon(general.readEntry("Icon"), templateArchive, d->resourceFilter(
                        TemplatesModelPrivate::Preview));

                QStandardItem* templateItem = d->createItem(name, category, invisibleRootItem());
                templateItem->setData(templateDescription, DescriptionFileRole);
                templateItem->setData(templateArchive, ArchiveFileRole);
                templateItem->setData(comment, CommentRole);
                templateItem->setData(QVariant::fromValue<TemplatePreviewIcon>(icon), PreviewIconRole);
            }
        }

        if (!archiveFound) {
            // Template file doesn't exist anymore, so remove the description
            // saves us the extra lookups for templateExists on the next run
            QFile(templateDescription).remove();
        }
    }
}

QStandardItem* TemplatesModelPrivate::createItem(const QString& name, const QString& category, QStandardItem* parent)
{
    const QStringList path = category.split(QLatin1Char('/'));

    QStringList currentPath;
    currentPath.reserve(path.size());
    for (const QString& entry : path) {
        currentPath << entry;
        if (!templateItems.contains(currentPath.join(QLatin1Char('/')))) {
            auto* item = new QStandardItem(entry);
            item->setEditable(false);
            parent->appendRow(item);
            templateItems[currentPath.join(QLatin1Char('/'))] = item;
            parent = item;
        } else {
            parent = templateItems[currentPath.join(QLatin1Char('/'))];
        }
    }

    auto* templateItem = new QStandardItem(name);
    templateItem->setEditable(false);
    parent->appendRow(templateItem);
    return templateItem;
}

void TemplatesModelPrivate::extractTemplateDescriptions()
{
    QStringList templateArchives;
    searchPaths << QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, resourceFilter(
                                                 Template), QStandardPaths::LocateDirectory);
    searchPaths.removeDuplicates();
    for (const QString& archivePath : qAsConst(searchPaths)) {
        const QStringList files = QDir(archivePath).entryList(QDir::Files);
        for (const QString& file : files) {
            if (file.endsWith(QLatin1String(".zip")) || file.endsWith(QLatin1String(".tar.bz2"))) {
                QString archfile = archivePath + file;
                templateArchives.append(archfile);
            }
        }
    }

    QString localDescriptionsDir = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char(
        '/') + resourceFilter(Description);

    QDir dir(localDescriptionsDir);
    if (!dir.exists())
        dir.mkpath(QStringLiteral("."));

    for (const QString& archName : qAsConst(templateArchives)) {
        qCDebug(LANGUAGE) << "processing template" << archName;

        QScopedPointer<KArchive> templateArchive;
        if (QFileInfo(archName).completeSuffix() == QLatin1String("zip")) {
            templateArchive.reset(new KZip(archName));
        } else
        {
            templateArchive.reset(new KTar(archName));
        }

        if (templateArchive->open(QIODevice::ReadOnly)) {
            /*
             * This class looks for template description files in the following order
             *
             * - "basename.kdevtemplate"
             * - "*.kdevtemplate"
             * - "basename.desktop"
             * - "*.desktop"
             *
             * This is done because application templates can contain .desktop files used by the application
             * so the kdevtemplate suffix must have priority.
             */
            QFileInfo templateInfo(archName);
            QString suffix = QStringLiteral(".kdevtemplate");
            const KArchiveEntry* templateEntry =
                templateArchive->directory()->entry(templateInfo.baseName() + suffix);

            if (!templateEntry || !templateEntry->isFile()) {
                /*
                 * First, if the .kdevtemplate file is not found by name,
                 * we check all the files in the archive for any .kdevtemplate file
                 *
                 * This is needed because kde-files.org renames downloaded files
                 */
                const auto dirEntries = templateArchive->directory()->entries();
                for (const QString& entryName : dirEntries) {
                    if (entryName.endsWith(suffix)) {
                        templateEntry = templateArchive->directory()->entry(entryName);
                        break;
                    }
                }
            }

            if (!templateEntry || !templateEntry->isFile()) {
                suffix = QStringLiteral(".desktop");
                templateEntry = templateArchive->directory()->entry(templateInfo.baseName() + suffix);
            }

            if (!templateEntry || !templateEntry->isFile()) {
                const auto dirEntries = templateArchive->directory()->entries();
                for (const QString& entryName : dirEntries) {
                    if (entryName.endsWith(suffix)) {
                        templateEntry = templateArchive->directory()->entry(entryName);
                        break;
                    }
                }
            }
            if (!templateEntry || !templateEntry->isFile()) {
                qCDebug(LANGUAGE) << "template" << archName << "does not contain .kdevtemplate or .desktop file";
                continue;
            }
            const auto* templateFile = static_cast<const KArchiveFile*>(templateEntry);

            qCDebug(LANGUAGE) << "copy template description to" << localDescriptionsDir;
            const QString descriptionFileName = templateInfo.baseName() + suffix;
            if (templateFile->name() == descriptionFileName) {
                templateFile->copyTo(localDescriptionsDir);
            } else {
                // Rename the extracted description
                // so that its basename matches the basename of the template archive
                // Use temporary dir to not overwrite other files with same name
                QTemporaryDir dir;
                templateFile->copyTo(dir.path());
                const QString destinationPath = localDescriptionsDir + descriptionFileName;
                QFile::remove(destinationPath);
                QFile::rename(dir.path() + QLatin1Char('/') + templateFile->name(), destinationPath);
            }
        } else
        {
            qCWarning(LANGUAGE) << "could not open template" << archName;
        }
    }
}

QModelIndexList TemplatesModel::templateIndexes(const QString& fileName) const
{
    Q_D(const TemplatesModel);

    QFileInfo info(fileName);
    QString description =
        QStandardPaths::locate(QStandardPaths::GenericDataLocation,
                               d->resourceFilter(TemplatesModelPrivate::Description,
                                                 info.baseName() + QLatin1String(".kdevtemplate")));
    if (description.isEmpty()) {
        description =
            QStandardPaths::locate(QStandardPaths::GenericDataLocation,
                                   d->resourceFilter(TemplatesModelPrivate::Description,
                                                     info.baseName() + QLatin1String(".desktop")));
    }

    QModelIndexList indexes;

    if (!description.isEmpty()) {
        KConfig templateConfig(description);
        KConfigGroup general(&templateConfig, "General");
        const QStringList categories = general.readEntry("Category").split(QLatin1Char('/'));

        QStringList levels;
        levels.reserve(categories.size());
        for (const QString& category : categories) {
            levels << category;
            indexes << d->templateItems[levels.join(QLatin1Char('/'))]->index();
        }

        if (!indexes.isEmpty()) {
            QString name = general.readEntry("Name");
            QStandardItem* categoryItem = d->templateItems[levels.join(QLatin1Char('/'))];
            for (int i = 0; i < categoryItem->rowCount(); ++i) {
                QStandardItem* templateItem = categoryItem->child(i);
                if (templateItem->text() == name) {
                    indexes << templateItem->index();
                    break;
                }
            }
        }
    }

    return indexes;
}

QString TemplatesModel::typePrefix() const
{
    Q_D(const TemplatesModel);

    return d->typePrefix;
}

void TemplatesModel::addDataPath(const QString& path)
{
    Q_D(TemplatesModel);

    QString realpath = path + d->resourceFilter(TemplatesModelPrivate::Template);
    d->searchPaths.append(realpath);
}

QString TemplatesModel::loadTemplateFile(const QString& fileName)
{
    Q_D(TemplatesModel);

    QString saveLocation = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1Char('/') +
                           d->resourceFilter(TemplatesModelPrivate::Template);

    QDir dir(saveLocation);
    if (!dir.exists())
        dir.mkpath(QStringLiteral("."));

    QFileInfo info(fileName);
    QString destination = saveLocation + info.baseName();

    QMimeType mimeType = QMimeDatabase().mimeTypeForFile(fileName);
    qCDebug(LANGUAGE) << "Loaded file" << fileName << "with type" << mimeType.name();

    if (mimeType.name() == QLatin1String("application/x-desktop")) {
        qCDebug(LANGUAGE) << "Loaded desktop file" << info.absoluteFilePath() << ", compressing";
#ifdef Q_WS_WIN
        destination += ".zip";
        KZip archive(destination);
#else
        destination += QLatin1String(".tar.bz2");
        KTar archive(destination, QStringLiteral("application/x-bzip"));
#endif //Q_WS_WIN

        archive.open(QIODevice::WriteOnly);

        QDir dir(info.absoluteDir());
        const auto dirEntryInfos = dir.entryInfoList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
        for (const QFileInfo& entry : dirEntryInfos) {
            if (entry.isFile()) {
                archive.addLocalFile(entry.absoluteFilePath(), entry.fileName());
            } else if (entry.isDir()) {
                archive.addLocalDirectory(entry.absoluteFilePath(), entry.fileName());
            }
        }

        archive.close();
    } else
    {
        qCDebug(LANGUAGE) << "Copying" << fileName << "to" << saveLocation;
        QFile::copy(fileName, saveLocation + info.fileName());
    }

    refresh();

    return destination;
}