aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/utils/namevaluemodel.cpp
blob: 2a310d6b6155a6a82a91706fdf8f6c7bd503a79f (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
/****************************************************************************
**
** Copyright (C) 2019 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/

#include "namevaluemodel.h"

#include <utils/algorithm.h>
#include <utils/hostosinfo.h>
#include <utils/namevaluedictionary.h>

#include <QFont>
#include <QString>

namespace Utils {
namespace Internal {

class NameValueModelPrivate
{
public:
    void updateResultNameValueDictionary()
    {
        m_resultNameValueDictionary = m_baseNameValueDictionary;
        m_resultNameValueDictionary.modify(m_items);
        // Add removed variables again and mark them as "<UNSET>" so
        // that the user can actually see those removals:
        foreach (const NameValueItem &item, m_items) {
            if (item.operation == NameValueItem::Unset)
                m_resultNameValueDictionary.set(item.name, NameValueModel::tr("<UNSET>"));
        }
    }

    int findInChanges(const QString &name) const
    {
        for (int i = 0; i < m_items.size(); ++i)
            if (m_items.at(i).name == name)
                return i;
        return -1;
    }

    int findInResultInsertPosition(const QString &name) const
    {
        NameValueDictionary::const_iterator it;
        int i = 0;
        for (it = m_resultNameValueDictionary.constBegin();
             it != m_resultNameValueDictionary.constEnd();
             ++it, ++i)
            if (m_resultNameValueDictionary.key(it) > name)
                return i;
        return m_resultNameValueDictionary.size();
    }

    int findInResult(const QString &name) const
    {
        NameValueDictionary::const_iterator it;
        int i = 0;
        for (it = m_resultNameValueDictionary.constBegin();
             it != m_resultNameValueDictionary.constEnd();
             ++it, ++i)
            if (m_resultNameValueDictionary.key(it) == name)
                return i;
        return -1;
    }

    NameValueDictionary m_baseNameValueDictionary;
    NameValueDictionary m_resultNameValueDictionary;
    NameValueItems m_items;
};

} // namespace Internal

NameValueModel::NameValueModel(QObject *parent)
    : QAbstractTableModel(parent)
    , d(std::make_unique<Internal::NameValueModelPrivate>())
{}

NameValueModel::~NameValueModel() = default;

QString NameValueModel::indexToVariable(const QModelIndex &index) const
{
    return d->m_resultNameValueDictionary.key(d->m_resultNameValueDictionary.constBegin()
                                              + index.row());
}

void NameValueModel::setBaseNameValueDictionary(const NameValueDictionary &dictionary)
{
    if (d->m_baseNameValueDictionary == dictionary)
        return;
    beginResetModel();
    d->m_baseNameValueDictionary = dictionary;
    d->updateResultNameValueDictionary();
    endResetModel();
}

int NameValueModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return d->m_resultNameValueDictionary.size();
}
int NameValueModel::columnCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return 2;
}

bool NameValueModel::changes(const QString &name) const
{
    return d->findInChanges(name) >= 0;
}

const NameValueDictionary &NameValueModel::baseNameValueDictionary() const
{
    return d->m_baseNameValueDictionary;
}

QVariant NameValueModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();

    if (role == Qt::DisplayRole || role == Qt::EditRole || role == Qt::ToolTipRole) {
        if (index.column() == 0) {
            return d->m_resultNameValueDictionary.key(d->m_resultNameValueDictionary.constBegin()
                                                      + index.row());
        } else if (index.column() == 1) {
            // Do not return "<UNSET>" when editing a previously unset variable:
            if (role == Qt::EditRole) {
                int pos = d->findInChanges(indexToVariable(index));
                if (pos >= 0)
                    return d->m_items.at(pos).value;
            }
            QString value = d->m_resultNameValueDictionary.value(
                d->m_resultNameValueDictionary.constBegin() + index.row());
            if (role == Qt::ToolTipRole && value.length() > 80) {
                // Use html to enable text wrapping
                value = value.toHtmlEscaped();
                value.prepend(QLatin1String("<html><body>"));
                value.append(QLatin1String("</body></html>"));
            }
            return value;
        }
    }
    if (role == Qt::FontRole) {
        // check whether this name value item variable exists in d->m_items
        if (changes(d->m_resultNameValueDictionary.key(d->m_resultNameValueDictionary.constBegin()
                                                       + index.row()))) {
            QFont f;
            f.setBold(true);
            return QVariant(f);
        }
        return QFont();
    }
    return QVariant();
}

Qt::ItemFlags NameValueModel::flags(const QModelIndex &index) const
{
    Q_UNUSED(index)
    return Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled;
}

QVariant NameValueModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (orientation == Qt::Vertical || role != Qt::DisplayRole)
        return QVariant();
    return section == 0 ? tr("Variable") : tr("Value");
}

/// *****************
/// Utility functions
/// *****************
QModelIndex NameValueModel::variableToIndex(const QString &name) const
{
    int row = d->findInResult(name);
    if (row == -1)
        return QModelIndex();
    return index(row, 0);
}

bool NameValueModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || role != Qt::EditRole)
        return false;

    // ignore changes to already set values:
    if (data(index, role) == value)
        return true;

    const QString oldName = data(this->index(index.row(), 0, QModelIndex())).toString();
    const QString oldValue = data(this->index(index.row(), 1, QModelIndex()), Qt::EditRole).toString();
    int changesPos = d->findInChanges(oldName);

    if (index.column() == 0) {
        //fail if a variable with the same name already exists
        const QString &newName = HostOsInfo::isWindowsHost() ? value.toString().toUpper()
                                                             : value.toString();
        if (newName.isEmpty() || newName.contains('='))
            return false;
        // Does the new name exist already?
        if (d->m_resultNameValueDictionary.hasKey(newName) || newName.isEmpty())
            return false;

        NameValueItem newVariable(newName, oldValue);

        if (changesPos != -1)
            resetVariable(oldName); // restore the original base variable again

        QModelIndex newIndex = addVariable(newVariable);      // add the new variable
        emit focusIndex(newIndex.sibling(newIndex.row(), 1)); // hint to focus on the value
        return true;
    } else if (index.column() == 1) {
        // We are changing an existing value:
        const QString stringValue = value.toString();
        if (changesPos != -1) {
            // We have already changed this value
            if (d->m_baseNameValueDictionary.hasKey(oldName)
                && stringValue == d->m_baseNameValueDictionary.value(oldName)) {
                // ... and now went back to the base value
                d->m_items.removeAt(changesPos);
            } else {
                // ... and changed it again
                d->m_items[changesPos].value = stringValue;
                d->m_items[changesPos].operation = NameValueItem::Set;
            }
        } else {
            // Add a new change item:
            d->m_items.append(NameValueItem(oldName, stringValue));
        }
        d->updateResultNameValueDictionary();
        emit dataChanged(index, index);
        emit userChangesChanged();
        return true;
    }
    return false;
}

QModelIndex NameValueModel::addVariable()
{
    //: Name when inserting a new variable
    return addVariable(NameValueItem(tr("<VARIABLE>"),
                                     //: Value when inserting a new variable
                                     tr("<VALUE>")));
}

QModelIndex NameValueModel::addVariable(const NameValueItem &item)
{
    // Return existing index if the name is already in the result set:
    int pos = d->findInResult(item.name);
    if (pos >= 0 && pos < d->m_resultNameValueDictionary.size())
        return index(pos, 0, QModelIndex());

    int insertPos = d->findInResultInsertPosition(item.name);
    int changePos = d->findInChanges(item.name);
    if (d->m_baseNameValueDictionary.hasKey(item.name)) {
        // We previously unset this!
        Q_ASSERT(changePos >= 0);
        // Do not insert a line here as we listed the variable as <UNSET> before!
        Q_ASSERT(d->m_items.at(changePos).name == item.name);
        Q_ASSERT(d->m_items.at(changePos).operation == NameValueItem::Unset);
        Q_ASSERT(d->m_items.at(changePos).value.isEmpty());
        d->m_items[changePos] = item;
        emit dataChanged(index(insertPos, 0, QModelIndex()), index(insertPos, 1, QModelIndex()));
    } else {
        // We add something that is not in the base dictionary
        // Insert a new line!
        beginInsertRows(QModelIndex(), insertPos, insertPos);
        Q_ASSERT(changePos < 0);
        d->m_items.append(item);
        d->updateResultNameValueDictionary();
        endInsertRows();
    }
    emit userChangesChanged();
    return index(insertPos, 0, QModelIndex());
}

void NameValueModel::resetVariable(const QString &name)
{
    int rowInChanges = d->findInChanges(name);
    if (rowInChanges < 0)
        return;

    int rowInResult = d->findInResult(name);
    if (rowInResult < 0)
        return;

    if (d->m_baseNameValueDictionary.hasKey(name)) {
        d->m_items.removeAt(rowInChanges);
        d->updateResultNameValueDictionary();
        emit dataChanged(index(rowInResult, 0, QModelIndex()), index(rowInResult, 1, QModelIndex()));
        emit userChangesChanged();
    } else {
        // Remove the line completely!
        beginRemoveRows(QModelIndex(), rowInResult, rowInResult);
        d->m_items.removeAt(rowInChanges);
        d->updateResultNameValueDictionary();
        endRemoveRows();
        emit userChangesChanged();
    }
}

void NameValueModel::unsetVariable(const QString &name)
{
    // This does not change the number of rows as we will display a <UNSET>
    // in place of the original variable!
    int row = d->findInResult(name);
    if (row < 0)
        return;

    // look in d->m_items for the variable
    int pos = d->findInChanges(name);
    if (pos != -1) {
        d->m_items[pos].operation = NameValueItem::Unset;
        d->m_items[pos].value.clear();
        d->updateResultNameValueDictionary();
        emit dataChanged(index(row, 0, QModelIndex()), index(row, 1, QModelIndex()));
        emit userChangesChanged();
        return;
    }
    d->m_items.append(NameValueItem(name, QString(), NameValueItem::Unset));
    d->updateResultNameValueDictionary();
    emit dataChanged(index(row, 0, QModelIndex()), index(row, 1, QModelIndex()));
    emit userChangesChanged();
}

bool NameValueModel::canUnset(const QString &name)
{
    int pos = d->findInChanges(name);
    if (pos != -1)
        return d->m_items.at(pos).operation == NameValueItem::Unset;
    else
        return false;
}

bool NameValueModel::canReset(const QString &name)
{
    return d->m_baseNameValueDictionary.hasKey(name);
}

NameValueItems NameValueModel::userChanges() const
{
    return d->m_items;
}

void NameValueModel::setUserChanges(const NameValueItems &items)
{
    NameValueItems filtered = Utils::filtered(items, [](const NameValueItem &i) {
        return i.name != "export " && !i.name.contains('=');
    });
    // We assume nobody is reordering the items here.
    if (filtered == d->m_items)
        return;
    beginResetModel();
    d->m_items = filtered;
    for (NameValueItem &item : d->m_items) {
        QString &name = item.name;
        name = name.trimmed();
        if (name.startsWith("export "))
            name = name.mid(7).trimmed();
        if (d->m_baseNameValueDictionary.osType() == OsTypeWindows) {
            // NameValueDictionary variable names are case-insensitive under windows, but we still
            // want to preserve the case of pre-existing variables.
            auto it = d->m_baseNameValueDictionary.constFind(name);
            if (it != d->m_baseNameValueDictionary.constEnd())
                name = d->m_baseNameValueDictionary.key(it);
        }
    }

    d->updateResultNameValueDictionary();
    endResetModel();
    emit userChangesChanged();
}

} // namespace Utils