File indexing completed on 2024-04-28 04:37:25
0001 /* 0002 SPDX-FileCopyrightText: 2021 Igor Kushnir <igorkuo@gmail.com> 0003 0004 SPDX-License-Identifier: LGPL-2.0-or-later 0005 */ 0006 0007 #ifndef KDEVPLATFORM_SOURCEFORMATTERCONFIG_H 0008 #define KDEVPLATFORM_SOURCEFORMATTERCONFIG_H 0009 0010 #include "debug.h" 0011 0012 #include <KConfigGroup> 0013 0014 #include <QMimeType> 0015 #include <QString> 0016 #include <QStringView> 0017 0018 #include <utility> 0019 0020 namespace KDevelop { 0021 namespace SourceFormatter { 0022 0023 class ConfigForMimeType 0024 { 0025 public: 0026 explicit ConfigForMimeType(const KConfigGroup& sourceFormatterConfig, const QMimeType& mimeType) 0027 : ConfigForMimeType(sourceFormatterConfig, mimeType.name()) 0028 { 0029 } 0030 explicit ConfigForMimeType(const KConfigGroup& sourceFormatterConfig, const QString& mimeTypeName); 0031 0032 bool isValid() const 0033 { 0034 return m_formatterEndPos != 0; 0035 } 0036 0037 QStringView formatterName() const 0038 { 0039 Q_ASSERT(isValid()); 0040 return QStringView{m_entry.constData(), m_formatterEndPos}; 0041 } 0042 0043 QStringView styleName() const 0044 { 0045 Q_ASSERT(isValid()); 0046 return QStringView{m_entry}.mid(stylePos()); 0047 } 0048 0049 QString takeStyleName() && 0050 { 0051 Q_ASSERT(isValid()); 0052 // the order of the following statements is important 0053 m_entry.remove(0, stylePos()); 0054 m_formatterEndPos = 0; 0055 0056 Q_ASSERT(!isValid()); 0057 return std::move(m_entry); 0058 } 0059 0060 template<class Style> 0061 static void writeEntry(KConfigGroup& sourceFormatterConfig, const QMimeType& mimeType, const QString& formatterName, 0062 const Style* style) 0063 { 0064 if (style) { 0065 QString entry = formatterName + delimiter + style->name(); 0066 sourceFormatterConfig.writeEntry(mimeType.name(), std::move(entry)); 0067 } else { 0068 sourceFormatterConfig.deleteEntry(mimeType.name()); 0069 } 0070 } 0071 0072 private: 0073 static constexpr QLatin1String delimiter{"||", 2}; 0074 0075 qsizetype stylePos() const 0076 { 0077 return m_formatterEndPos + delimiter.size(); 0078 } 0079 0080 QString m_entry; 0081 qsizetype m_formatterEndPos = 0; 0082 }; 0083 0084 inline ConfigForMimeType::ConfigForMimeType(const KConfigGroup& sourceFormatterConfig, const QString& mimeTypeName) 0085 { 0086 m_entry = sourceFormatterConfig.readEntry(mimeTypeName, QString{}); 0087 if (m_entry.isEmpty()) { 0088 Q_ASSERT(!isValid()); 0089 return; 0090 } 0091 0092 m_formatterEndPos = m_entry.indexOf(delimiter); 0093 if (m_formatterEndPos <= 0 || stylePos() >= m_entry.size()) { 0094 qCWarning(SHELL) << "Broken formatting entry for mime type" << mimeTypeName << ":" << m_entry; 0095 m_formatterEndPos = 0; 0096 Q_ASSERT(!isValid()); 0097 return; 0098 } 0099 0100 Q_ASSERT(isValid()); 0101 } 0102 0103 } 0104 } 0105 0106 #endif // KDEVPLATFORM_SOURCEFORMATTERCONFIG_H