1/****************************************************************************
2**
3** Copyright (C) 2016 The Qt Company Ltd.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the examples of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:BSD$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** BSD License Usage
18** Alternatively, you may use this file under the terms of the BSD license
19** as follows:
20**
21** "Redistribution and use in source and binary forms, with or without
22** modification, are permitted provided that the following conditions are
23** met:
24** * Redistributions of source code must retain the above copyright
25** notice, this list of conditions and the following disclaimer.
26** * Redistributions in binary form must reproduce the above copyright
27** notice, this list of conditions and the following disclaimer in
28** the documentation and/or other materials provided with the
29** distribution.
30** * Neither the name of The Qt Company Ltd nor the names of its
31** contributors may be used to endorse or promote products derived
32** from this software without specific prior written permission.
33**
34**
35** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
36** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
37** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
38** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
39** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
45** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
46**
47** $QT_END_LICENSE$
48**
49****************************************************************************/
50
51#include "settingstree.h"
52#include "variantdelegate.h"
53
54#include <QApplication>
55#include <QHeaderView>
56#include <QScreen>
57#include <QSettings>
58
59SettingsTree::SettingsTree(QWidget *parent)
60 : QTreeWidget(parent),
61 m_typeChecker(new TypeChecker)
62{
63 setItemDelegate(new VariantDelegate(m_typeChecker, this));
64
65 setHeaderLabels({tr("Setting"), tr("Type"), tr("Value")});
66 header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
67 header()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
68 header()->setSectionResizeMode(2, QHeaderView::Stretch);
69
70 refreshTimer.setInterval(2000);
71
72 groupIcon.addPixmap(style()->standardPixmap(QStyle::SP_DirClosedIcon),
73 QIcon::Normal, QIcon::Off);
74 groupIcon.addPixmap(style()->standardPixmap(QStyle::SP_DirOpenIcon),
75 QIcon::Normal, QIcon::On);
76 keyIcon.addPixmap(style()->standardPixmap(QStyle::SP_FileIcon));
77
78 connect(&refreshTimer, &QTimer::timeout, this, &SettingsTree::maybeRefresh);
79}
80
81SettingsTree::~SettingsTree() = default;
82
83void SettingsTree::setSettingsObject(const SettingsPtr &newSettings)
84{
85 settings = newSettings;
86 clear();
87
88 if (settings.isNull()) {
89 refreshTimer.stop();
90 } else {
91 refresh();
92 if (autoRefresh)
93 refreshTimer.start();
94 }
95}
96
97QSize SettingsTree::sizeHint() const
98{
99 const QRect availableGeometry = screen()->availableGeometry();
100 return QSize(availableGeometry.width() * 2 / 3, availableGeometry.height() * 2 / 3);
101}
102
103void SettingsTree::setAutoRefresh(bool autoRefresh)
104{
105 this->autoRefresh = autoRefresh;
106 if (!settings.isNull()) {
107 if (autoRefresh) {
108 maybeRefresh();
109 refreshTimer.start();
110 } else {
111 refreshTimer.stop();
112 }
113 }
114}
115
116void SettingsTree::setFallbacksEnabled(bool enabled)
117{
118 if (!settings.isNull()) {
119 settings->setFallbacksEnabled(enabled);
120 refresh();
121 }
122}
123
124void SettingsTree::maybeRefresh()
125{
126 if (state() != EditingState)
127 refresh();
128}
129
130void SettingsTree::refresh()
131{
132 if (settings.isNull())
133 return;
134
135 disconnect(this, &QTreeWidget::itemChanged,
136 this, &SettingsTree::updateSetting);
137
138 settings->sync();
139 updateChildItems(nullptr);
140
141 connect(this, &QTreeWidget::itemChanged,
142 this, &SettingsTree::updateSetting);
143}
144
145bool SettingsTree::event(QEvent *event)
146{
147 if (event->type() == QEvent::WindowActivate) {
148 if (isActiveWindow() && autoRefresh)
149 maybeRefresh();
150 }
151 return QTreeWidget::event(event);
152}
153
154void SettingsTree::updateSetting(QTreeWidgetItem *item)
155{
156 QString key = item->text(0);
157 QTreeWidgetItem *ancestor = item->parent();
158 while (ancestor) {
159 key.prepend(ancestor->text(0) + QLatin1Char('/'));
160 ancestor = ancestor->parent();
161 }
162
163 settings->setValue(key, item->data(2, Qt::UserRole));
164 if (autoRefresh)
165 refresh();
166}
167
168void SettingsTree::updateChildItems(QTreeWidgetItem *parent)
169{
170 int dividerIndex = 0;
171
172 const QStringList childGroups = settings->childGroups();
173 for (const QString &group : childGroups) {
174 QTreeWidgetItem *child;
175 int childIndex = findChild(parent, group, dividerIndex);
176 if (childIndex != -1) {
177 child = childAt(parent, childIndex);
178 child->setText(1, QString());
179 child->setText(2, QString());
180 child->setData(2, Qt::UserRole, QVariant());
181 moveItemForward(parent, childIndex, dividerIndex);
182 } else {
183 child = createItem(group, parent, dividerIndex);
184 }
185 child->setIcon(0, groupIcon);
186 ++dividerIndex;
187
188 settings->beginGroup(group);
189 updateChildItems(child);
190 settings->endGroup();
191 }
192
193 const QStringList childKeys = settings->childKeys();
194 for (const QString &key : childKeys) {
195 QTreeWidgetItem *child;
196 int childIndex = findChild(parent, key, 0);
197
198 if (childIndex == -1 || childIndex >= dividerIndex) {
199 if (childIndex != -1) {
200 child = childAt(parent, childIndex);
201 for (int i = 0; i < child->childCount(); ++i)
202 delete childAt(child, i);
203 moveItemForward(parent, childIndex, dividerIndex);
204 } else {
205 child = createItem(key, parent, dividerIndex);
206 }
207 child->setIcon(0, keyIcon);
208 ++dividerIndex;
209 } else {
210 child = childAt(parent, childIndex);
211 }
212
213 QVariant value = settings->value(key);
214 if (value.userType() == QMetaType::UnknownType) {
215 child->setText(1, "Invalid");
216 } else {
217 if (value.type() == QVariant::String) {
218 const QString stringValue = value.toString();
219 if (m_typeChecker->boolExp.match(stringValue).hasMatch()) {
220 value.setValue(stringValue.compare("true", Qt::CaseInsensitive) == 0);
221 } else if (m_typeChecker->signedIntegerExp.match(stringValue).hasMatch())
222 value.setValue(stringValue.toInt());
223 }
224
225 child->setText(1, value.typeName());
226 }
227 child->setText(2, VariantDelegate::displayText(value));
228 child->setData(2, Qt::UserRole, value);
229 }
230
231 while (dividerIndex < childCount(parent))
232 delete childAt(parent, dividerIndex);
233}
234
235QTreeWidgetItem *SettingsTree::createItem(const QString &text,
236 QTreeWidgetItem *parent, int index)
237{
238 QTreeWidgetItem *after = nullptr;
239 if (index != 0)
240 after = childAt(parent, index - 1);
241
242 QTreeWidgetItem *item;
243 if (parent)
244 item = new QTreeWidgetItem(parent, after);
245 else
246 item = new QTreeWidgetItem(this, after);
247
248 item->setText(0, text);
249 item->setFlags(item->flags() | Qt::ItemIsEditable);
250 return item;
251}
252
253QTreeWidgetItem *SettingsTree::childAt(QTreeWidgetItem *parent, int index) const
254{
255 return (parent ? parent->child(index) : topLevelItem(index));
256}
257
258int SettingsTree::childCount(QTreeWidgetItem *parent) const
259{
260 return (parent ? parent->childCount() : topLevelItemCount());
261}
262
263int SettingsTree::findChild(QTreeWidgetItem *parent, const QString &text,
264 int startIndex) const
265{
266 for (int i = startIndex; i < childCount(parent); ++i) {
267 if (childAt(parent, i)->text(0) == text)
268 return i;
269 }
270 return -1;
271}
272
273void SettingsTree::moveItemForward(QTreeWidgetItem *parent, int oldIndex,
274 int newIndex)
275{
276 for (int i = 0; i < oldIndex - newIndex; ++i)
277 delete childAt(parent, newIndex);
278}
279