configmodel.cpp 15.1 KB
Newer Older
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
/****************************************************************************
**
** Copyright (C) 2016 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 "configmodel.h"

28
#include <utils/asconst.h>
29 30
#include <utils/algorithm.h>
#include <utils/qtcassert.h>
31
#include <utils/theme/theme.h>
32

33
#include <QCoreApplication>
34
#include <QFont>
35
#include <QString>
36
#include <QSortFilterProxyModel>
37 38 39 40 41 42

namespace CMakeProjectManager {

static bool isTrue(const QString &value)
{
    const QString lower = value.toLower();
43 44
    return lower == QStringLiteral("true") || lower == QStringLiteral("on")
            || lower == QStringLiteral("1") || lower == QStringLiteral("yes");
45 46
}

47
ConfigModel::ConfigModel(QObject *parent) : Utils::TreeModel<>(parent)
48
{
49
    setHeader({tr("Key"), tr("Value")});
50 51
}

52
QVariant ConfigModel::data(const QModelIndex &idx, int role) const
53
{
54 55 56 57 58 59 60 61 62 63 64
    // Hide/show groups according to "isAdvanced" setting:
    Utils::TreeItem *item = static_cast<Utils::TreeItem *>(idx.internalPointer());
    if (role == ItemIsAdvancedRole && item->childCount() > 0) {
        const bool hasNormalChildren = item->findAnyChild([](const Utils::TreeItem *ti) {
            if (auto cmti = dynamic_cast<const Internal::ConfigModelTreeItem*>(ti))
                return !cmti->dataItem->isAdvanced;
            return false;
        }) != nullptr;
        return hasNormalChildren ? "0" : "1";
    }
    return Utils::TreeModel<>::data(idx, role);
65 66
}

67 68 69 70 71 72 73
ConfigModel::~ConfigModel() = default;

void ConfigModel::appendConfiguration(const QString &key,
                                      const QString &value,
                                      const ConfigModel::DataItem::Type type,
                                      const QString &description,
                                      const QStringList &values)
74
{
75 76 77 78 79 80
    DataItem item;
    item.key = key;
    item.type = type;
    item.value = value;
    item.description = description;
    item.values = values;
81

82 83
    InternalDataItem internalItem(item);
    internalItem.isUserNew = true;
84

85 86 87 88 89
    if (m_kitConfiguration.contains(key))
        internalItem.kitValue = m_kitConfiguration.value(key);

    m_configuration.append(internalItem);
    setConfiguration(m_configuration);
90 91
}

92
void ConfigModel::setConfiguration(const QList<DataItem> &config)
93
{
94 95
    setConfiguration(Utils::transform(config, [](const DataItem &di) { return InternalDataItem(di); }));
}
96

97 98 99
void ConfigModel::setKitConfiguration(const QHash<QString, QString> &kitConfig)
{
    m_kitConfiguration = kitConfig;
100

101 102 103
    for (InternalDataItem &i : m_configuration) {
        if (m_kitConfiguration.contains(i.key)) {
            i.kitValue = m_kitConfiguration.value(i.key);
104 105
        }
    }
106
    setConfiguration(m_configuration);
107 108
}

109
void ConfigModel::flush()
110
{
111 112
    setConfiguration(QList<InternalDataItem>());
}
113

114 115 116 117 118
void ConfigModel::resetAllChanges()
{
    const QList<InternalDataItem> tmp
            = Utils::filtered(m_configuration,
                              [](const InternalDataItem &i) { return !i.isUserNew; });
119

120 121 122 123 124 125
    setConfiguration(Utils::transform(tmp, [](const InternalDataItem &i) {
        InternalDataItem ni(i);
        ni.newValue.clear();
        ni.isUserChanged = false;
        return ni;
    }));
126 127
}

128
bool ConfigModel::hasChanges() const
129
{
130
    return Utils::contains(m_configuration, [](const InternalDataItem &i) { return i.isUserChanged || i.isUserNew; });
131 132
}

133
bool ConfigModel::hasCMakeChanges() const
134
{
135 136
    return Utils::contains(m_configuration, [](const InternalDataItem &i) { return i.isCMakeChanged; });
}
137

138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
bool ConfigModel::canForceToString(const QModelIndex &idx) const
{
    if (idx.model() != const_cast<ConfigModel *>(this) || idx.column() != 1)
        return false;
    Utils::TreeItem *item = itemForIndex(idx);
    auto cmti = dynamic_cast<Internal::ConfigModelTreeItem *>(item);
    return cmti && (cmti->dataItem->type != DataItem::STRING);
}

void ConfigModel::forceToString(const QModelIndex &idx)
{
    QTC_ASSERT(canForceToString(idx), return);
    Utils::TreeItem *item = itemForIndex(idx);
    auto cmti = dynamic_cast<Internal::ConfigModelTreeItem *>(item);

    cmti->dataItem->type = DataItem::STRING;
    const QModelIndex valueIdx = idx.sibling(1, idx.column());
    emit dataChanged(valueIdx, valueIdx);
}

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
ConfigModel::DataItem ConfigModel::dataItemFromIndex(const QModelIndex &idx)
{
    const QAbstractItemModel *m = idx.model();
    QModelIndex mIdx = idx;
    while (auto sfpm = qobject_cast<const QSortFilterProxyModel *>(m)) {
        m = sfpm->sourceModel();
        mIdx = sfpm->mapToSource(mIdx);
    }
    auto model = qobject_cast<const ConfigModel *>(m);
    QTC_ASSERT(model, return DataItem());
    const QModelIndex modelIdx = mIdx;

    Utils::TreeItem *item = model->itemForIndex(modelIdx);
    auto cmti = dynamic_cast<Internal::ConfigModelTreeItem *>(item);

    if (cmti && cmti->dataItem) {
        DataItem di;
        di.key = cmti->dataItem->key;
        di.type = cmti->dataItem->type;
        di.isHidden = cmti->dataItem->isHidden;
        di.isAdvanced = cmti->dataItem->isAdvanced;
        di.inCMakeCache = cmti->dataItem->inCMakeCache;
        di.value = cmti->dataItem->currentValue();
        di.description = cmti->dataItem->description;
        di.values = cmti->dataItem->values;

        return di;
    }
    return DataItem();
}

189 190 191 192 193 194 195 196 197 198 199 200
QList<ConfigModel::DataItem> ConfigModel::configurationChanges() const
{
    const QList<InternalDataItem> tmp
            = Utils::filtered(m_configuration, [](const InternalDataItem &i) {
        return i.isUserChanged || i.isUserNew || !i.inCMakeCache;
    });
    return Utils::transform(tmp, [](const InternalDataItem &item) {
        DataItem newItem(item);
        if (item.isUserChanged)
            newItem.value = item.newValue;
        return newItem;
    });
201 202
}

203
void ConfigModel::setConfiguration(const QList<ConfigModel::InternalDataItem> &config)
204
{
205
    QList<InternalDataItem> tmp = config;
206 207 208 209 210 211 212
    auto newIt = tmp.constBegin();
    auto newEndIt = tmp.constEnd();
    auto oldIt = m_configuration.constBegin();
    auto oldEndIt = m_configuration.constEnd();

    QList<InternalDataItem> result;
    while (newIt != newEndIt && oldIt != oldEndIt) {
213 214 215
        if (newIt->isHidden) {
            ++newIt;
        } else if (newIt->key < oldIt->key) {
216
            // Add new entry:
217
            result << *newIt;
218 219
            ++newIt;
        } else if (newIt->key > oldIt->key) {
220 221 222
            // Keep old user settings, but skip other entries:
            if (oldIt->isUserChanged || oldIt->isUserNew)
                result << InternalDataItem(*oldIt);
223 224 225 226
            ++oldIt;
        } else {
            // merge old/new entry:
            InternalDataItem item(*newIt);
227
            item.newValue = (newIt->value != oldIt->newValue) ? oldIt->newValue : QString();
228
            item.isCMakeChanged = (oldIt->value != newIt->value);
229
            item.isUserChanged = !item.newValue.isEmpty() && (item.newValue != item.value);
230 231 232 233 234 235 236
            result << item;
            ++newIt;
            ++oldIt;
        }
    }

    // Add remaining new entries:
237 238 239
    for (; newIt != newEndIt; ++newIt) {
        if (newIt->isHidden)
            continue;
240
        result << InternalDataItem(*newIt);
241
    }
242 243 244

    m_configuration = result;

245
    generateTree();
246 247
}

248
static QString prefix(const QString &key)
249
{
250 251 252 253
    int pos = key.indexOf('_');
    if (pos > 0)
        return key.left(pos);
    return key;
254 255
}

256
void ConfigModel::generateTree()
257
{
258 259 260 261 262 263 264 265 266 267 268
    QList<QString> prefixList;

    // Generate nodes for *all* prefixes
    QHash<QString, QList<Utils::TreeItem *>> prefixes;
    for (const InternalDataItem &di : m_configuration) {
        const QString p = prefix(di.key);
        if (!prefixes.contains(p)) {
            prefixes.insert(p, {});
            prefixList.append(p);
        }
    }
269

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    // Fill prefix nodes:
    for (InternalDataItem &di : m_configuration)
        prefixes[prefix(di.key)].append(new Internal::ConfigModelTreeItem(&di));

    Utils::TreeItem *root = new Utils::TreeItem;

    for (const QString &p : Utils::asConst(prefixList)) {
        const QList<Utils::TreeItem *> &prefixItemList = prefixes.value(p);
        QTC_ASSERT(!prefixItemList.isEmpty(), continue);

        if (prefixItemList.count() == 1) {
            root->appendChild(prefixItemList.at(0));
        } else {
            Utils::TreeItem *sti = new Utils::StaticTreeItem(p);
            for (Utils::TreeItem *const ti : prefixItemList)
                sti->appendChild(ti);
            root->appendChild(sti);
        }
        prefixes.remove(p);
    }
    QTC_CHECK(prefixes.isEmpty());

    setRootItem(root);
293 294
}

295 296 297 298
ConfigModel::InternalDataItem::InternalDataItem(const ConfigModel::DataItem &item) : DataItem(item)
{ }

QString ConfigModel::InternalDataItem::toolTip() const
299
{
300 301 302 303 304 305 306 307 308 309 310 311 312
    QString desc = description;
    if (isAdvanced)
        desc += QCoreApplication::translate("CMakeProjectManager::ConfigModel", " (ADVANCED)");
    QStringList tooltip(desc);
    if (inCMakeCache) {
        if (value != newValue)
            tooltip << QCoreApplication::translate("CMakeProjectManager", "Current CMake: %1").arg(value);
    }  else {
        tooltip << QCoreApplication::translate("CMakeProjectManager", "Not in CMakeCache.txt").arg(value);
    }
    if (!kitValue.isEmpty())
        tooltip << QCoreApplication::translate("CMakeProjectManager::ConfigModel", "Current Kit: %1").arg(kitValue);
    return tooltip.join("<br>");
313 314
}

315
QString ConfigModel::InternalDataItem::currentValue() const
316
{
317
    return isUserChanged ? newValue : value;
318 319
}

320 321 322 323 324
namespace Internal {

ConfigModelTreeItem::~ConfigModelTreeItem() = default;

QVariant ConfigModelTreeItem::data(int column, int role) const
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
    QTC_ASSERT(column >= 0 && column < 2, return QVariant());

    QTC_ASSERT(dataItem, return QVariant());

    if (firstChild()) {
        // Node with children: Only ever show name:
        if (column == 0)
            return dataItem->key;
        return QVariant();
    }

    // Leaf node:
    if (role == ConfigModel::ItemIsAdvancedRole)
        return dataItem->isAdvanced ? "1" : "0";

    switch (column) {
    case 0:
        switch (role) {
        case Qt::DisplayRole:
            return dataItem->key.isEmpty() ? QCoreApplication::translate("CMakeProjectManager::ConfigModel", "<UNSET>") : dataItem->key;
        case Qt::EditRole:
            return dataItem->key;
        case Qt::ToolTipRole:
            return toolTip();
        case Qt::FontRole: {
            QFont font;
            font.setItalic(dataItem->isCMakeChanged);
            font.setBold(dataItem->isUserNew);
            font.setStrikeOut(!dataItem->inCMakeCache && !dataItem->isUserNew);
            return font;
        }
        default:
            return QVariant();
        }
    case 1: {
        const QString value = currentValue();

        switch (role) {
        case Qt::CheckStateRole:
            return (dataItem->type == ConfigModel::DataItem::BOOLEAN)
                    ? QVariant(isTrue(value) ? Qt::Checked : Qt::Unchecked) : QVariant();
        case Qt::DisplayRole:
            return value;
        case Qt::EditRole:
            return (dataItem->type == ConfigModel::DataItem::BOOLEAN) ? QVariant(isTrue(value)) : QVariant(value);
        case Qt::FontRole: {
            QFont font;
            font.setBold(dataItem->isUserChanged || dataItem->isUserNew);
            font.setItalic(dataItem->isCMakeChanged);
            return font;
        }
        case Qt::ForegroundRole:
            return Utils::creatorTheme()->color((!dataItem->kitValue.isNull() && dataItem->kitValue != value)
                    ? Utils::Theme::TextColorHighlight : Utils::Theme::TextColorNormal);
        case Qt::ToolTipRole: {
            return toolTip();
        }
        default:
            return QVariant();
        }
    }
    default:
        return QVariant();
    }
390 391
}

392
bool ConfigModelTreeItem::setData(int column, const QVariant &value, int role)
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 422 423 424
    QTC_ASSERT(column >= 0 && column < 2, return false);
    QTC_ASSERT(dataItem, return false);

    QString newValue = value.toString();
    if (role == Qt::CheckStateRole) {
        if (column != 1)
            return false;
        newValue = QString::fromLatin1(value.toInt() == 0 ? "OFF" : "ON");
    } else if (role != Qt::EditRole) {
        return false;
    }

    switch (column) {
    case 0:
        if (!dataItem->key.isEmpty() && !dataItem->isUserNew)
            return false;
        dataItem->key = newValue;
        dataItem->isUserNew = true;
        return true;
    case 1:
        if (dataItem->value == newValue) {
            dataItem->newValue.clear();
            dataItem->isUserChanged = false;
        } else {
            dataItem->newValue = newValue;
            dataItem->isUserChanged = true;
        }
        return true;
    default:
        return false;
    }
425 426
}

427
Qt::ItemFlags ConfigModelTreeItem::flags(int column) const
428
{
429 430
    if (column < 0 || column >= 2)
        return Qt::NoItemFlags;
431

432
    QTC_ASSERT(dataItem, return Qt::NoItemFlags);
433

434 435 436 437 438 439 440 441 442 443 444 445 446 447
    if (column == 1) {
        if (dataItem->type == ConfigModel::DataItem::BOOLEAN)
            return Qt::ItemIsEnabled | Qt::ItemIsUserCheckable | Qt::ItemIsSelectable;
        else
            return Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsSelectable;
    } else {
        Qt::ItemFlags flags = Qt::ItemIsEnabled | Qt::ItemIsSelectable;
        if (dataItem->isUserNew)
            return flags |= Qt::ItemIsEditable;
        return flags;
    }
}

QString ConfigModelTreeItem::toolTip() const
448
{
449 450 451 452 453 454 455
    QTC_ASSERT(dataItem, return QString());
    QStringList tooltip(dataItem->description);
    if (!dataItem->kitValue.isEmpty())
        tooltip << QCoreApplication::translate("CMakeProjectManager", "Value requested by Kit: %1").arg(dataItem->kitValue);
    if (dataItem->inCMakeCache) {
        if (dataItem->value != dataItem->newValue)
            tooltip << QCoreApplication::translate("CMakeProjectManager", "Current CMake: %1").arg(dataItem->value);
456
    }  else {
457
        tooltip << QCoreApplication::translate("CMakeProjectManager", "Not in CMakeCache.txt");
458
    }
459 460 461
    return tooltip.join("<br>");
}

462
QString ConfigModelTreeItem::currentValue() const
463
{
464 465
    QTC_ASSERT(dataItem, return QString());
    return dataItem->isUserChanged ? dataItem->newValue : dataItem->value;
466
}
467

468
} // namespace Internal
469
} // namespace CMakeProjectManager