PageRenderTime 43ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/src/libs/utils/persistentsettings.cpp

https://github.com/KDAB/KDAB-Creator
C++ | 410 lines | 293 code | 42 blank | 75 comment | 44 complexity | 304217073e1f90981bd26f3c01ab0e27 MD5 | raw file
  1. /**************************************************************************
  2. **
  3. ** This file is part of Qt Creator
  4. **
  5. ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
  6. **
  7. ** Contact: Nokia Corporation (qt-info@nokia.com)
  8. **
  9. **
  10. ** GNU Lesser General Public License Usage
  11. **
  12. ** This file may be used under the terms of the GNU Lesser General Public
  13. ** License version 2.1 as published by the Free Software Foundation and
  14. ** appearing in the file LICENSE.LGPL included in the packaging of this file.
  15. ** Please review the following information to ensure the GNU Lesser General
  16. ** Public License version 2.1 requirements will be met:
  17. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  18. **
  19. ** In addition, as a special exception, Nokia gives you certain additional
  20. ** rights. These rights are described in the Nokia Qt LGPL Exception
  21. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  22. **
  23. ** Other Usage
  24. **
  25. ** Alternatively, this file may be used in accordance with the terms and
  26. ** conditions contained in a signed written agreement between you and Nokia.
  27. **
  28. ** If you have questions regarding the use of this file, please contact
  29. ** Nokia at qt-info@nokia.com.
  30. **
  31. **************************************************************************/
  32. #include "persistentsettings.h"
  33. #include <app/app_version.h>
  34. #include <utils/fileutils.h>
  35. #include <QDebug>
  36. #include <QFile>
  37. #include <QVariant>
  38. #include <QStack>
  39. #include <QXmlStreamAttributes>
  40. #include <QXmlStreamReader>
  41. #include <QXmlStreamWriter>
  42. #include <QDateTime>
  43. #include <utils/qtcassert.h>
  44. /*!
  45. \class Utils::PersistentSettingsReader
  46. \brief Reads a QVariantMap of arbitrary, nested data structures from a XML file.
  47. Handles all string-serializable simple types and QVariantList and QVariantMap. Example:
  48. \code
  49. <qtcreator>
  50. <data>
  51. <variable>ProjectExplorer.Project.ActiveTarget</variable>
  52. <value type="int">0</value>
  53. </data>
  54. <data>
  55. <variable>ProjectExplorer.Project.EditorSettings</variable>
  56. <valuemap type="QVariantMap">
  57. <value type="bool" key="EditorConfiguration.AutoIndent">true</value>
  58. </valuemap>
  59. </data>
  60. \endcode
  61. When parsing the structure, a parse stack of ParseValueStackEntry is used for each
  62. <data> element. ParseValueStackEntry is a variant/union of:
  63. \list
  64. \o simple value
  65. \o map
  66. \o list
  67. \endlist
  68. When entering a value element ( \c <value> / \c <valuelist> , \c <valuemap> ), entry is pushed
  69. accordingly. When leaving the element, the QVariant-value of the entry is taken off the stack
  70. and added to the stack entry below (added to list or inserted into map). The first element
  71. of the stack is the value of the <data> element.
  72. \sa Utils::PersistentSettingsWriter
  73. */
  74. namespace Utils {
  75. struct Context // Basic context containing element name string constants.
  76. {
  77. Context();
  78. const QString qtCreatorElement;
  79. const QString dataElement;
  80. const QString variableElement;
  81. const QString typeAttribute;
  82. const QString valueElement;
  83. const QString valueListElement;
  84. const QString valueMapElement;
  85. const QString keyAttribute;
  86. };
  87. Context::Context() :
  88. qtCreatorElement(QLatin1String("qtcreator")),
  89. dataElement(QLatin1String("data")),
  90. variableElement(QLatin1String("variable")),
  91. typeAttribute(QLatin1String("type")),
  92. valueElement(QLatin1String("value")),
  93. valueListElement(QLatin1String("valuelist")),
  94. valueMapElement(QLatin1String("valuemap")),
  95. keyAttribute(QLatin1String("key"))
  96. {
  97. }
  98. struct ParseValueStackEntry
  99. {
  100. explicit ParseValueStackEntry(QVariant::Type t = QVariant::Invalid, const QString &k = QString()) : type(t), key(k) {}
  101. explicit ParseValueStackEntry(const QVariant &aSimpleValue, const QString &k);
  102. QVariant value() const;
  103. void addChild(const QString &key, const QVariant &v);
  104. QVariant::Type type;
  105. QString key;
  106. QVariant simpleValue;
  107. QVariantList listValue;
  108. QVariantMap mapValue;
  109. };
  110. ParseValueStackEntry::ParseValueStackEntry(const QVariant &aSimpleValue, const QString &k) :
  111. type(aSimpleValue.type()), key(k), simpleValue(aSimpleValue)
  112. {
  113. QTC_ASSERT(simpleValue.isValid(), return ; )
  114. }
  115. QVariant ParseValueStackEntry::value() const
  116. {
  117. switch (type) {
  118. case QVariant::Invalid:
  119. return QVariant();
  120. case QVariant::Map:
  121. return QVariant(mapValue);
  122. case QVariant::List:
  123. return QVariant(listValue);
  124. default:
  125. break;
  126. }
  127. return simpleValue;
  128. }
  129. void ParseValueStackEntry::addChild(const QString &key, const QVariant &v)
  130. {
  131. switch (type) {
  132. case QVariant::Map:
  133. mapValue.insert(key, v);
  134. break;
  135. case QVariant::List:
  136. listValue.push_back(v);
  137. break;
  138. default:
  139. qWarning() << "ParseValueStackEntry::Internal error adding " << key << v << " to "
  140. << QVariant::typeToName(type) << value();
  141. break;
  142. }
  143. }
  144. class ParseContext : public Context
  145. {
  146. public:
  147. QVariantMap parse(QFile &file);
  148. private:
  149. enum Element { QtCreatorElement, DataElement, VariableElement,
  150. SimpleValueElement, ListValueElement, MapValueElement, UnknownElement };
  151. Element element(const QStringRef &r) const;
  152. static inline bool isValueElement(Element e)
  153. { return e == SimpleValueElement || e == ListValueElement || e == MapValueElement; }
  154. QVariant readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const;
  155. bool handleStartElement(QXmlStreamReader &r);
  156. bool handleEndElement(const QStringRef &name);
  157. QStack<ParseValueStackEntry> m_valueStack;
  158. QVariantMap m_result;
  159. QString m_currentVariableName;
  160. };
  161. QVariantMap ParseContext::parse(QFile &file)
  162. {
  163. QXmlStreamReader r(&file);
  164. m_result.clear();
  165. m_currentVariableName.clear();
  166. while (!r.atEnd()) {
  167. switch (r.readNext()) {
  168. case QXmlStreamReader::StartElement:
  169. if (handleStartElement(r))
  170. return m_result;
  171. break;
  172. case QXmlStreamReader::EndElement:
  173. if (handleEndElement(r.name()))
  174. return m_result;
  175. break;
  176. case QXmlStreamReader::Invalid:
  177. qWarning("Error reading %s:%d: %s", qPrintable(file.fileName()),
  178. int(r.lineNumber()), qPrintable(r.errorString()));
  179. return QVariantMap();
  180. break;
  181. default:
  182. break;
  183. } // switch token
  184. } // while (!r.atEnd())
  185. return m_result;
  186. }
  187. bool ParseContext::handleStartElement(QXmlStreamReader &r)
  188. {
  189. const QStringRef name = r.name();
  190. const Element e = element(name);
  191. if (e == VariableElement) {
  192. m_currentVariableName = r.readElementText();
  193. return false;
  194. }
  195. if (!ParseContext::isValueElement(e))
  196. return false;
  197. const QXmlStreamAttributes attributes = r.attributes();
  198. const QString key = attributes.hasAttribute(keyAttribute) ?
  199. attributes.value(keyAttribute).toString() : QString();
  200. switch (e) {
  201. case SimpleValueElement:
  202. // This reads away the end element, so, handle end element right here.
  203. m_valueStack.push_back(ParseValueStackEntry(readSimpleValue(r, attributes), key));
  204. return handleEndElement(name);
  205. case ListValueElement:
  206. m_valueStack.push_back(ParseValueStackEntry(QVariant::List, key));
  207. break;
  208. case MapValueElement:
  209. m_valueStack.push_back(ParseValueStackEntry(QVariant::Map, key));
  210. break;
  211. default:
  212. break;
  213. }
  214. return false;
  215. }
  216. bool ParseContext::handleEndElement(const QStringRef &name)
  217. {
  218. const Element e = element(name);
  219. if (ParseContext::isValueElement(e)) {
  220. QTC_ASSERT(!m_valueStack.isEmpty(), return true; )
  221. const ParseValueStackEntry top = m_valueStack.pop();
  222. if (m_valueStack.isEmpty()) { // Last element? -> Done with that variable.
  223. QTC_ASSERT(!m_currentVariableName.isEmpty(), return true; )
  224. m_result.insert(m_currentVariableName, top.value());
  225. m_currentVariableName.clear();
  226. return false;
  227. }
  228. m_valueStack.top().addChild(top.key, top.value());
  229. }
  230. return e == QtCreatorElement;
  231. }
  232. ParseContext::Element ParseContext::element(const QStringRef &r) const
  233. {
  234. if (r == valueElement)
  235. return SimpleValueElement;
  236. if (r == valueListElement)
  237. return ListValueElement;
  238. if (r == valueMapElement)
  239. return MapValueElement;
  240. if (r == qtCreatorElement)
  241. return QtCreatorElement;
  242. if (r == dataElement)
  243. return DataElement;
  244. if (r == variableElement)
  245. return VariableElement;
  246. return UnknownElement;
  247. }
  248. QVariant ParseContext::readSimpleValue(QXmlStreamReader &r, const QXmlStreamAttributes &attributes) const
  249. {
  250. // Simple value
  251. const QString type = attributes.value(typeAttribute).toString();
  252. const QString text = r.readElementText();
  253. if (type == QLatin1String("QChar")) { // Workaround: QTBUG-12345
  254. QTC_ASSERT(text.size() == 1, return QVariant(); )
  255. return QVariant(QChar(text.at(0)));
  256. }
  257. QVariant value;
  258. value.setValue(text);
  259. value.convert(QVariant::nameToType(type.toLatin1().data()));
  260. return value;
  261. }
  262. // =================================== PersistentSettingsReader
  263. PersistentSettingsReader::PersistentSettingsReader()
  264. {
  265. }
  266. QVariant PersistentSettingsReader::restoreValue(const QString &variable) const
  267. {
  268. if (m_valueMap.contains(variable))
  269. return m_valueMap.value(variable);
  270. return QVariant();
  271. }
  272. QVariantMap PersistentSettingsReader::restoreValues() const
  273. {
  274. return m_valueMap;
  275. }
  276. bool PersistentSettingsReader::load(const QString &fileName)
  277. {
  278. m_valueMap.clear();
  279. QFile file(fileName);
  280. if (!file.open(QIODevice::ReadOnly|QIODevice::Text))
  281. return false;
  282. ParseContext ctx;
  283. m_valueMap = ctx.parse(file);
  284. file.close();
  285. return true;
  286. }
  287. /*!
  288. \class Utils::PersistentSettingsWriter
  289. \brief Serializes a QVariantMap of arbitrary, nested data structures to a XML file.
  290. \sa Utils::PersistentSettingsReader
  291. */
  292. PersistentSettingsWriter::PersistentSettingsWriter()
  293. {
  294. }
  295. static void writeVariantValue(QXmlStreamWriter &w, const Context &ctx,
  296. const QVariant &variant, const QString &key = QString())
  297. {
  298. switch (variant.type()) {
  299. case QVariant::StringList:
  300. case QVariant::List:
  301. w.writeStartElement(ctx.valueListElement);
  302. w.writeAttribute(ctx.typeAttribute, QLatin1String(QVariant::typeToName(QVariant::List)));
  303. if (!key.isEmpty())
  304. w.writeAttribute(ctx.keyAttribute, key);
  305. foreach (const QVariant &var, variant.toList())
  306. writeVariantValue(w, ctx, var);
  307. w.writeEndElement();
  308. break;
  309. case QVariant::Map: {
  310. w.writeStartElement(ctx.valueMapElement);
  311. w.writeAttribute(ctx.typeAttribute, QLatin1String(QVariant::typeToName(QVariant::Map)));
  312. if (!key.isEmpty())
  313. w.writeAttribute(ctx.keyAttribute, key);
  314. const QVariantMap varMap = variant.toMap();
  315. const QVariantMap::const_iterator cend = varMap.constEnd();
  316. for (QVariantMap::const_iterator i = varMap.constBegin(); i != cend; ++i)
  317. writeVariantValue(w, ctx, i.value(), i.key());
  318. w.writeEndElement();
  319. }
  320. break;
  321. default:
  322. w.writeStartElement(ctx.valueElement);
  323. w.writeAttribute(ctx.typeAttribute, QLatin1String(variant.typeName()));
  324. if (!key.isEmpty())
  325. w.writeAttribute(ctx.keyAttribute, key);
  326. w.writeCharacters(variant.toString());
  327. w.writeEndElement();
  328. break;
  329. }
  330. }
  331. void PersistentSettingsWriter::saveValue(const QString &variable, const QVariant &value)
  332. {
  333. m_valueMap.insert(variable, value);
  334. }
  335. bool PersistentSettingsWriter::save(const QString &fileName, const QString &docType,
  336. QWidget *parent) const
  337. {
  338. Utils::FileSaver saver(fileName, QIODevice::Text);
  339. if (!saver.hasError()) {
  340. const Context ctx;
  341. QXmlStreamWriter w(saver.file());
  342. w.setAutoFormatting(true);
  343. w.setAutoFormattingIndent(1); // Historical, used to be QDom.
  344. w.writeStartDocument();
  345. w.writeDTD(QLatin1String("<!DOCTYPE ") + docType + QLatin1Char('>'));
  346. w.writeComment(QString::fromAscii(" Written by Qt Creator %1, %2. ").
  347. arg(QLatin1String(Core::Constants::IDE_VERSION_LONG),
  348. QDateTime::currentDateTime().toString(Qt::ISODate)));
  349. w.writeStartElement(ctx.qtCreatorElement);
  350. const QVariantMap::const_iterator cend = m_valueMap.constEnd();
  351. for (QVariantMap::const_iterator it = m_valueMap.constBegin(); it != cend; ++it) {
  352. w.writeStartElement(ctx.dataElement);
  353. w.writeTextElement(ctx.variableElement, it.key());
  354. writeVariantValue(w, ctx, it.value());
  355. w.writeEndElement();
  356. }
  357. w.writeEndDocument();
  358. saver.setResult(&w);
  359. }
  360. return saver.finalize(parent);
  361. }
  362. } // namespace Utils