aboutsummaryrefslogtreecommitdiffstats
path: root/src/plugins/squish/objectsmapdocument.cpp
blob: 0555bb3512c4aee631227363b04f08dc0cf674cb (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
// Copyright (C) 2022 The Qt Company Ltd
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

#include "objectsmapdocument.h"

#include "objectsmaptreeitem.h"
#include "squishconstants.h"
#include "squishplugin.h"
#include "squishsettings.h"
#include "squishtr.h"

#include <utils/fileutils.h>
#include <utils/qtcprocess.h>

#include <QtCore5Compat/QTextCodec>

namespace Squish {
namespace Internal {

static const char kItemSeparator = '\n';
static const char kPropertySeparator = '\t';

ObjectsMapDocument::ObjectsMapDocument()
    : m_contentModel(new ObjectsMapModel(this))
    , m_isModified(false)
{
    setMimeType(Constants::SQUISH_OBJECTSMAP_MIMETYPE);
    setId(Constants::OBJECTSMAP_EDITOR_ID);
    connect(m_contentModel, &ObjectsMapModel::modelChanged, this, [this] { setModified(true); });
}

Core::IDocument::OpenResult ObjectsMapDocument::open(QString *errorString,
                                                     const Utils::FilePath &fileName,
                                                     const Utils::FilePath &realFileName)
{
    OpenResult result = openImpl(errorString, fileName, realFileName);
    if (result == OpenResult::Success) {
        setFilePath(fileName);
        setModified(fileName != realFileName);
    }
    return result;
}

bool ObjectsMapDocument::save(QString *errorString, const Utils::FilePath &fileName, bool autoSave)
{
    const Utils::FilePath actual = fileName.isEmpty() ? filePath() : fileName;
    if (actual.isEmpty())
        return false;

    const bool writeOk = writeFile(actual);
    if (!writeOk) {
        if (errorString)
            *errorString = Tr::tr("Failed to write \"%1\"").arg(actual.toUserOutput());
        return false;
    }

    if (!autoSave) {
        setModified(false);
        setFilePath(actual);
    }
    return true;
}

Utils::FilePath ObjectsMapDocument::fallbackSaveAsPath() const
{
    return Utils::FilePath();
}

QString ObjectsMapDocument::fallbackSaveAsFileName() const
{
    return "objects.map";
}

void ObjectsMapDocument::setModified(bool modified)
{
    m_isModified = modified;
    emit changed();
}

bool ObjectsMapDocument::reload(QString *errorString,
                                Core::IDocument::ReloadFlag flag,
                                Core::IDocument::ChangeType type)
{
    Q_UNUSED(type);
    if (flag == FlagIgnore)
        return true;
    emit aboutToReload();
    const bool success = (openImpl(errorString, filePath(), filePath()) == OpenResult::Success);
    if (success)
        setModified(false);
    emit reloadFinished(success);
    return success;
}

bool ObjectsMapDocument::buildObjectsMapTree(const QByteArray &contents)
{
    QMap<QString, ObjectsMapTreeItem *> itemForName;

    // get names and their properties as we don't have correct (creation) order inside objects.map
    const QList<QByteArray> lines = contents.split(kItemSeparator);
    for (const QByteArray &line : lines) {
        if (line.isEmpty())
            continue;

        const int tabPosition = line.indexOf(kPropertySeparator);
        const QString objectName = QString::fromUtf8(line.left(tabPosition).trimmed());
        if (!objectName.startsWith(ObjectsMapTreeItem::COLON)) {
            qDeleteAll(itemForName);
            return false;
        }

        ObjectsMapTreeItem *item = new ObjectsMapTreeItem(objectName,
                                                          Qt::ItemIsEnabled | Qt::ItemIsSelectable
                                                              | Qt::ItemIsEditable);

        item->setPropertiesContent(line.mid(tabPosition + 1).trimmed());

        itemForName.insert(objectName, item);
        item->initPropertyModelConnections(m_contentModel);
    }
    // now build the tree
    ObjectsMapTreeItem *root = new ObjectsMapTreeItem(QString());

    QMap<QString, ObjectsMapTreeItem *>::iterator end = itemForName.end();
    for (ObjectsMapTreeItem *item : std::as_const(itemForName)) {
        const QString &parentName = item->parentName();
        auto parent = itemForName.find(parentName);
        if (parent != end)
            parent.value()->appendChild(item);
        else
            root->appendChild(item);
    }

    m_contentModel->changeRootItem(root);
    return true;
}

bool ObjectsMapDocument::setContents(const QByteArray &contents)
{
    return buildObjectsMapTree(contents);
}

QByteArray ObjectsMapDocument::contents() const
{
    QByteArray result;
    QMap<QString, PropertyList> objects;
    m_contentModel->forAllItems([&objects](ObjectsMapTreeItem *item) {
        if (item->parent())
            objects.insert(item->data(0, Qt::DisplayRole).toString(), item->properties());
    });
    const QStringList &keys = objects.keys();

    for (const QString &objName : keys) {
        result.append(objName.toUtf8());
        result.append(kPropertySeparator);

        const PropertyList properties = objects.value(objName);
        // ensure to store invalid properties content as is instead of an empty {}
        if (properties.isEmpty()) {
            if (Utils::TreeItem *item = m_contentModel->findItem(objName)) {
                ObjectsMapTreeItem *objMapItem = static_cast<ObjectsMapTreeItem *>(item);
                if (!objMapItem->isValid()) {
                    result.append(objMapItem->propertiesContent()).append(kItemSeparator);
                    continue;
                }
            }
        }
        result.append('{');
        for (const Property &property : properties) {
            result.append(property.toString().toUtf8());
            result.append(' ');
        }
        // remove the last space added by the last property
        if (result.at(result.size() - 1) == ' ')
            result.chop(1);
        result.append('}');
        result.append(kItemSeparator);
    }

    return result;
}

Core::IDocument::OpenResult ObjectsMapDocument::openImpl(QString *error,
                                                         const Utils::FilePath &fileName,
                                                         const Utils::FilePath &realFileName)
{
    if (fileName.isEmpty())
        return OpenResult::CannotHandle;

    QByteArray text;
    if (realFileName.fileName() == "objects.map") {
        Utils::FileReader reader;
        if (!reader.fetch(realFileName, QIODevice::Text, error))
            return OpenResult::ReadError;

        text = reader.data();
    } else {
        const Utils::FilePath base = SquishPlugin::squishSettings()->squishPath.filePath();
        if (base.isEmpty()) {
            if (error)
                error->append(Tr::tr("Incomplete Squish settings. "
                                     "Missing Squish installation path."));
            return OpenResult::ReadError;
        }
        const Utils::FilePath exe = base.pathAppended("lib/exec/objectmaptool").withExecutableSuffix();
        if (!exe.isExecutableFile()) {
            if (error)
                error->append(Tr::tr("objectmaptool not found."));
            return OpenResult::ReadError;
        }

        Utils::Process objectMapReader;
        objectMapReader.setCommand({exe, {"--scriptMap", "--mode", "read",
                                          "--scriptedObjectMapPath", realFileName.toUserOutput()}});
        objectMapReader.setCodec(QTextCodec::codecForName("UTF-8"));
        objectMapReader.start();
        objectMapReader.waitForFinished();
        text = objectMapReader.cleanedStdOut().toUtf8();
    }
    if (!setContents(text)) {
        if (error)
            error->append(Tr::tr("Failure while parsing objects.map content."));
        return OpenResult::ReadError;
    }
    return OpenResult::Success;
}

bool ObjectsMapDocument::writeFile(const Utils::FilePath &fileName) const
{
    if (fileName.endsWith("objects.map")) {
        Utils::FileSaver saver(fileName);
        return saver.write(contents()) && saver.finalize();
    }

    // otherwise we need the objectmaptool to write the scripted object map again
    const Utils::FilePath base = SquishPlugin::squishSettings()->squishPath.filePath();
    if (base.isEmpty())
        return false;
    const Utils::FilePath exe = base.pathAppended("lib/exec/objectmaptool").withExecutableSuffix();
    if (!exe.isExecutableFile())
        return false;

    Utils::Process objectMapWriter;
    objectMapWriter.setCommand({exe, {"--scriptMap", "--mode", "write",
                                      "--scriptedObjectMapPath", fileName.toUserOutput()}});
    objectMapWriter.setWriteData(contents());
    objectMapWriter.start();
    objectMapWriter.waitForFinished();
    return objectMapWriter.result() == Utils::ProcessResult::FinishedWithSuccess;
}

} // namespace Internal
} // namespace Squish