diff options
| author | Yuhang Zhao <2546789017@qq.com> | 2022-08-24 15:25:36 +0800 |
|---|---|---|
| committer | Yuhang Zhao <2546789017@qq.com> | 2022-09-29 21:31:17 +0800 |
| commit | e7c1fec763f3113b45e2b3b9b67392cbd06cb37c (patch) | |
| tree | 259601cfd2a33d75db9ea287e5181cfed47ac6bf /src | |
| parent | cd62ba232a4a6ee349ea983179dd8b85ccdf89d3 (diff) | |
Move Settings out of Qt.labs module
Move Settings from the Qt.labs module to the QtCore module.
And deprecate the original one in Qt.labs.
Also changed the fileName(QString) property to location(QUrl)
to better fit the Qt API.
Adjust the tests accordingly.
Task-number: QTBUG-92806
Change-Id: I1cbad1315383a9f2963583fd4d00cf3612f99f1e
Reviewed-by: Shawn Rutledge <shawn.rutledge@qt.io>
Diffstat (limited to 'src')
| -rw-r--r-- | src/core/CMakeLists.txt | 2 | ||||
| -rw-r--r-- | src/core/qqmlsettings.cpp | 489 | ||||
| -rw-r--r-- | src/core/qqmlsettings_p.h | 72 | ||||
| -rw-r--r-- | src/labs/settings/qqmlsettings.cpp | 7 | ||||
| -rw-r--r-- | src/quicktemplates2/qquicksplitview.cpp | 6 |
5 files changed, 572 insertions, 4 deletions
diff --git a/src/core/CMakeLists.txt b/src/core/CMakeLists.txt index 6387cbde77..fb6f15ffec 100644 --- a/src/core/CMakeLists.txt +++ b/src/core/CMakeLists.txt @@ -15,6 +15,8 @@ qt_internal_add_qml_module(QmlCore qqmlstandardpaths_p.h qqmlstandardpaths.cpp qqmlcoreglobal_p.h + qqmlsettings_p.h + qqmlsettings.cpp DEFINES QT_BUILD_QML_CORE_LIB PUBLIC_LIBRARIES diff --git a/src/core/qqmlsettings.cpp b/src/core/qqmlsettings.cpp new file mode 100644 index 0000000000..38352c2141 --- /dev/null +++ b/src/core/qqmlsettings.cpp @@ -0,0 +1,489 @@ +// Copyright (C) 2022 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#include "qqmlsettings_p.h" +#include <qcoreevent.h> +#include <qcoreapplication.h> +#include <qloggingcategory.h> +#include <qsettings.h> +#include <qpointer.h> +#include <qjsvalue.h> +#include <qqmlinfo.h> +#include <qdebug.h> +#include <qhash.h> + +QT_BEGIN_NAMESPACE + +/*! + \qmltype Settings +//! \instantiates QQmlSettings + \inherits QtObject + \inqmlmodule QtCore + \since 6.5 + \brief Provides persistent platform-independent application settings. + + The Settings type provides persistent platform-independent application settings. + + Users normally expect an application to remember its settings (window sizes + and positions, options, etc.) across sessions. The Settings type enables you + to save and restore such application settings with the minimum of effort. + + Individual setting values are specified by declaring properties within a + Settings element. Only value types recognized by QSettings are supported. + The recommended approach is to use property aliases in order + to get automatic property updates both ways. The following example shows + how to use Settings to store and restore the geometry of a window. + + \qml + import QtCore + import QtQuick + + Window { + id: window + + width: 800 + height: 600 + + Settings { + property alias x: window.x + property alias y: window.y + property alias width: window.width + property alias height: window.height + } + } + \endqml + + At first application startup, the window gets default dimensions specified + as 800x600. Notice that no default position is specified - we let the window + manager handle that. Later when the window geometry changes, new values will + be automatically stored to the persistent settings. The second application + run will get initial values from the persistent settings, bringing the window + back to the previous position and size. + + A fully declarative syntax, achieved by using property aliases, comes at the + cost of storing persistent settings whenever the values of aliased properties + change. Normal properties can be used to gain more fine-grained control over + storing the persistent settings. The following example illustrates how to save + a setting on component destruction. + + \qml + import QtCore + import QtQuick + + Item { + id: page + + state: settings.state + + states: [ + State { + name: "active" + // ... + }, + State { + name: "inactive" + // ... + } + ] + + Settings { + id: settings + property string state: "active" + } + + Component.onDestruction: { + settings.state = page.state + } + } + \endqml + + Notice how the default value is now specified in the persistent setting property, + and the actual property is bound to the setting in order to get the initial value + from the persistent settings. + + \section1 Application Identifiers + + Application specific settings are identified by providing application + \l {QCoreApplication::applicationName}{name}, + \l {QCoreApplication::organizationName}{organization} and + \l {QCoreApplication::organizationDomain}{domain}, or by specifying + \l location. + + \code + #include <QGuiApplication> + #include <QQmlApplicationEngine> + + int main(int argc, char *argv[]) + { + QGuiApplication app(argc, argv); + app.setOrganizationName("Some Company"); + app.setOrganizationDomain("somecompany.com"); + app.setApplicationName("Amazing Application"); + + QQmlApplicationEngine engine("main.qml"); + return app.exec(); + } + \endcode + + These are typically specified in C++ in the beginning of \c main(), + but can also be controlled in QML via the following properties: + \list + \li \l {Qt::application}{Qt.application.name}, + \li \l {Qt::application}{Qt.application.organization} and + \li \l {Qt::application}{Qt.application.domain}. + \endlist + + \section1 Categories + + Application settings may be divided into logical categories by specifying + a category name via the \l category property. Using logical categories not + only provides a cleaner settings structure, but also prevents possible + conflicts between setting keys. + + If several categories are required, use several Settings objects, each with + their own category: + + \qml + Item { + id: panel + + visible: true + + Settings { + category: "OutputPanel" + property alias visible: panel.visible + // ... + } + + Settings { + category: "General" + property alias fontSize: fontSizeSpinBox.value + // ... + } + } + \endqml + + Instead of ensuring that all settings in the application have unique names, + the settings can be divided into unique categories that may then contain + settings using the same names that are used in other categories - without + a conflict. + + \section1 Notes + + The current implementation is based on \l QSettings. This imposes certain + limitations, such as missing change notifications. Writing a setting value + using one instance of Settings does not update the value in another Settings + instance, even if they are referring to the same setting in the same category. + + The information is stored in the system registry on Windows, and in XML + preferences files on \macos. On other Unix systems, in the absence of a + standard, INI text files are used. See \l QSettings documentation for + more details. + + \sa QSettings +*/ + +using namespace Qt::StringLiterals; + +Q_LOGGING_CATEGORY(lcQmlSettings, "qt.core.settings") + +static constexpr const int settingsWriteDelay = 500; + +class QQmlSettingsPrivate +{ + Q_DISABLE_COPY_MOVE(QQmlSettingsPrivate) + Q_DECLARE_PUBLIC(QQmlSettings) + +public: + QQmlSettingsPrivate() = default; + ~QQmlSettingsPrivate() = default; + + QSettings *instance() const; + + void init(); + void reset(); + + void load(); + void store(); + + void _q_propertyChanged(); + QVariant readProperty(const QMetaProperty &property) const; + + QQmlSettings *q_ptr = nullptr; + int timerId = 0; + bool initialized = false; + QString category = {}; + QUrl location = {}; + mutable QPointer<QSettings> settings = nullptr; + QHash<const char *, QVariant> changedProperties = {}; +}; + +QSettings *QQmlSettingsPrivate::instance() const +{ + if (settings) + return settings; + + QQmlSettings *q = const_cast<QQmlSettings *>(q_func()); + settings = location.isLocalFile() ? new QSettings(location.toLocalFile(), QSettings::IniFormat, q) : new QSettings(q); + + if (settings->status() != QSettings::NoError) { + // TODO: can't print out the enum due to the following error: + // error: C2666: 'QQmlInfo::operator <<': 15 overloads have similar conversions + qmlWarning(q) << "Failed to initialize QSettings instance. Status code is: " << int(settings->status()); + + if (settings->status() == QSettings::AccessError) { + QStringList missingIdentifiers = {}; + if (QCoreApplication::organizationName().isEmpty()) + missingIdentifiers.append(u"organizationName"_s); + if (QCoreApplication::organizationDomain().isEmpty()) + missingIdentifiers.append(u"organizationDomain"_s); + if (QCoreApplication::applicationName().isEmpty()) + missingIdentifiers.append(u"applicationName"_s); + + if (!missingIdentifiers.isEmpty()) + qmlWarning(q) << "The following application identifiers have not been set: " << missingIdentifiers; + } + + return settings; + } + + if (!category.isEmpty()) + settings->beginGroup(category); + + if (initialized) + q->d_func()->load(); + + return settings; +} + +void QQmlSettingsPrivate::init() +{ + if (initialized) + return; + load(); + initialized = true; + qCDebug(lcQmlSettings) << "QQmlSettings: stored at" << instance()->fileName(); +} + +void QQmlSettingsPrivate::reset() +{ + if (initialized && settings && !changedProperties.isEmpty()) + store(); + delete settings; +} + +void QQmlSettingsPrivate::load() +{ + Q_Q(QQmlSettings); + const QMetaObject *mo = q->metaObject(); + const int offset = mo->propertyOffset(); + const int count = mo->propertyCount(); + + // don't save built-in properties if there aren't any qml properties + if (offset == 1) + return; + + for (int i = offset; i < count; ++i) { + QMetaProperty property = mo->property(i); + const QString propertyName = QString::fromUtf8(property.name()); + + const QVariant previousValue = readProperty(property); + const QVariant currentValue = instance()->value(propertyName, + previousValue); + + if (!currentValue.isNull() && (!previousValue.isValid() + || (currentValue.canConvert(previousValue.metaType()) + && previousValue != currentValue))) { + property.write(q, currentValue); + qCDebug(lcQmlSettings) << "QQmlSettings: load" << property.name() << "setting:" << currentValue << "default:" << previousValue; + } + + // ensure that a non-existent setting gets written + // even if the property wouldn't change later + if (!instance()->contains(propertyName)) + _q_propertyChanged(); + + // setup change notifications on first load + if (!initialized && property.hasNotifySignal()) { + static const int propertyChangedIndex = mo->indexOfSlot("_q_propertyChanged()"); + QMetaObject::connect(q, property.notifySignalIndex(), q, propertyChangedIndex); + } + } +} + +void QQmlSettingsPrivate::store() +{ + QHash<const char *, QVariant>::const_iterator it = changedProperties.constBegin(); + while (it != changedProperties.constEnd()) { + instance()->setValue(QString::fromUtf8(it.key()), it.value()); + qCDebug(lcQmlSettings) << "QQmlSettings: store" << it.key() << ":" << it.value(); + ++it; + } + changedProperties.clear(); +} + +void QQmlSettingsPrivate::_q_propertyChanged() +{ + Q_Q(QQmlSettings); + const QMetaObject *mo = q->metaObject(); + const int offset = mo->propertyOffset(); + const int count = mo->propertyCount(); + for (int i = offset; i < count; ++i) { + const QMetaProperty &property = mo->property(i); + const QVariant value = readProperty(property); + changedProperties.insert(property.name(), value); + qCDebug(lcQmlSettings) << "QQmlSettings: cache" << property.name() << ":" << value; + } + if (timerId != 0) + q->killTimer(timerId); + timerId = q->startTimer(settingsWriteDelay); +} + +QVariant QQmlSettingsPrivate::readProperty(const QMetaProperty &property) const +{ + Q_Q(const QQmlSettings); + QVariant var = property.read(q); + if (var.metaType() == QMetaType::fromType<QJSValue>()) + var = var.value<QJSValue>().toVariant(); + return var; +} + +QQmlSettings::QQmlSettings(QObject *parent) + : QObject(parent), d_ptr(new QQmlSettingsPrivate) +{ + Q_D(QQmlSettings); + d->q_ptr = this; +} + +QQmlSettings::~QQmlSettings() +{ + Q_D(QQmlSettings); + d->reset(); // flush pending changes +} + +/*! + \qmlproperty string Settings::category + + This property holds the name of the settings category. + + Categories can be used to group related settings together. +*/ +QString QQmlSettings::category() const +{ + Q_D(const QQmlSettings); + return d->category; +} + +void QQmlSettings::setCategory(const QString &category) +{ + Q_D(QQmlSettings); + if (d->category == category) + return; + d->reset(); + d->category = category; + if (d->initialized) + d->load(); + Q_EMIT categoryChanged(category); +} + +/*! + \qmlproperty url Settings::location + + This property holds the path to the settings file. If the file doesn't + already exist, it will be created. + + If this property is empty (the default), then QSettings::defaultFormat() + will be used. Otherwise, QSettings::IniFormat will be used. + + \sa QSettings::fileName, QSettings::defaultFormat, QSettings::IniFormat +*/ +QUrl QQmlSettings::location() const +{ + Q_D(const QQmlSettings); + return d->location; +} + +void QQmlSettings::setLocation(const QUrl &location) +{ + Q_D(QQmlSettings); + if (d->location == location) + return; + d->reset(); + d->location = location; + if (d->initialized) + d->load(); + Q_EMIT locationChanged(location); +} + +/*! + \qmlmethod var Settings::value(string key, var defaultValue) + + Returns the value for setting \a key. If the setting doesn't exist, + returns \a defaultValue. + + \sa QSettings::value +*/ +QVariant QQmlSettings::value(const QString &key, const QVariant &defaultValue) const +{ + Q_D(const QQmlSettings); + return d->instance()->value(key, defaultValue); +} + +/*! + \qmlmethod Settings::setValue(string key, var value) + + Sets the value of setting \a key to \a value. If the key already exists, + the previous value is overwritten. + + \sa QSettings::setValue +*/ +void QQmlSettings::setValue(const QString &key, const QVariant &value) +{ + Q_D(const QQmlSettings); + d->instance()->setValue(key, value); + qCDebug(lcQmlSettings) << "QQmlSettings: setValue" << key << ":" << value; +} + +/*! + \qmlmethod Settings::sync() + + Writes any unsaved changes to permanent storage, and reloads any + settings that have been changed in the meantime by another + application. + + This function is called automatically from QSettings's destructor and + by the event loop at regular intervals, so you normally don't need to + call it yourself. + + \sa QSettings::sync +*/ +void QQmlSettings::sync() +{ + Q_D(QQmlSettings); + d->instance()->sync(); +} + +void QQmlSettings::classBegin() +{ +} + +void QQmlSettings::componentComplete() +{ + Q_D(QQmlSettings); + d->init(); +} + +void QQmlSettings::timerEvent(QTimerEvent *event) +{ + Q_D(QQmlSettings); + QObject::timerEvent(event); + if (event->timerId() != d->timerId) + return; + killTimer(d->timerId); + d->timerId = 0; + d->store(); +} + +QT_END_NAMESPACE + +#include "moc_qqmlsettings_p.cpp" diff --git a/src/core/qqmlsettings_p.h b/src/core/qqmlsettings_p.h new file mode 100644 index 0000000000..90d664efaf --- /dev/null +++ b/src/core/qqmlsettings_p.h @@ -0,0 +1,72 @@ +// Copyright (C) 2022 The Qt Company Ltd. +// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only + +#ifndef QQMLSETTINGS_P_H +#define QQMLSETTINGS_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include <QtCore/qobject.h> +#include <QtCore/qvariant.h> +#include <QtCore/qurl.h> +#include <QtQml/qqml.h> +#include <QtQml/qqmlparserstatus.h> +#include <QtQmlCore/private/qqmlcoreglobal_p.h> + +QT_BEGIN_NAMESPACE + +class QQmlSettingsPrivate; + +class Q_QMLCORE_PRIVATE_EXPORT QQmlSettings : public QObject, public QQmlParserStatus +{ + Q_OBJECT + Q_INTERFACES(QQmlParserStatus) + Q_DECLARE_PRIVATE(QQmlSettings) + QML_NAMED_ELEMENT(Settings) + QML_ADDED_IN_VERSION(6, 5) + + Q_PROPERTY(QString category READ category WRITE setCategory NOTIFY categoryChanged FINAL) + Q_PROPERTY(QUrl location READ location WRITE setLocation NOTIFY locationChanged FINAL) + +public: + explicit QQmlSettings(QObject *parent = nullptr); + ~QQmlSettings() override; + + QString category() const; + void setCategory(const QString &category); + + QUrl location() const; + void setLocation(const QUrl &location); + + Q_INVOKABLE QVariant value(const QString &key, const QVariant &defaultValue = {}) const; + Q_INVOKABLE void setValue(const QString &key, const QVariant &value); + Q_INVOKABLE void sync(); + +Q_SIGNALS: + void categoryChanged(const QString &arg); + void locationChanged(const QUrl &arg); + +protected: + void timerEvent(QTimerEvent *event) override; + + void classBegin() override; + void componentComplete() override; + +private: + QScopedPointer<QQmlSettingsPrivate> d_ptr; + + Q_PRIVATE_SLOT(d_func(), void _q_propertyChanged()) +}; + +QT_END_NAMESPACE + +#endif // QQMLSETTINGS_P_H diff --git a/src/labs/settings/qqmlsettings.cpp b/src/labs/settings/qqmlsettings.cpp index a964f4dbdc..fe0fa831d2 100644 --- a/src/labs/settings/qqmlsettings.cpp +++ b/src/labs/settings/qqmlsettings.cpp @@ -18,6 +18,7 @@ QT_BEGIN_NAMESPACE \qmlmodule Qt.labs.settings 1.0 \title Qt Labs Settings QML Types \ingroup qmlmodules + \deprecated [6.5] Use \l {QtQmlCore::}{Settings} from Qt QML Core instead. \brief Provides persistent platform-independent application settings. To use this module, import the module with the following line: @@ -32,6 +33,7 @@ QT_BEGIN_NAMESPACE //! \instantiates QQmlSettings \inqmlmodule Qt.labs.settings \ingroup settings + \deprecated [6.5] Use \l {QtQmlCore::}{Settings} from Qt QML Core instead. \brief Provides persistent platform-independent application settings. The Settings type provides persistent platform-independent application settings. @@ -196,7 +198,7 @@ QT_BEGIN_NAMESPACE standard, INI text files are used. See \l QSettings documentation for more details. - \sa QSettings + \sa {QtQmlCore::}{Settings}, QSettings */ Q_LOGGING_CATEGORY(lcSettings, "qt.labs.settings") @@ -481,6 +483,9 @@ void QQmlSettings::componentComplete() { Q_D(QQmlSettings); d->init(); + qmlWarning(this) << "The Settings type from Qt.labs.settings is deprecated" + " and will be removed in a future release. Please use " + "the one from QtCore instead."; } void QQmlSettings::timerEvent(QTimerEvent *event) diff --git a/src/quicktemplates2/qquicksplitview.cpp b/src/quicktemplates2/qquicksplitview.cpp index 7f6a86f116..2ca9923860 100644 --- a/src/quicktemplates2/qquicksplitview.cpp +++ b/src/quicktemplates2/qquicksplitview.cpp @@ -1,4 +1,4 @@ -// Copyright (C) 2018 The Qt Company Ltd. +// Copyright (C) 2022 The Qt Company Ltd. // SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only #include "qquicksplitview_p.h" @@ -173,8 +173,8 @@ QT_BEGIN_NAMESPACE serialized using the \l saveState() and \l restoreState() functions: \qml + import QtCore import QtQuick.Controls - import Qt.labs.settings ApplicationWindow { // ... @@ -198,8 +198,8 @@ QT_BEGIN_NAMESPACE functions of \l Settings can be used: \qml + import QtCore import QtQuick.Controls - import Qt.labs.settings ApplicationWindow { // ... |
