File indexing completed on 2024-04-14 03:49:47
0001 /* 0002 This file is part of the KDE Baloo project. 0003 SPDX-FileCopyrightText: 2019 Stefan BrĂ¼ns <stefan.bruens@rwth-aachen.de> 0004 0005 SPDX-License-Identifier: LGPL-2.1-or-later 0006 */ 0007 0008 #include "propertydata.h" 0009 #include <QJsonArray> 0010 #include <QJsonValue> 0011 0012 namespace Baloo 0013 { 0014 0015 const QJsonObject propertyMapToJson(const KFileMetaData::PropertyMultiMap& properties) 0016 { 0017 auto it = properties.cbegin(); 0018 QJsonObject jsonDict; 0019 0020 while (it != properties.cend()) { 0021 auto property = it.key(); 0022 QString keyString = QString::number(static_cast<int>(property)); 0023 0024 auto rangeEnd = properties.upperBound(property); 0025 0026 QJsonValue value; 0027 // In case a key has multiple values, convert to QJsonArray 0028 if (std::distance(it, rangeEnd) > 1) { 0029 QJsonArray values; 0030 0031 // Last inserted is first element, for backwards compatible 0032 // ordering prepend earlier elements 0033 while (it != rangeEnd) { 0034 values.insert(0, QJsonValue::fromVariant(it.value())); 0035 ++it; 0036 }; 0037 0038 value = values; 0039 } else { 0040 auto type = it.value().userType(); 0041 if ((type == QMetaType::QVariantList) || (type == QMetaType::QStringList)) { 0042 // if it is a QList<T>, recurse 0043 auto list = it.value().toList(); 0044 QJsonArray values; 0045 while (!list.isEmpty()) { 0046 values.push_back(QJsonValue::fromVariant(list.takeLast())); 0047 } 0048 value = values; 0049 } else { 0050 value = QJsonValue::fromVariant(it.value()); 0051 } 0052 } 0053 0054 jsonDict.insert(keyString, value); 0055 0056 // pivot to next key 0057 it = rangeEnd; 0058 } 0059 0060 return jsonDict; 0061 } 0062 0063 const KFileMetaData::PropertyMultiMap jsonToPropertyMap(const QJsonObject& properties) 0064 { 0065 KFileMetaData::PropertyMultiMap propertyMap; 0066 0067 auto it = properties.begin(); 0068 while (it != properties.end()) { 0069 int propNum = it.key().toInt(); 0070 auto prop = static_cast<KFileMetaData::Property::Property>(propNum); 0071 0072 if (it.value().isArray()) { 0073 const auto values = it.value().toArray(); 0074 for (const auto val : values) { 0075 propertyMap.insert(prop, val.toVariant()); 0076 } 0077 0078 } else if (it.value().isDouble()) { 0079 propertyMap.insert(prop, it.value().toDouble()); 0080 } else { 0081 propertyMap.insert(prop, it.value().toString()); 0082 } 0083 ++it; 0084 } 0085 0086 return propertyMap; 0087 } 0088 0089 } // namespace Baloo