-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathdconfigfile.cpp
More file actions
1538 lines (1293 loc) · 46.5 KB
/
Copy pathdconfigfile.cpp
File metadata and controls
1538 lines (1293 loc) · 46.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2021 - 2026 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: LGPL-3.0-or-later
#include "dconfigfile.h"
#include "dobject_p.h"
#include "filesystem/dstandardpaths.h"
#include <QFile>
#include <QJsonDocument>
#include <QLoggingCategory>
#include <QJsonObject>
#include <QJsonArray>
#include <QCoreApplication>
#include <QVariant>
#include <QDebug>
#include <QFileInfo>
#include <QDir>
#include <QDirIterator>
#include <QCollator>
#include <QDateTime>
#include <unistd.h>
#include <pwd.h>
// https://gitlabwh.uniontech.com/wuhan/se/deepin-specifications/-/issues/3
DCORE_BEGIN_NAMESPACE
#ifndef QT_DEBUG
Q_LOGGING_CATEGORY(cfLog, "dtk.dsg.config" , QtInfoMsg);
#else
Q_LOGGING_CATEGORY(cfLog, "dtk.dsg.config");
#endif
#define FILE_SUFFIX QLatin1String(".json")
// subpath must be a subdirectory of the dir.
inline static bool subpathIsValid(const QString &subpath, const QDir &dir)
{
if (subpath.isEmpty())
return true;
if (!subpath.startsWith(QLatin1Char('/')))
return false;
const QDir subDir(dir.filePath(subpath.mid(1)));
return subDir.absolutePath().startsWith(dir.absolutePath());
}
// name must be a valid filename.
inline static bool isValidFilename(const QString& filename)
{
static const QRegularExpression regex("^[\\w\\-\\.\\ ]+$");
QRegularExpressionMatch match = regex.match(filename);
return match.hasMatch();
}
// AppId don't contain ' ', but it can be empty.
inline static bool isValidAppId(const QString& appId)
{
static const QRegularExpression regex("^[\\w\\-\\.]*$");
QRegularExpressionMatch match = regex.match(appId);
return match.hasMatch();
}
/*!
@~english
\internal
@brief 按子目录查找机制查找配置文件
在 \a baseDir目录下,查找名称为 \a name的文件,
若存在 \a subpath,则从 \a subpath叶子目录逐级向上查找名称为 \a name的文件,
若不存在此文件,则返回无效路径.
*/
inline QString getFile(const QString &baseDir, const QString &subpath, const QString &name,
bool canFallbackUp = true) {
qCDebug(cfLog, "load json file from base dir:\"%s\", subpath = \"%s\", file name =\"%s\".",
qPrintable(baseDir), qPrintable(subpath), qPrintable(name));
const QDir base_dir(baseDir);
if (!subpathIsValid(subpath, base_dir)) {
qCDebug(cfLog, "subpath is invalid in the base dir:\"%s\", subpath:\"%s\".", qPrintable(baseDir), qPrintable(subpath));
return QString();
}
QDir target_dir = base_dir;
if (!subpath.isEmpty())
target_dir.cd(subpath.mid(1));
do {
qCDebug(cfLog, "load json file from: \"%s\"", qPrintable(target_dir.path()));
if (QFile::exists(target_dir.filePath(name))) {
return target_dir.filePath(name);
}
if (base_dir == target_dir)
break;
} while (canFallbackUp && target_dir.cdUp());
return QString();
}
inline QFile *loadFile(const QString &baseDir, const QString &subpath, const QString &name,
bool canFallbackUp = true)
{
QString path = getFile(baseDir, subpath, name, canFallbackUp);
if (!path.isEmpty()) {
return new QFile(path);
}
return nullptr;
}
static QJsonDocument loadJsonFile(QIODevice *data)
{
if (!data->open(QIODevice::ReadOnly)) {
if (auto file = qobject_cast<QFile*>(data)) {
qCDebug(cfLog, "Falied on open file: \"%s\", error message: \"%s\"",
qPrintable(file->fileName()), qPrintable(file->errorString()));
}
return QJsonDocument();
}
QJsonParseError error;
auto document = QJsonDocument::fromJson(data->readAll(), &error);
data->close();
if (error.error != QJsonParseError::NoError) {
qCWarning(cfLog, "%s", qPrintable(error.errorString()));
return QJsonDocument();
}
return document;
}
static DConfigFile::Version parseVersion(const QJsonObject &obj) {
DConfigFile::Version version {0, 0};
const QString &verStr = obj[QLatin1String("version")].toString();
if (verStr.isEmpty()) {
return version;
}
const QStringList &items = verStr.split(QLatin1Char('.'));
if (items.size() != 2)
return version;
bool ok = false;
quint16 major = items.first().toUShort(&ok);
if (!ok)
return version;
quint16 minor = items.last().toUShort(&ok);
if (!ok)
return version;
version.major = major;
version.minor = minor;
return version;
}
#define MAGIC_META QLatin1String("dsg.config.meta")
#define MAGIC_OVERRIDE QLatin1String("dsg.config.override")
#define MAGIC_CACHE QLatin1String("dsg.config.cache")
static const uint InvalidUID = 0xFFFF;
inline static bool checkMagic(const QJsonObject &obj, QLatin1String request) {
return obj[QLatin1String("magic")].toString() == request;
}
inline static bool versionIsValid(const DConfigFile::Version &v) {
return v.major > 0 || v.minor > 0;
}
inline static bool checkVersion(const QJsonObject &obj, const DConfigFile::Version &request) {
const DConfigFile::Version &v = parseVersion(obj);
return versionIsValid(v) && v.major == request.major;
}
inline void overrideValue(QLatin1String subkey, const QJsonValue &from, QVariantHash &target) {
const QJsonValue &v = from[subkey];
if (!v.isUndefined())
target[subkey] = v.toVariant();
}
inline static QString getUserName(const uint uid) {
passwd *pw = getpwuid(uid);
return pw ? QString::fromLocal8Bit(pw->pw_name) : QString();
}
/*!
@~english
@class Dtk::Core::DConfigFile
\inmodule dtkcore
@brief Specification configuration file implementation of the interface that the configuration file reads and writes.
*/
/*!
@~english
@enum DConfigFile::Flag
\value NoOverride When this flag exists , it indicates that this configuration item can't be overwritten (see the override mechanism below for details).
Otherwise, the absence of this flag indicates that this configuration item is allowed to be overwritten,
If it has a screen setting entry, hide or disable the screen setting entry when this entry is not writable.
\value Global When reading or writing such a configuration, the user identity is ignored and the same data is obtained regardless of which user identity the program executes.
The write operation will take effect for all users. However, if the corresponding configuration storage directory does not exist or has no write permission, this flag is ignored.
*/
/*!
@~english
@enum DConfigFile::Permissions
\value ReadOnly Overwrite the configuration item as readonly.
\value ReadWrite Overwrite the configuration item as readable and writable.
*/
/*!
@~english
@enum DConfigFile::Visibility
\value Private For internal program use only,
Not visible to the outside world. Such configuration items are completely read and written by the program itself, and can be added, deleted and rewritten at will without compatibility consideration,
\value Public External programs are available.
Once this type of configuration item is released, ensure that the configuration item is backward compatible during the upgrade of the compatible version.
In short, this type of configuration item is only allowed to be deleted or modified when a major version of the program/library is upgraded.
The configuration item is changed if any of its permissions, visibility, or flags properties are changed.
In addition, you do not need to consider compatibility when modifying the value, name, and description attributes.
*/
/*!
@~english
@struct Dtk::Core::DConfigFile::Version
\inmodule dtkcore
@brief Version Information
The content format version of this file. The version number is described by two digits,
Profiles with different first digits are incompatible with each other, and profiles with different second digits need to be compatible with each other.
A program that reads this profile needs to perform content analysis by version, and when it encounters an incompatible version, it needs to terminate parsing immediately and ignore the file.
And write a warning message to the program log, such as "1.0" and "2.0" versions are not compatible,
If the parser only supports version 1.0, it should stop parsing when it encounters a 2.0 profile.
But if version 1.1 is encountered, execution can continue.
When writing to this profile, if an incompatible version is encountered, the current contents need to be cleared before writing, and this field needs to be updated with each write
*/
DConfigMeta::~DConfigMeta() {}
QStringList DConfigMeta::genericMetaDirs(const QString &localPrefix)
{
QStringList paths;
// lower priority is higher.
for (auto item: DStandardPaths::paths(DStandardPaths::DSG::DataDir)) {
paths.prepend(QDir::cleanPath(QString("%1/%2/configs").arg(localPrefix, item)));
}
return paths;
}
QStringList DConfigMeta::applicationMetaDirs(const QString &localPrefix, const QString &appId)
{
QStringList paths;
const auto &dataPaths = genericMetaDirs(localPrefix);
paths.reserve(dataPaths.size());
for (auto item : dataPaths) {
paths << QString("%1/%2").arg(item, appId);
}
return paths;
}
Dtk::Core::DConfigCache::~DConfigCache() {}
struct DConfigKey {
DConfigKey(const QString &aappId, const QString &afileName, const QString &asubpath)
: appId(aappId),
fileName(afileName),
subpath(asubpath)
{
}
explicit DConfigKey(const DConfigKey &src)
: DConfigKey(src.appId, src.fileName, src.subpath)
{
}
DConfigKey &operator = (const DConfigKey &src)
{
this->appId = src.appId;
this->fileName = src.fileName;
this->subpath = src.subpath;
return *this;
}
QString appId;
QString fileName;
QString subpath;
};
class Q_DECL_HIDDEN DConfigInfo {
public:
DConfigInfo()
{
}
DConfigInfo(const DConfigInfo &other)
{
this->values = other.values;
}
DConfigInfo operator = (const DConfigInfo &other)
{
this->values = other.values;
return *this;
}
inline static bool checkSerial(const int metaSerial, const int cacheSerial)
{
if (cacheSerial < 0)
return true;
if (metaSerial >= 0 && metaSerial == cacheSerial)
return true;
return false;
}
DConfigFile::Visibility visibility(const QString &key) const
{
DConfigFile::Visibility p = DConfigFile::Private;
const auto &tmp = values[key][QLatin1String("visibility")].toString();
if (tmp == QLatin1String("public"))
p = DConfigFile::Public;
return p;
}
DConfigFile::Permissions permissions(const QString &key) const
{
DConfigFile::Permissions p = DConfigFile::ReadOnly;
const auto &tmp = values[key][QLatin1String("permissions")].toString();
if (tmp == QLatin1String("readwrite"))
p = DConfigFile::ReadWrite;
return p;
}
DConfigFile::Flags flags(const QString &key) const
{
DConfigFile::Flags flags = {};
const auto &tmp = values[key][QLatin1String("flags")];
Q_FOREACH(const QString &flag, tmp.toStringList()) {
if (flag == QLatin1String("nooverride")) {
flags |= DConfigFile::NoOverride;
} else if (flag == QLatin1String("global")) {
flags |= DConfigFile::Global;
} else if (flag == QLatin1String("user-public")) {
flags |= DConfigFile::UserPublic;
}
}
return flags;
}
QString displayName(const QString &key, const QLocale &locale) const
{
if (locale == QLocale::AnyLanguage)
return values[key][QLatin1String("name")].toString();
return values[key].value(QString("name[%1]")
.arg(locale.name())).toString();
}
QString description(const QString &key, const QLocale &locale) const
{
if (locale == QLocale::AnyLanguage)
return values[key][QLatin1String("description")].toString();
return values[key].value(QString("description[%1]")
.arg(locale.name())).toString();
}
inline QVariant value(const QString &key) const
{
return values[key][QLatin1String("value")];
}
inline int serial(const QString &key) const
{
bool status = false;
const int tmp = values[key][QLatin1String("serial")].toInt(&status);
if (status) {
return tmp;
}
return -1;
}
inline void setValue(const QString &key, const QVariant &value)
{
values[key]["value"] = value;
}
inline void setSerial(const QString &key, const int &value)
{
values[key]["serial"] = value;
}
inline void setTime(const QString &key, const QString &value)
{
values[key]["time"] = value;
}
inline void setUser(const QString &key, const uint &value)
{
values[key]["user"] = getUserName(value);
}
inline void setAppId(const QString &key, const QString &value)
{
values[key]["appid"] = value;
}
inline QStringList keyList() const
{
return values.keys();
}
inline bool contains(const QString &key) const
{
return values.contains(key);
}
inline void remove(const QString &key)
{
values.remove(key);
}
inline bool update(const QString &key, const QVariantHash &value)
{
if (!value.contains("value")) {
return false;
}
values[key] = value;
return true;
}
inline bool updateValue(const QString &key, const QJsonValue &value)
{
return overrideValue(key, "value", value);
}
inline void updateSerial(const QString &key, const QJsonValue &value)
{
overrideValue(key, "serial", value);
}
inline void updatePermissions(const QString &key, const QJsonValue &value)
{
overrideValue(key, "permissions", value);
}
QJsonObject content() const
{
QJsonObject contents;
for (auto i = values.constBegin(); i != values.constEnd(); ++i) {
contents[i.key()] = QJsonObject::fromVariantHash(i.value());
}
return contents;
}
private:
bool overrideValue(const QString &key, const QString &subkey, const QJsonValue &from) {
const QJsonValue &v = from[subkey];
if (v.isUndefined()) {
return false;
}
values[key][subkey] = v.toVariant();
return true;
}
QHash<QString, QVariantHash> values;
};
/*!
@~english
@class Dtk::Core::DConfigMeta
\inmodule dtkcore
@brief Provides a prototype of the configuration file and an access interface to the override mechanism.
*/
/*!
@~english
@fn DConfigFile::Version DConfigMeta::version() const = 0;
@brief Returns configuration version information.
@return
*/
/*!
@~english
@fn void DConfigMeta::setVersion(quint16 major, quint16 minor) = 0;
@brief Sets configuration version information
\a major Major version number
\a minor Minor version number
*/
/*!
@~english
@fn bool DConfigMeta::load(const QString &localPrefix = QString()) = 0;
@brief Parsing configuration files
\a localPrefix Directory prefix
@return
*/
/*!
@~english
@fn bool DConfigMeta::load(QIODevice *meta, const QList<QIODevice*> &overrides) = 0;
@brief Parse the configuration file stream
\a meta Prototype stream
\a overrides The file stream to find for the override mechanism
@return
*/
/*!
@~english
@fn QStringList DConfigMeta::keyList() const = 0;
@brief Returns all configuration items for the configuration content
@return
*/
/*!
@~english
@fn DConfigFile::Flags DConfigMeta::flags(const QString &key) const = 0;
@brief Returns the attribute of the specified configuration item
\a key Configure the name of the option, NoOverride This option can't be overridden, and Global ignores the user identity
@return
*/
/*!
@~english
@fn DConfigFile::Permissions DConfigMeta::permissions(const QString &key) const = 0;
@brief Returns the permission for the specified configuration item
\a key Configuration name
@return
*/
/*!
@~english
@fn DConfigFile::Visibility DConfigMeta::visibility(const QString &key) const = 0;
@brief Returns the visibility of the specified configuration item
\a key Configuration name
@return
*/
/*!
@~english
@fn int DConfigMeta::serial(const QString &key) const = 0;
@brief Returns a monotonically increasing value of a configuration item
\a key Configuration name
@return An invalid value of -1 indicates that the entry is not configured
*/
/*!
@~english
@fn QString DConfigMeta::displayName(const QString &key, const QLocale &locale) = 0;
@brief Returns the display name of the specified configuration
\a key Configuration name
\a locale Language version
@return
*/
/*!
@~english
@fn QString DConfigMeta::description(const QString &key, const QLocale &locale) = 0;
@brief Returns a description of the specified configuration item
\a key Configuration name
\a locale Language version
@return
*/
/*!
@~english
@fn QString DConfigMeta::metaPath(const QString &localPrefix = QString(), bool *useAppId = nullptr) const = 0;
@brief Returns the path to the profile
\a localPrefix Directory of all override mechanisms that need to be searched
@return
*/
/*!
@~english
@fn QStringList DConfigMeta::allOverrideDirs(const bool useAppId, const QString &prefix = QString()) const = 0;
@brief Gets all the override mechanism directories to look for for the \a prefix directory
\a useAppId Whether not to use the generic directory
@return
*/
/*!
@~english
@fn QVariant DConfigMeta::value(const QString &key) const = 0;
@brief Original value of meta overwritten by the overwriting mechanism
\a key Configuration name
@return
*/
class Q_DECL_HIDDEN DConfigMetaImpl : public DConfigMeta {
// DConfigMeta interface
public:
explicit DConfigMetaImpl(const DConfigKey &configKey);
virtual ~DConfigMetaImpl() override;
inline virtual QStringList keyList() const override
{
return values.keyList();
}
inline virtual DConfigFile::Flags flags(const QString &key) const override
{
return values.flags(key);
}
inline virtual DConfigFile::Permissions permissions(const QString &key) const override
{
return values.permissions(key);
}
inline virtual DConfigFile::Visibility visibility(const QString &key) const override
{
return values.visibility(key);
}
inline virtual int serial(const QString &key) const override
{
return values.serial(key);
}
inline virtual QString description(const QString &key, const QLocale &locale) override
{
return values.description(key, locale);
}
virtual DConfigFile::Version version() const override
{
return m_version;
}
inline virtual void setVersion(quint16 major, quint16 minor) override
{
m_version.major = major;
m_version.minor = minor;
}
inline virtual QString displayName(const QString &key, const QLocale &locale) override
{
return values.displayName(key, locale);
}
inline virtual QVariant value(const QString &key) const override
{
return values.value(key);
}
QString metaPath(const QString &localPrefix, bool *useAppId) const override
{
bool useAppIdForOverride = true;
QString path;
const QStringList &applicationMetas = applicationMetaDirs(localPrefix, configKey.appId);
for (auto iter = applicationMetas.rbegin(); iter != applicationMetas.rend(); iter++) {
path = getFile(*iter, configKey.subpath, configKey.fileName + FILE_SUFFIX);
if (!path.isEmpty())
break;
}
if (path.isEmpty()) {
useAppIdForOverride = false;
const QStringList &genericnMetas = genericMetaDirs(localPrefix);
for (auto iter = genericnMetas.rbegin(); iter != genericnMetas.rend(); iter++) {
path = getFile(*iter, configKey.subpath, configKey.fileName + FILE_SUFFIX);
if (!path.isEmpty())
break;
}
}
if (useAppId) {
*useAppId = useAppIdForOverride;
}
return path;
}
bool load(const QString &localPrefix) override
{
if (!isValidAppId(configKey.appId)) {
qCWarning(cfLog, "AppId is invalid, appId=%s", qPrintable(configKey.appId));
return false;
}
if (!isValidFilename(configKey.fileName)) {
qCWarning(cfLog, "Name is invalid, filename=%s", qPrintable(configKey.fileName));
return false;
}
bool useAppIdForOverride = true;
QString path = metaPath(localPrefix, &useAppIdForOverride);
if (path.isEmpty()) {
qCWarning(cfLog, "Can't load meta file from local prefix: \"%s\"", qPrintable(localPrefix));
return false;
}
qCDebug(cfLog, "Load meta file: \"%s\"", qPrintable(path));
QScopedPointer<QFile> meta(new QFile(path));
struct _ScopedPointer {
explicit _ScopedPointer(const QList<QIODevice*> &list)
: m_list(list) {}
~_ScopedPointer() {qDeleteAll(m_list);}
QList<QIODevice*> m_list;
};
_ScopedPointer overrides(loadOverrides(localPrefix, useAppIdForOverride));
return load(meta.data(), overrides.m_list);
}
bool load(QIODevice *meta, const QList<QIODevice*> &overrides) override
{
{
const QJsonDocument &doc = loadJsonFile(meta);
if (!doc.isObject())
return false;
// 检查标识
const QJsonObject &root = doc.object();
if (!checkMagic(root, MAGIC_META)) {
qCWarning(cfLog, "The meta magic does not match");
return false;
}
// 检查版本兼容性
const auto &v = parseVersion(root);
if (!versionIsValid(v) || v.major > DConfigFile::supportedVersion().major) {
qCWarning(cfLog, "The meta version number does not match, "
"the file major version=%i, supported major version<=%i",
v.major, DConfigFile::supportedVersion().major);
return false;
}
m_version = v;
const auto &contents = root[QLatin1String("contents")].toObject();
auto i = contents.constBegin();
// 初始化原始值
for (; i != contents.constEnd(); ++i) {
if (!values.update(i.key(), i.value().toObject().toVariantHash())) {
qWarning() << "key:" << i.key() << "has no value";
return false;
}
}
}
// for override
Q_FOREACH(auto override, overrides) {
const QJsonDocument &doc = loadJsonFile(override);
if (doc.isObject()) {
const QJsonObject &root = doc.object();
if (!checkMagic(root, MAGIC_OVERRIDE)) {
if (auto file = static_cast<QFile*>(override)) {
qCWarning(cfLog, "The override magic does not match, file: \"%s\", error message: \"%s\"",
qPrintable(file->fileName()), qPrintable(file->errorString()));
} else {
qCWarning(cfLog, "The override magic does not match");
}
break; //TODO don't continue parse?
}
if (!checkVersion(root, m_version)) {
qCWarning(cfLog, "The override version number does not match");
break;
}
if (auto file = static_cast<QFile*>(override)) {
qCDebug(cfLog, "The override will be applied, file: \"%s\"", qPrintable(file->fileName()));
}
const auto &contents = root[QLatin1String("contents")].toObject();
auto i = contents.constBegin();
for (; i != contents.constEnd(); ++i) {
if (!values.contains(i.key())) {
qCWarning(cfLog, "The meta doesn't contain the override key: \"%s\".", qPrintable(i.key()));
continue;
}
// 检查是否允许 override
if (values.flags(i.key()) & DConfigFile::NoOverride)
continue;
if (!values.updateValue(i.key(), i.value())) {
qWarning() << "key (override):" << i.key() << "has no value";
return false;
}
values.updateSerial(i.key(), i.value());
values.updatePermissions(i.key(), i.value());
}
}
}
return true;
}
/*!
@~english
\internal
@brief 获得前缀为 \a prefix 目录的应用或公共库的所有覆盖机制目录,越后优先级越高
*/
inline QStringList overrideDirs(const QString & prefix, bool useAppId) const {
const QString &path2 = QString("%1/etc/dsg/configs/overrides/%2/%3")
.arg(prefix, useAppId ? configKey.appId : QString(), configKey.fileName);
QStringList paths;
const QStringList &dataPaths = DStandardPaths::paths(DStandardPaths::DSG::DataDir);
paths.reserve(dataPaths.size() + 1);
for (auto path: dataPaths) {
// reverse `DataDir`'s paths, previous `DataDir`'s value has high priority
paths.prepend(QString("%1%2/configs/overrides/%3/%4")
.arg(prefix, path, useAppId ? configKey.appId : QString(), configKey.fileName));
}
// 在后面的优先级更高
paths.append(path2);
return paths;
}
inline QStringList allOverrideDirs(const bool useAppId, const QString &prefix) const override
{
QStringList dirs;
// 只有当允许不使用 appid 时才能回退到通用目录
if (!useAppId) {
dirs << overrideDirs(prefix, false);
}
// 无论如何都先从带 appid 的目录下加载override文件
// 在列表后面的更优先
dirs << overrideDirs(prefix, true);
return dirs;
}
/*!
@~english
\internal
@brief 获得所有遵守覆盖机制的文件流
在override文件放置路径下按优先级查找覆盖文件,支持子目录查找机制,
使用自然排序(如“a2”在“a11”之前)规则按文件名进行排序
*/
QList<QIODevice *> loadOverrides(const QString &prefix, bool useAppId) const
{
auto filters = QDir::Files | QDir::NoDotAndDotDot | QDir::Readable;
const QStringList nameFilters {"*" + FILE_SUFFIX};
QStringList dirs = allOverrideDirs(useAppId, prefix);
QList<QIODevice*> list;
list.reserve(50);
QCollator collator(QLocale::English);
collator.setNumericMode(true);
collator.setIgnorePunctuation(true);
Q_FOREACH(const auto &dir, dirs) {
const QDir base_dir(QDir::cleanPath(dir));
if (!base_dir.exists())
continue;
if (!subpathIsValid(configKey.subpath, base_dir))
continue;
QDir target_dir = base_dir;
target_dir.setFilter(filters);
target_dir.setNameFilters(nameFilters);
if (!configKey.subpath.isEmpty())
target_dir.cd(configKey.subpath.mid(1));
do {
qCDebug(cfLog, "load override file from: \"%s\"", qPrintable(target_dir.path()));
QDirIterator iterator(target_dir);
QList<QIODevice*> sublist;
sublist.reserve(50);
while(iterator.hasNext()) {
sublist.append(new QFile(iterator.next()));
}
// 从小到大排序
std::sort(sublist.begin(), sublist.end(), [&collator](QIODevice *f1, QIODevice *f2){
if (collator.compare(static_cast<const QFile*>(f1)->fileName(),
static_cast<const QFile*>(f2)->fileName()) < 0)
return true;
return false;
});
list = sublist + list;
if (base_dir.path() == target_dir.path())
break;
} while (target_dir.cdUp());
}
return list;
}
DConfigKey configKey;
DConfigInfo values;
DConfigFile::Version m_version = {0, 0};
char padding [4] = {};
};
DConfigMetaImpl::DConfigMetaImpl(const DConfigKey &configKey)
: DConfigMeta (),
configKey(configKey)
{
}
DConfigMetaImpl::~DConfigMetaImpl()
{
}
/*!
@~english
@class Dtk::Core::DConfigCache
\inmodule dtkcore
@brief Provides user and global runtime cache access interfaces for Configuration file.
*/
/*!
@~english
@fn bool DConfigCache::load(const QString &localPrefix = QString()) = 0;
@brief Parse the cache configuration file
@return
*/
/*!
@~english
@fn bool DConfigCache::save(const QString &localPrefix = QString(), QJsonDocument::JsonFormat format = QJsonDocument::Indented, bool sync = false) = 0;
@brief Save the cached value to disk
\a localPrefix Directory prefix
\a format Save format
\a sync Whether to refresh immediately
@return
*/
/*!
@~english
@fn bool DConfigCache::isGlobal() const = 0;
@brief Whether to cache globally
@return
*/
/*!
@~english
@fn void DConfigCache::remove(const QString &key) = 0;
@brief Delete a configuration entry from the cache
\a key Configuration name
@return
*/
/*!
@~english
@fn QStringList DConfigCache::keyList() const = 0;
@brief Returns all configuration items for the configuration content
@return
*/
/*!
@~english
@fn bool DConfigCache::setValue(const QString &key, const QVariant &value, const int serial, const uint uid, const QString &callerAppid) = 0;
@brief Sets the value in the cache
\a key Configuration name
\a value Configuration name
\a uid User Id at setup time
\a callerAppid Application id at setup time
@return true if the cache was updated (value or serial changed), false if no update was needed
*/
/*!
@~english
@fn QVariant DConfigCache::value(const QString &key) const = 0;
@brief Get the value in the cache
\a key Configuration name
@return
*/
/*!
@~english