configmodel.cpp 14.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 37 38 39 40 41

namespace CMakeProjectManager {

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

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

51
QVariant ConfigModel::data(const QModelIndex &idx, int role) const
52
{
53 54 55 56 57 58 59 60 61 62 63
    // 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);
64 65
}

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

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

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

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

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

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

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

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

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

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

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

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

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

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
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);
}

157 158 159 160 161 162 163 164 165 166 167 168
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;
    });
169 170
}

171
void ConfigModel::setConfiguration(const QList<ConfigModel::InternalDataItem> &config)
172
{
173
    QList<InternalDataItem> tmp = config;
174 175 176 177 178 179 180
    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) {
181 182 183
        if (newIt->isHidden) {
            ++newIt;
        } else if (newIt->key < oldIt->key) {
184
            // Add new entry:
185
            result << *newIt;
186 187
            ++newIt;
        } else if (newIt->key > oldIt->key) {
188 189 190
            // Keep old user settings, but skip other entries:
            if (oldIt->isUserChanged || oldIt->isUserNew)
                result << InternalDataItem(*oldIt);
191 192 193 194
            ++oldIt;
        } else {
            // merge old/new entry:
            InternalDataItem item(*newIt);
195
            item.newValue = (newIt->value != oldIt->newValue) ? oldIt->newValue : QString();
196
            item.isCMakeChanged = (oldIt->value != newIt->value);
197
            item.isUserChanged = !item.newValue.isEmpty() && (item.newValue != item.value);
198 199 200 201 202 203 204
            result << item;
            ++newIt;
            ++oldIt;
        }
    }

    // Add remaining new entries:
205 206 207
    for (; newIt != newEndIt; ++newIt) {
        if (newIt->isHidden)
            continue;
208
        result << InternalDataItem(*newIt);
209
    }
210 211 212

    m_configuration = result;

213
    generateTree();
214 215
}

216
static QString prefix(const QString &key)
217
{
218 219 220 221
    int pos = key.indexOf('_');
    if (pos > 0)
        return key.left(pos);
    return key;
222 223
}

224
void ConfigModel::generateTree()
225
{
226 227 228 229 230 231 232 233 234 235 236
    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);
        }
    }
237

238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    // 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);
261 262
}

263 264 265 266
ConfigModel::InternalDataItem::InternalDataItem(const ConfigModel::DataItem &item) : DataItem(item)
{ }

QString ConfigModel::InternalDataItem::toolTip() const
267
{
268 269 270 271 272 273 274 275 276 277 278 279 280
    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>");
281 282
}

283
QString ConfigModel::InternalDataItem::currentValue() const
284
{
285
    return isUserChanged ? newValue : value;
286 287
}

288 289 290 291 292
namespace Internal {

ConfigModelTreeItem::~ConfigModelTreeItem() = default;

QVariant ConfigModelTreeItem::data(int column, int role) const
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
    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::ItemTypeRole)
        return dataItem->type;
    if (role == ConfigModel::ItemValuesRole)
        return dataItem->values;
    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();
    }
362 363
}

364
bool ConfigModelTreeItem::setData(int column, const QVariant &value, int role)
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
    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;
    }
397 398
}

399
Qt::ItemFlags ConfigModelTreeItem::flags(int column) const
400
{
401 402
    if (column < 0 || column >= 2)
        return Qt::NoItemFlags;
403

404
    QTC_ASSERT(dataItem, return Qt::NoItemFlags);
405

406 407 408 409 410 411 412 413 414 415 416 417 418 419
    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
420
{
421 422 423 424 425 426 427
    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);
428
    }  else {
429
        tooltip << QCoreApplication::translate("CMakeProjectManager", "Not in CMakeCache.txt");
430
    }
431 432 433
    return tooltip.join("<br>");
}

434
QString ConfigModelTreeItem::currentValue() const
435
{
436 437
    QTC_ASSERT(dataItem, return QString());
    return dataItem->isUserChanged ? dataItem->newValue : dataItem->value;
438
}
439

440
} // namespace Internal
441
} // namespace CMakeProjectManager