Debian Codegraph @

src/dsysinfo.cpp

raw
1 // SPDX-FileCopyrightText: 2017 - 2023 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "dsysinfo.h"
6 #include "ddesktopentry.h"
7
8 #include <QFile>
9 #include <QLocale>
10 #include <QStorageInfo>
11 #include <QProcess>
12 #include <QDebug>
13 #include <QJsonObject>
14 #include <QJsonDocument>
15 #include <QJsonArray>
16 #include <QSettings>
17 #include <QStandardPaths>
18 #include <QDateTime>
19 #include <QRegularExpression>
20 #include <QLoggingCategory>
21 #include <qmath.h>
22
23 #ifdef Q_OS_LINUX
24 #include <sys/sysinfo.h>
25 #include <sys/utsname.h>
26 #include <unistd.h>
27 #endif
28
29 #define OS_VERSION_FILE DSYSINFO_PREFIX"/etc/os-version"
30 #define LSB_RELEASE_FILE DSYSINFO_PREFIX"/etc/lsb-release"
31 #define OS_RELEASE_FILE DSYSINFO_PREFIX"/etc/os-release"
32 #define DEEPIN_VERSION_FILE DSYSINFO_PREFIX"/etc/deepin-version"
33
34 static inline bool inTest()
35 {
36 return !QLatin1String(DSYSINFO_PREFIX).isEmpty();
37 }
38
39 DCORE_BEGIN_NAMESPACE
40
41 #ifdef QT_DEBUG
42 Q_LOGGING_CATEGORY(logSysInfo, "dtk.dsysinfo")
43 #else
44 Q_LOGGING_CATEGORY(logSysInfo, "dtk.dsysinfo", QtInfoMsg)
45 #endif
46
47 class Q_DECL_HIDDEN DSysInfoPrivate
48 {
49 public:
50 DSysInfoPrivate();
51
52 #ifdef Q_OS_LINUX
53 void ensureDeepinInfo();
54 bool ensureOsVersion();
55 void ensureDistributionInfo();
56 bool splitA_BC_DMode();
57 #endif
58 void ensureReleaseInfo();
59 void ensureComputerInfo();
60 QMap<QString, QString> parseInfoFile(QFile &file);
61 QMap<QString, QString> parseInfoContent(const QString &content);
62 #ifdef Q_OS_LINUX
63 DSysInfo::DeepinType deepinType = DSysInfo::DeepinType(-1);
64 QMap<QString, QString> deepinTypeMap; //Type Name with Language
65 QString deepinVersion;
66 QString deepinEdition;
67 QString deepinCopyright;
68
69 QString majorVersion;
70 QString minorVersion;
71 struct MinVersion {
72 enum Type {
73 A_BC_D, /*!< Professional Edition*/
74 X_Y_Z, /*!< Home Edition*/
75 A_B_C /*!< Community Edition*/
76 };
77 MinVersion()
78 : A(0)
79 , B(0)
80 , BC(0)
81 , C(0)
82 , D(0)
83 , X(0)
84 , Y(0)
85 , Z(0)
86 {
87 }
88
89 uint A, B, BC, C, D; // A-BC-D
90 uint X, Y, Z;
91 Type type;
92 };
93 struct OSBuild {
94 OSBuild():A(0), B(0), C(0), D(0), xyz(100){
95 }
96 uint A, B, C, D, E, xyz; // ABCDE.xyz
97 };
98
99 MinVersion minVersion;
100 OSBuild osBuild;
101 #endif
102
103 QScopedPointer<DDesktopEntry> distributionInfo;
104
105 DSysInfo::ProductType productType = DSysInfo::ProductType(-1);
106 QString prettyName;
107 QString productTypeString;
108 QString productVersion;
109
110 QString computerName;
111 QString cpuModelName;
112 qint64 memoryAvailableSize = -1;
113 qint64 memoryInstalledSize = -1;
114 qint64 diskSize = 0;
115 };
116
117 DSysInfoPrivate::DSysInfoPrivate()
118 {
119
120 }
121
122 #ifdef Q_OS_LINUX
123 void DSysInfoPrivate::ensureDistributionInfo()
124 {
125 if (distributionInfo)
126 return;
127
128 const QString distributionInfoFile(DSysInfo::distributionInfoPath());
129 // Generic DDE distribution info
130 distributionInfo.reset(new DDesktopEntry(distributionInfoFile));
131 }
132
133 bool DSysInfoPrivate::splitA_BC_DMode()
134 {
135 // A-BC-D
136 bool ok = false;
137 uint minv = minorVersion.toUInt(&ok);
138 if (ok) {
139 minVersion.D = minv % 10;
140 } else if (minorVersion.length() > 0) {
141 const QString D = minorVersion.right(1);
142 if (D.contains(QRegularExpression("[0-9A-Z]"))) {
143 // 0-9...A-Z
144 minVersion.D = 10 + static_cast<uint>(D.data()->toLatin1() - 'A');
145 } else {
146 qWarning() << "invalid minorVersion";
147 minVersion.D = 0;
148 }
149 }
150 uint minVer = minorVersion.left(3).toUInt();
151 minVersion.BC = minVer % 100;
152 minVer /= 100;
153 minVersion.A = minVer % 10;
154 minVersion.type = MinVersion::A_BC_D;
155 return ok;
156 }
157
158 void DSysInfoPrivate::ensureDeepinInfo()
159 {
160 if (static_cast<int>(deepinType) > 0 && !inTest())
161 return;
162
163 if (inTest())
164 deepinTypeMap.clear(); // clear cache for test
165
166 QFile file(DEEPIN_VERSION_FILE);
167
168 if (!file.open(QFile::ReadOnly)) {
169 deepinType = DSysInfo::UnknownDeepin;
170
171 return;
172 }
173
174 char buf[1024];
175 int buf_length = 0;
176
177 Q_FOREVER {
178 buf_length = file.readLine(buf, sizeof(buf));
179
180 if (buf_length < 0)
181 break;
182
183 const QByteArray line(buf, buf_length);
184 const QByteArrayList &list = line.split('=');
185
186 if (list.count() != 2) {
187 continue;
188 }
189
190 const auto key_value = qMakePair(list.first().trimmed(), list.last().trimmed());
191
192 if (key_value.first == "Version") {
193 deepinVersion = key_value.second;
194 } else if (line.startsWith("Type")) {
195 if (key_value.first == "Type") {
196 deepinTypeMap[QString()] = QString::fromLatin1(key_value.second);
197 } else if (key_value.first.at(4) == '[' && key_value.first.at(key_value.first.size() - 1) == ']') {
198 const QByteArray &language = key_value.first.mid(5, key_value.first.size() - 6);
199
200 if (!language.isEmpty()) {
201 deepinTypeMap[QString::fromLatin1(language)] = QString::fromUtf8(key_value.second);
202 }
203 }
204 } else if (key_value.first == "Edition") {
205 deepinEdition = QString::fromUtf8(key_value.second);
206 } else if (key_value.first == "Copyright") {
207 deepinCopyright = QString::fromUtf8(key_value.second);
208 }
209
210 // deepinTypeMap may not parse finished(multi language) but !deepinTypeMap.isEmpty()
211 // if (!deepinTypeMap.isEmpty() && !deepinEdition.isEmpty() && !deepinCopyright.isEmpty()) {
212 // break;
213 // }
214 }
215
216 file.close();
217
218 const QString &deepin_type = deepinTypeMap[QString()];
219
220 if (deepin_type.isEmpty()) {
221 deepinType = DSysInfo::UnknownDeepin;
222 } else if (deepin_type == "Desktop") {
223 deepinType = DSysInfo::DeepinDesktop;
224 } else if (deepin_type == "Professional") {
225 deepinType = DSysInfo::DeepinProfessional;
226 } else if (deepin_type == "Server") {
227 deepinType = DSysInfo::DeepinServer;
228 } else if (deepin_type == "Personal") {
229 deepinType = DSysInfo::DeepinPersonal;
230 } else if (deepin_type == "Military") {
231 deepinType = DSysInfo::DeepinMilitary;
232 } else {
233 deepinType = DSysInfo::UnknownDeepin;
234 }
235 }
236
237 bool DSysInfoPrivate::ensureOsVersion()
238 {
239 if (osBuild.A > 0 && !inTest())
240 return true;
241
242 DDesktopEntry entry(OS_VERSION_FILE);
243 bool ok = false;
244
245 #define D_ASSET_EXIT(con, msg) do { \
246 if (!(con)) { \
247 qWarning() << __func__ << msg; \
248 return false; \
249 } \
250 } while (false)
251
252 D_ASSET_EXIT(entry.status() == DDesktopEntry::NoError, entry.status());
253
254 // 先获取版本信息
255 // ABCDE.xyz.abc
256 QString osb = entry.stringValue("OsBuild", "Version");
257 QStringList osbs = osb.split(".");
258 ok = (osbs.size() >= 2 && osbs.value(0).size() == 5);
259 D_ASSET_EXIT(ok, "OsBuild version invalid!");
260
261 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
262 const QStringList &left = osbs.value(0).split(QString(), Qt::SkipEmptyParts);
263 #else
264 const QStringList &left = osbs.value(0).split(QString(), QString::SkipEmptyParts);
265 #endif
266 D_ASSET_EXIT(left.size() == 5, "OsBuild version(ls) invalid!");
267
268 int idx = 0;
269 osBuild.A = left.value(idx++, "0").toUInt(&ok);
270 D_ASSET_EXIT(ok, "OsBuild version(A) invalid!");
271 osBuild.B = left.value(idx++, "0").toUInt(&ok);
272 D_ASSET_EXIT(ok, "OsBuild version(B) invalid!");
273 osBuild.C = left.value(idx++, "0").toUInt(&ok);
274 if (!ok) {
275 auto c = left.value(idx-1, "0").toLatin1();
276 D_ASSET_EXIT(c.size()>0, "OsBuild version(C) invalid!");
277 osBuild.C = uint(c.at(0));
278 }
279 osBuild.D = left.value(idx++, "0").toUInt(&ok);
280 D_ASSET_EXIT(ok, "OsBuild version(D) invalid!");
281 osBuild.E = left.value(idx++, "0").toUInt(&ok);
282 D_ASSET_EXIT(ok, "OsBuild version(E) invalid!");
283
284 // xyz
285 osBuild.xyz = osbs.value(1).trimmed().toUInt(&ok);
286
287 majorVersion = entry.stringValue("MajorVersion", "Version");
288 minorVersion = entry.stringValue("MinorVersion", "Version");
289
290 switch (osBuild.D) {
291 case 7: {
292 // Home Edition uses the form of "full version number coding -x.y.z"
293 const QStringList &versionList = minorVersion.split('.');
294 if (versionList.isEmpty()) {
295 // If the reading fails, return it directly to empty
296 qWarning() << "no minorVersion";
297 return false;
298 } else if (versionList.length() == 2) {
299 // Z is 0
300 minVersion.X = versionList.first().toUInt();
301 minVersion.Y = versionList.last().toUInt();
302 minVersion.Z = 0;
303 } else if (versionList.length() == 3) {
304 // X.Y.Z exists
305 minVersion.X = versionList.at(0).toUInt();
306 minVersion.Y = versionList.at(1).toUInt();
307 minVersion.Z = versionList.at(2).toUInt();
308 }
309 minVersion.type = MinVersion::X_Y_Z;
310 } break;
311
312 case 3: {
313 // The community version uses the form of "full version number coding A.B.C"
314 bool a_bc_dMode = false;
315 const QStringList &versionList = minorVersion.split('.');
316 if (versionList.isEmpty()) {
317 // If the reading fails, return it directly to empty
318 qWarning() << "no minorVersion";
319 return false;
320 } else if (versionList.length() == 1) {
321 QString modeVersion = versionList.first();
322 if (modeVersion.length() == 2) {
323 //A.B.C mode and B c are 0
324 minVersion.A = modeVersion.toUInt();
325 minVersion.B = 0;
326 minVersion.C = 0;
327 } else {
328 // A_BC_D mode
329 splitA_BC_DMode();
330 a_bc_dMode = true;
331 }
332 } else if (versionList.length() == 2) {
333 // C=0
334 minVersion.A = versionList.first().toUInt();
335 minVersion.B = versionList.last().toUInt();
336 minVersion.C = 0;
337 } else if (versionList.length() == 3) {
338 // A.B.C exists
339 minVersion.A = versionList.at(0).toUInt();
340 minVersion.B = versionList.at(1).toUInt();
341 minVersion.C = versionList.at(2).toUInt();
342 }
343
344 if (!a_bc_dMode)
345 minVersion.type = MinVersion::A_B_C;
346 } break;
347 default: {
348 // A-BC-D
349 ok = splitA_BC_DMode();
350 } break;
351 }
352 return ok;
353 }
354
355 static QString unquote(const QByteArray &value)
356 {
357 if (value.at(0) == '"' || value.at(0) == '\'') {
358 return QString::fromLatin1(value.mid(1, value.size() - 2));
359 }
360
361 return QString::fromLatin1(value);
362 }
363
364 static bool readEtcFile(DSysInfoPrivate *info, const char *filename,
365 const QByteArray &idKey, const QByteArray &versionKey, const QByteArray &prettyNameKey)
366 {
367
368 QFile file(QString::fromLatin1(filename));
369
370 if (!file.open(QIODevice::ReadOnly)) {
371 return false;
372 }
373
374 quint8 valid_data_count = 0;
375 char buf[1024];
376
377
378 if (inTest()) {
379 // for test clear cache
380 info->productTypeString.clear();
381 info->productType = DSysInfo::UnknownType;
382 }
383
384 while (valid_data_count < 3) {
385 int buf_length = file.readLine(buf, sizeof(buf));
386
387 if (buf_length < 0)
388 break;
389
390 const QByteArray line(buf, buf_length - 1);
391
392 if (info->productTypeString.isEmpty() && line.startsWith(idKey)) {
393 const QByteArray value(line.constData() + idKey.size());
394 info->productTypeString = unquote(value);
395 ++valid_data_count;
396 continue;
397 }
398
399 if (info->prettyName.isEmpty() && line.startsWith(prettyNameKey)) {
400 const QByteArray value(line.constData() + prettyNameKey.size());
401 info->prettyName = unquote(value);
402 ++valid_data_count;
403 continue;
404 }
405
406 if (info->productVersion.isEmpty() && line.startsWith(versionKey)) {
407 const QByteArray value(line.constData() + versionKey.size());
408 info->productVersion = unquote(value);
409 ++valid_data_count;
410 continue;
411 }
412 }
413
414 file.close();
415
416 return valid_data_count != 0;
417 }
418
419 static bool readOsRelease(DSysInfoPrivate *info)
420 {
421 if (!readEtcFile(info, OS_RELEASE_FILE, "ID=", "VERSION_ID=", "PRETTY_NAME="))
422 return readEtcFile(info, DSYSINFO_PREFIX"/usr/lib/os-release", "ID=", "VERSION_ID=", "PRETTY_NAME=");
423
424 return true;
425 }
426
427 static bool readLsbRelease(DSysInfoPrivate *info)
428 {
429 return readEtcFile(info, LSB_RELEASE_FILE, "DISTRIB_ID=", "DISTRIB_RELEASE=", "DISTRIB_DESCRIPTION=");
430 }
431 #endif
432
433 void DSysInfoPrivate::ensureReleaseInfo()
434 {
435 if (productType > 0 && !inTest()) {
436 return;
437 }
438
439 #ifdef Q_OS_LINUX
440 readOsRelease(this);
441 readLsbRelease(this);
442
443 if (productTypeString.isEmpty()) {
444 productType = DSysInfo::UnknownType;
445 } else {
446 switch (productTypeString.at(0).unicode()) {
447 case 'd':
448 case 'D':
449 if (productTypeString.compare("deepin", Qt::CaseInsensitive) == 0) {
450 productType = DSysInfo::Deepin;
451 } else if (productTypeString.compare("debian", Qt::CaseInsensitive) == 0) {
452 productType = DSysInfo::Debian;
453 }
454 break;
455 case 'a':
456 case 'A':
457 if (productTypeString.compare("arch", Qt::CaseInsensitive) == 0)
458 productType = DSysInfo::ArchLinux;
459 break;
460 case 'c':
461 case 'C':
462 if (productTypeString.compare("centos", Qt::CaseInsensitive) == 0)
463 productType = DSysInfo::CentOS;
464 break;
465 case 'f':
466 case 'F':
467 if (productTypeString.compare("fedora", Qt::CaseInsensitive) == 0)
468 productType = DSysInfo::Fedora;
469 break;
470 case 'g':
471 case 'G':
472 if (productTypeString.compare("gentoo", Qt::CaseInsensitive) == 0)
473 productType = DSysInfo::Gentoo;
474 break;
475 case 'l':
476 case 'L':
477 if (productTypeString.compare("linuxmint", Qt::CaseInsensitive) == 0)
478 productType = DSysInfo::LinuxMint;
479 break;
480 case 'm':
481 case 'M':
482 if (productTypeString.compare("manjaro", Qt::CaseInsensitive) == 0)
483 productType = DSysInfo::Manjaro;
484 break;
485 case 'n':
486 case 'N':
487 if (productTypeString.compare("nixos", Qt::CaseInsensitive) == 0)
488 productType = DSysInfo::NixOS;
489 break;
490 case 'o':
491 case 'O':
492 if (productTypeString.compare("opensuse", Qt::CaseInsensitive) == 0)
493 productType = DSysInfo::openSUSE;
494 break;
495 case 's':
496 case 'S':
497 if (productTypeString.compare("sailfishos", Qt::CaseInsensitive) == 0)
498 productType = DSysInfo::SailfishOS;
499 break;
500 case 'u':
501 case 'U':
502 if (productTypeString.compare("ubuntu", Qt::CaseInsensitive) == 0) {
503 productType = DSysInfo::Ubuntu;
504 } else if (productTypeString.compare("uos", Qt::CaseInsensitive) == 0 || productTypeString.compare("UnionTech OS", Qt::CaseInsensitive) == 0) {
505 productType = DSysInfo::Uos;
506 }
507 break;
508 default:
509 productType = DSysInfo::UnknownType;
510 break;
511 }
512 }
513 #endif
514 }
515
516 void DSysInfoPrivate::ensureComputerInfo()
517 {
518 #ifdef Q_OS_LINUX
519
520 #endif
521 }
522
523 QMap<QString, QString> DSysInfoPrivate::parseInfoFile(QFile &file)
524 {
525 char buf[1024];
526 qint64 lineLength = 0;
527 QMap<QString, QString> map;
528 do {
529 lineLength = file.readLine(buf, sizeof(buf));
530 QString s(buf);
531 if (s.contains(':')) {
532 QStringList list = s.split(':');
533 if (list.size() == 2) {
534 map.insert(list.first().trimmed(), list.back().trimmed());
535 }
536 }
537 } while (lineLength >= 0);
538 return map;
539 }
540
541 QMap<QString, QString> DSysInfoPrivate::parseInfoContent(const QString &content)
542 {
543 QMap<QString, QString> map;
544 QStringList lineContents = content.split("\n");
545 for (auto lineContent : lineContents) {
546 if (lineContent.contains(':')) {
547 QStringList list = lineContent.split(':');
548 if (list.size() == 2) {
549 map.insert(list.first().trimmed(), list.back().trimmed());
550 }
551 }
552 }
553 return map;
554 }
555
556 Q_GLOBAL_STATIC(DSysInfoPrivate, siGlobal)
557
558 QString DSysInfo::operatingSystemName()
559 {
560 siGlobal->ensureReleaseInfo();
561
562 return siGlobal->prettyName;
563 }
564
565 #ifdef Q_OS_LINUX
566 /*!
567 \brief Check current distro is Deepin or not.
568 \note Uos will also return true.
569 */
570 bool DSysInfo::isDeepin()
571 {
572 siGlobal->ensureReleaseInfo();
573
574 return productType() == Deepin || productType() == Uos;
575 }
576
577 bool DSysInfo::isDDE()
578 {
579 if (!DSysInfo::isDeepin()) {
580 const QByteArray &xsd = qgetenv("XDG_SESSION_DESKTOP");
581 return !xsd.compare("deepin", Qt::CaseInsensitive) ||
582 !xsd.compare("DDE", Qt::CaseInsensitive);
583 }
584
585 siGlobal->ensureDeepinInfo();
586
587 return siGlobal->deepinType != UnknownDeepin;
588 }
589
590 DSysInfo::DeepinType DSysInfo::deepinType()
591 {
592 siGlobal->ensureDeepinInfo();
593
594 return siGlobal->deepinType;
595 }
596
597 QString DSysInfo::deepinTypeDisplayName(const QLocale &locale)
598 {
599 siGlobal->ensureDeepinInfo();
600
601 return siGlobal->deepinTypeMap.value(locale.name(), siGlobal->deepinTypeMap.value(QString()));
602 }
603
604 QString DSysInfo::deepinVersion()
605 {
606 siGlobal->ensureDeepinInfo();
607
608 return siGlobal->deepinVersion;
609 }
610
611 QString DSysInfo::deepinEdition()
612 {
613 siGlobal->ensureDeepinInfo();
614
615 return siGlobal->deepinEdition;
616 }
617
618 QString DSysInfo::deepinCopyright()
619 {
620 siGlobal->ensureDeepinInfo();
621
622 return siGlobal->deepinCopyright;
623 }
624
625 /*!
626 @~english
627 \brief
628 Display system type [1: desktop] [2: server] [3: special devices]
629 \note 根据 osBuild.B 判断
630 */
631 DSysInfo::UosType DSysInfo::uosType()
632 {
633 if (!DSysInfo::isDeepin() && !inTest())
634 return UosTypeUnknown;
635
636 siGlobal->ensureOsVersion();
637
638 UosType ost = UosTypeUnknown;
639 if ((siGlobal->osBuild.B > UosTypeUnknown && siGlobal->osBuild.B < UosTypeCount)) {
640 ost = static_cast<UosType>(siGlobal->osBuild.B);
641 }
642
643 return ost;
644 }
645
646 /*!
647 @~english
648 \brief
649 Editions: professional version/personal version/community version ...
650 \note According to osbuild.b && osbuild.d
651 */
652 DSysInfo::UosEdition DSysInfo::uosEditionType()
653 {
654 siGlobal->ensureOsVersion();
655 UosEdition ospt = UosEditionUnknown;
656 if (siGlobal->osBuild.B == UosDesktop) {
657 switch (siGlobal->osBuild.D) {
658 case 1:
659 return UosProfessional;
660 case 2:
661 case 7:
662 //The new version of the family version (7) and the old version of the personal version (2) The same as the home does not modify the old logic (7) to ensure the adaptation of the old version
663 return UosHome;
664 case 3:
665 return UosCommunity;
666 case 4:
667 return UosMilitary;
668 case 5:
669 return UosDeviceEdition;
670 case 6:
671 return UosEducation;
672 default:
673 break;
674 }
675 } else if (siGlobal->osBuild.B == UosServer) {
676 switch (siGlobal->osBuild.D) {
677 case 1:
678 return UosEnterprise;
679 case 2:
680 return UosEnterpriseC;
681 case 3:
682 return UosEuler;
683 case 4:
684 return UosMilitaryS;
685 case 5:
686 return UosDeviceEdition;
687 default:
688 break;
689 }
690 } else if (siGlobal->osBuild.B == UosDevice){
691 ospt = UosEnterprise; // os-version 1.4 if B==Device then et=Enterprise
692 }
693
694 return ospt;
695 }
696
697 #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
698 /*!
699 @~english
700 \brief Architecture information (using bit flags of a byte)
701 【0x8 sw64】【0x4 mips64】【0x2 arm64】【0x1 amd64】
702 */
703 DSysInfo::UosArch DSysInfo::uosArch()
704 {
705 siGlobal->ensureOsVersion();
706
707 return static_cast<UosArch>(siGlobal->osBuild.E);
708 }
709 #endif
710
711 static QString getUosVersionValue(const QString &key, const QLocale &locale)
712 {
713 DDesktopEntry entry(OS_VERSION_FILE);
714 QString localKey = QString("%1[%2]").arg(key, locale.name());
715
716 return entry.stringValue(localKey, "Version", entry.stringValue(key, "Version"));
717 }
718
719 /*!
720 @~english
721 \brief Version name
722 ProductType[xx] The corresponding value of the item, if you can't find the value of the corresponding language, use the value of the productType (desktop/server/device)
723 \a locale Current system language
724 */
725 QString DSysInfo::uosProductTypeName(const QLocale &locale)
726 {
727 return getUosVersionValue("ProductType", locale);
728 }
729
730 /*!
731 @~english
732 \brief DSysInfo::osSystemName Version name
733
734 The corresponding value corresponding to SystemName [xx] item, if you can't find the default language of the corresponding language, use the value of SystemName uniontech os
735 \a locale Current system language
736 */
737 QString DSysInfo::uosSystemName(const QLocale &locale)
738 {
739 return getUosVersionValue("SystemName", locale);
740 }
741
742 /*!
743 @~english
744 \brief DSysInfo::osEditionName Version name
745 EditionName[xx] The corresponding value of the item, if you can't find the value of the corresponding language, use the value of EditionName (Professional/Home/Community ...)
746 \a locale Current system language
747 */
748 QString DSysInfo::uosEditionName(const QLocale &locale)
749 {
750 return getUosVersionValue("EditionName", locale);
751 }
752
753 /*!
754 @~english
755 \brief DSysInfo::spVersion Period version name
756 BC, A.B.C in the small version number a-bc-d
757 Return to SP1-SPXX, if the official version returns empty
758 In the x.y.z mode, it will not support returning this version number for the time being
759 \ note minversion.bc == 00: The official version minversion.bc | minversion.b == 01-99: SP1 ... .sp99
760 */
761 QString DSysInfo::spVersion()
762 {
763 siGlobal->ensureOsVersion();
764 switch (siGlobal->minVersion.type) {
765 case DSysInfoPrivate::MinVersion::A_BC_D: {
766 if (siGlobal->minVersion.BC > 0) {
767 return QString("SP%1").arg(siGlobal->minVersion.BC);
768 } else {
769 return QString(); // 00 正式版
770 }
771 }
772
773 case DSysInfoPrivate::MinVersion::A_B_C: {
774 if (siGlobal->minVersion.B > 0) {
775 return QStringLiteral("SP%1").arg(siGlobal->minVersion.B);
776 } else {
777 return {};
778 }
779 }
780
781 case DSysInfoPrivate::MinVersion::X_Y_Z:
782 qWarning() << "Getting the SP version in this mode is not supported.";
783 return {};
784 }
785 return QString();
786 }
787
788 /*!
789 @~english
790 \brief DSysInfo::udpateVersion Update version name
791 minor version number D in A-BC-D mode、C in A.B.C mode
792 Return to Update1 ... Update9, if the official version returns to empty
793 In the x.y.z mode, it will not support returning this version number for the time being
794 \note minVersion.D == 0:official version minVersion.D | minVersion.C == 1-9:update1… update9,updateA...updateZ
795 */
796 QString DSysInfo::udpateVersion()
797 {
798 siGlobal->ensureOsVersion();
799 switch (siGlobal->minVersion.type) {
800 case DSysInfoPrivate::MinVersion::A_BC_D: {
801 if (siGlobal->minVersion.D > 0) {
802 uint uv = siGlobal->minVersion.D;
803 if (uv < 10) {
804 return QString("update%1").arg(uv);
805 } else if (uv < 36) {
806 return QString("update").append(QChar(uv - 10 + 'A'));
807 } else {
808 qWarning() << "invalid update versoin";
809 break;
810 }
811 } else {
812 break; // 0 正式版
813 }
814 }
815
816 case DSysInfoPrivate::MinVersion::A_B_C: {
817 if (siGlobal->minVersion.C > 0) {
818 return QStringLiteral("update%1").arg(siGlobal->minVersion.C);
819 } else {
820 break;
821 }
822 }
823
824 case DSysInfoPrivate::MinVersion::X_Y_Z:
825 qWarning() << "Getting the update version in this mode is not supported.";
826 break;
827 }
828
829 return {};
830 }
831
832 /*!
833 @~english
834 \brief Main edition number
835 Main edition number 【20】【23】【25】【26】【29】【30】
836 \note Return to Majorversion value
837 */
838 QString DSysInfo::majorVersion()
839 {
840 siGlobal->ensureOsVersion();
841 return siGlobal->majorVersion;
842 }
843
844 /*!
845 @~english
846 \brief DSysInfo::minorVersion minor version
847 *【ABCD】 ·[0-9]{4}
848 *【A.B.C】 or【X.Y.Z】
849 @return the value of minorversion
850 */
851 QString DSysInfo::minorVersion()
852 {
853 siGlobal->ensureOsVersion();
854 return siGlobal->minorVersion;
855 }
856
857 /*!
858 @~english
859 \brief DSysInfo::buildVersion Small version number
860 System mirror batch number, in order of time (non-retreat) increase from 100-999
861 \note Return osbuild.xyz value
862 */
863 QString DSysInfo::buildVersion()
864 {
865 DDesktopEntry entry(OS_VERSION_FILE);
866 QString osb = entry.stringValue("OsBuild", "Version");
867 return osb.mid(6).trimmed();
868 }
869 #endif
870
871 #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
872 QString DSysInfo::deepinDistributionInfoPath()
873 {
874 return distributionInfoPath();
875 }
876 #endif
877
878 QString DSysInfo::distributionInfoPath()
879 {
880 #ifdef Q_OS_LINUX
881 // return "/usr/share/deepin/distribution.info";
882 return QStandardPaths::locate(QStandardPaths::GenericDataLocation, "deepin/distribution.info");
883 #else
884 return QDir(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation)).filePath("deepin-distribution.info");
885 #endif // Q_OS_LINUX
886 }
887
888 QString DSysInfo::distributionInfoSectionName(DSysInfo::OrgType type)
889 {
890 switch (type) {
891 case Distribution:
892 return "Distribution";
893 case Distributor:
894 return "Distributor";
895 case Manufacturer:
896 return "Manufacturer";
897 }
898
899 return QString();
900 }
901
902 /*!
903 @~english
904 \return the organization name.
905
906 use \a type as Distribution to get the name of current deepin distribution itself.
907
908 \sa deepinDistributionInfoPath()
909 */
910 QString DSysInfo::distributionOrgName(DSysInfo::OrgType type, const QLocale &locale)
911 {
912 #ifdef Q_OS_LINUX
913 siGlobal->ensureDistributionInfo();
914 #endif
915
916 QString fallback = type == Distribution ? QStringLiteral("Deepin") : QString();
917
918 return siGlobal->distributionInfo->localizedValue("Name", locale, distributionInfoSectionName(type), fallback);
919 }
920
921 #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
922 QString DSysInfo::deepinDistributorName()
923 {
924 return distributionOrgName(Distributor);
925 }
926 #endif
927 /*!
928 @~english
929 \return the organization website name and url.
930
931 use \a type as Distribution to get the name of current deepin distribution itself.
932
933 \sa deepinDistributionInfoPath()
934 */
935 QPair<QString, QString> DSysInfo::distributionOrgWebsite(DSysInfo::OrgType type)
936 {
937 #ifdef Q_OS_LINUX
938 siGlobal->ensureDistributionInfo();
939 #endif
940
941 QString fallbackSiteName = type == Distribution ? QStringLiteral("www.deepin.org") : QString();
942 QString fallbackSiteUrl = type == Distribution ? QStringLiteral("https://www.deepin.org") : QString();
943
944 return {
945 siGlobal->distributionInfo->stringValue("WebsiteName", distributionInfoSectionName(type), fallbackSiteName),
946 siGlobal->distributionInfo->stringValue("Website", distributionInfoSectionName(type), fallbackSiteUrl),
947 };
948 }
949
950 #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
951 QPair<QString, QString> DSysInfo::deepinDistributorWebsite()
952 {
953 return distributionOrgWebsite(Distributor);
954 }
955 #endif
956
957 /*!
958 @~english
959 \return the obtained organization logo path, or the given \a fallback one if there are no such logo.
960
961 use \a type as Distribution to get the logo of current deepin distribution itself.
962
963 \sa deepinDistributionInfoPath()
964 */
965 QString DSysInfo::distributionOrgLogo(DSysInfo::OrgType orgType, DSysInfo::LogoType type, const QString &fallback)
966 {
967 DDesktopEntry distributionInfo(distributionInfoPath());
968 QString orgSectionName = distributionInfoSectionName(orgType);
969
970 switch (type) {
971 case Normal:
972 return distributionInfo.stringValue("Logo", orgSectionName, fallback);
973 case Light:
974 return distributionInfo.stringValue("LogoLight", orgSectionName, fallback);
975 case Symbolic:
976 return distributionInfo.stringValue("LogoSymbolic", orgSectionName, fallback);
977 case Transparent:
978 return distributionInfo.stringValue("LogoTransparent", orgSectionName, fallback);
979 }
980
981 return QString();
982 }
983
984 #if DTK_VERSION < DTK_VERSION_CHECK(6, 0, 0, 0)
985 QString DSysInfo::deepinDistributorLogo(DSysInfo::LogoType type, const QString &fallback)
986 {
987 return distributionOrgLogo(Distributor, type, fallback);
988 }
989 #endif
990
991 DSysInfo::ProductType DSysInfo::productType()
992 {
993 siGlobal->ensureReleaseInfo();
994
995 return siGlobal->productType;
996 }
997
998 QString DSysInfo::productTypeString()
999 {
1000 siGlobal->ensureReleaseInfo();
1001
1002 return siGlobal->productTypeString;
1003 }
1004
1005 QString DSysInfo::productVersion()
1006 {
1007 siGlobal->ensureReleaseInfo();
1008
1009 return siGlobal->productVersion;
1010 }
1011
1012 /*!
1013 @~english
1014 \brief Check if current edition is a community edition
1015
1016 Developer can use this way to check if we need enable or disable features
1017 for community or enterprise edition.
1018
1019 Current rule:
1020 - Professional, Server, Personal edition (DeepinType) will be treat as Enterprise edition.
1021 - Uos (ProductType) will be treat as Enterprise edition.
1022
1023 \return true if it's on a community edition distro/installation
1024 */
1025 bool DSysInfo::isCommunityEdition()
1026 {
1027 #ifdef Q_OS_LINUX
1028 DeepinType type = deepinType();
1029 QList<DeepinType> enterpriseTypes {
1030 DeepinProfessional, DeepinServer, DeepinPersonal
1031 };
1032
1033 if (enterpriseTypes.contains(type)) {
1034 return false;
1035 }
1036
1037 if (productType() == Uos) {
1038 return false;
1039 }
1040 #endif // Q_OS_LINUX
1041
1042 return true;
1043 }
1044
1045 QString DSysInfo::computerName()
1046 {
1047 #ifdef Q_OS_LINUX
1048 struct utsname u;
1049 if (uname(&u) == 0)
1050 siGlobal->computerName = QString::fromLatin1(u.nodename);
1051
1052 return siGlobal->computerName;
1053 #endif
1054 return QString();
1055 }
1056
1057 QString DSysInfo::cpuModelName()
1058 {
1059 if (!siGlobal->cpuModelName.isEmpty())
1060 return siGlobal->cpuModelName;
1061
1062 #ifdef Q_OS_LINUX
1063 static QFile file("/proc/cpuinfo");
1064
1065 if (file.open(QFile::ReadOnly)) {
1066 QMap<QString, QString> map = siGlobal->parseInfoFile(file);
1067 if (map.contains("Processor")) {
1068 // arm-cpuinfo hw_kirin-cpuinfo
1069 siGlobal->cpuModelName = map.value("Processor");
1070 } else if (map.contains("model name")) {
1071 // cpuinfo
1072 siGlobal->cpuModelName = map.value("model name");
1073 } else if (map.contains("cpu model")) {
1074 // loonson3-cpuinfo sw-cpuinfo
1075 siGlobal->cpuModelName = map.value("cpu model");
1076 } else if (map.contains("Hardware")) {
1077 // "HardWare" field contains cpu info on huawei kirin machine (e.g. klv or klu)
1078 siGlobal->cpuModelName = map.value("Hardware");
1079 }
1080
1081 file.close();
1082 }
1083
1084 // Get the cpu info by executing lscpu command
1085 if (siGlobal->cpuModelName.isEmpty()) {
1086 const auto &lscpu_command = QStandardPaths::findExecutable("lscpu");
1087 if (lscpu_command.isEmpty()) {
1088 qWarning() << "lscpu not found";
1089 return QString();
1090 }
1091 QProcess lscpu;
1092 QStringList env = QProcess::systemEnvironment();
1093 env << "LC_ALL=C"; // Add an environment variable
1094 lscpu.setEnvironment(env);
1095 lscpu.setProgram(lscpu_command);
1096 lscpu.start();
1097 if (lscpu.waitForFinished(3000)) {
1098 const QMap<QString, QString> map = siGlobal->parseInfoContent(lscpu.readAll());
1099 if (map.contains("Model name")) {
1100 siGlobal->cpuModelName = map.value("Model name");
1101 }
1102 } else {
1103 qWarning() << "lscpu:" << lscpu.errorString();
1104 }
1105 }
1106
1107 return siGlobal->cpuModelName;
1108 #endif
1109 return QString();
1110 }
1111
1112 /*!
1113 @~english
1114 \return the installed memory size
1115 */
1116 qint64 DSysInfo::memoryInstalledSize()
1117 {
1118 #ifdef Q_OS_LINUX
1119 // Getting Memory Installed Size
1120 // TODO: way to not dept on lshw?
1121 if (siGlobal->memoryInstalledSize >= 0) {
1122 return siGlobal->memoryInstalledSize;
1123 }
1124 if (!QStandardPaths::findExecutable("lshw").isEmpty()) {
1125 QProcess lshw;
1126
1127 lshw.start("lshw", {"-c", "memory", "-json", "-sanitize"}, QIODevice::ReadOnly);
1128
1129 if (!lshw.waitForFinished()) {
1130 return -1;
1131 }
1132
1133 const QByteArray &lshwInfoJson = lshw.readAllStandardOutput();
1134
1135 QJsonParseError error;
1136 auto doc = QJsonDocument::fromJson(lshwInfoJson, &error);
1137 if (error.error != QJsonParseError::NoError) {
1138 qCWarning(logSysInfo(), "parse failed, expect json doc from lshw command");
1139 return -1;
1140 }
1141
1142 if (!doc.isArray()) {
1143 qCWarning(logSysInfo(), "parse failed, expect array");
1144 return -1;
1145 }
1146
1147 QJsonArray lshwResultArray = doc.array();
1148 for (const QJsonValue value : lshwResultArray) {
1149 QJsonObject obj = value.toObject();
1150 if (obj.contains("id") && obj.value("id").toString() == "memory") {
1151 siGlobal->memoryInstalledSize = obj.value("size").toDouble(); // TODO: check "units" is "bytes" ?
1152 break;
1153 }
1154 }
1155 }
1156
1157 Q_ASSERT(siGlobal->memoryInstalledSize > 0);
1158
1159 return siGlobal->memoryInstalledSize;
1160 #else
1161 return -1;
1162 #endif
1163 }
1164
1165 /*!
1166 @~english
1167 \return the total available to use memory size
1168 */
1169 qint64 DSysInfo::memoryTotalSize()
1170 {
1171 #ifdef Q_OS_LINUX
1172 siGlobal->memoryAvailableSize = get_phys_pages() * sysconf(_SC_PAGESIZE);
1173 return siGlobal->memoryAvailableSize;
1174 #endif
1175 return -1;
1176 }
1177
1178 qint64 DSysInfo::systemDiskSize()
1179 {
1180 #ifdef Q_OS_LINUX
1181 // Getting Disk Size
1182 QString deviceName;
1183 QProcess lsblk;
1184
1185 lsblk.start("lsblk", {"-Jlpb", "-oNAME,KNAME,PKNAME,SIZE,MOUNTPOINT"}, QIODevice::ReadOnly);
1186
1187 if (!lsblk.waitForFinished()) {
1188 return -1;
1189 }
1190
1191 const QByteArray &diskStatusJson = lsblk.readAllStandardOutput();
1192 QJsonDocument diskStatus = QJsonDocument::fromJson(diskStatusJson);
1193 QJsonValue diskStatusJsonValue = diskStatus.object().value("blockdevices");
1194 QMap<QString, QPair<QString, qulonglong>> deviceParentAndSizeMap;
1195
1196 if (!diskStatusJsonValue.isUndefined()) {
1197 QJsonArray diskStatusArray = diskStatusJsonValue.toArray();
1198 QString keyName;
1199
1200 for (const QJsonValue oneValue : diskStatusArray) {
1201 QString name = oneValue.toObject().value("name").toString();
1202 QString kname = oneValue.toObject().value("kname").toString();
1203 QString pkname = oneValue.toObject().value("pkname").toString();
1204 qulonglong size = oneValue.toObject().value("size").toVariant().toULongLong();
1205 QString deviceNameMP = oneValue.toObject().value("mountpoint").toString();
1206
1207 if ("/" == deviceNameMP){
1208 deviceName = name;
1209 }
1210
1211 if (keyName.isNull() && deviceName == name) {
1212 keyName = kname;
1213 }
1214
1215 deviceParentAndSizeMap[kname] = QPair<QString, qulonglong>(pkname, size);
1216 }
1217
1218 while (!deviceParentAndSizeMap[keyName].first.isNull()) {
1219 keyName = deviceParentAndSizeMap[keyName].first;
1220 }
1221
1222 siGlobal->diskSize = deviceParentAndSizeMap[keyName].second;
1223 }
1224
1225 return siGlobal->diskSize;
1226
1227 #endif
1228
1229 return -1;
1230 }
1231
1232 /*! @~english DSysInfo::bootTime
1233 * @~english \sa DSysInfo::uptime
1234 * @~english \return the boot time(currentDateTime - uptime)
1235 */
1236 QDateTime DSysInfo::bootTime()
1237 {
1238 qint64 ut = uptime();
1239 return ut > 0 ? QDateTime::currentDateTime().addSecs(-ut) : QDateTime();
1240 }
1241
1242 /*! @~english DSysInfo::shutdownTime
1243 * @~english \return the last shutdown time
1244 */
1245 QDateTime DSysInfo::shutdownTime()
1246 {
1247 QDateTime dt;
1248 #if defined Q_OS_LINUX
1249 QProcess lastx;
1250 lastx.start("last", {"-x", "-F" }, QIODevice::ReadOnly);
1251 if (!lastx.waitForFinished()) {
1252 qWarning() << lastx.errorString();
1253 return QDateTime();
1254 }
1255
1256 while (lastx.canReadLine()) {
1257 const QByteArray data = lastx.readLine(1024);
1258 //shutdown system down 4.19.0-amd64-des Fri Sep 30 17:53:17 2022 - Sat Oct 8 08:32:47 2022 (7+14:39)
1259 if (data.startsWith("shutdown")) {
1260 #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
1261 QString timeFmt = QString(data).split(' ', Qt::SkipEmptyParts).mid(4, 5).join(' ');
1262 #else
1263 QString timeFmt = QString(data).split(' ', QString::SkipEmptyParts).mid(4, 5).join(' ');
1264 #endif
1265 dt = QDateTime::fromString(timeFmt);
1266 break;
1267 }
1268 }
1269 #else
1270
1271 #endif
1272 return dt;
1273 }
1274
1275 /*! @~english DSysInfo::uptime
1276 * @~english \return the up time (/proc/uptime)
1277 */
1278 qint64 DSysInfo::uptime()
1279 {
1280 #if defined Q_OS_LINUX
1281 QFile file("/proc/uptime");
1282 if (!file.open(QFile::ReadOnly)) {
1283 qWarning() << file.errorString();
1284 return -1;
1285 }
1286
1287 QByteArray upTime = file.readAll();
1288 bool ok = false;
1289 qint64 sec = qCeil(upTime.split(' ').value(0).toDouble(&ok)); // [0]: uptime [1]: idletime
1290
1291 return ok ? sec : -1;
1292 #elif defined Q_OS_WIN64
1293 return GetTickCount64();
1294 #elif defined Q_OS_WIN32
1295 return GetTickCount();
1296 #else
1297 return -1;
1298 #endif
1299 }
1300
1301 /*! @~english DSysInfo::arch
1302 * @~english \return the architecture of processor
1303 */
1304 DSysInfo::Arch DSysInfo::arch()
1305 {
1306 #if defined(__x86_64__)
1307 return X86_64;
1308 #elif defined(__i386__)
1309 return X86;
1310 #elif defined(__powerpc64__)
1311 # if __BYTE_ORDER == __BIG_ENDIAN
1312 return PPC64;
1313 # else
1314 return PPC64_LE;
1315 # endif
1316 #elif defined(__powerpc__)
1317 # if __BYTE_ORDER == __BIG_ENDIAN
1318 return PPC;
1319 # else
1320 return PPC_LE;
1321 # endif
1322 #elif defined(__ia64__)
1323 return IA64;
1324 #elif defined(__hppa64__)
1325 return PARISC64;
1326 #elif defined(__hppa__)
1327 return PARISC;
1328 #elif defined(__s390x__)
1329 return S390X;
1330 #elif defined(__s390__)
1331 return S390;
1332 #elif defined(__sparc__) && defined (__arch64__)
1333 return SPARC64;
1334 #elif defined(__sparc__)
1335 return SPARC;
1336 #elif defined(__mips64) && defined(__LP64__)
1337 # if __BYTE_ORDER == __BIG_ENDIAN
1338 return MIPS64;
1339 # else
1340 return MIPS64_LE;
1341 # endif
1342 #elif defined(__mips64)
1343 # if __BYTE_ORDER == __BIG_ENDIAN
1344 return MIPS64;
1345 # else
1346 return MIPS64_LE;
1347 # endif
1348 #elif defined(__mips__)
1349 # if __BYTE_ORDER == __BIG_ENDIAN
1350 return MIPS;
1351 # else
1352 return MIPS_LE;
1353 # endif
1354 #elif defined(__alpha__)
1355 return ALPHA;
1356 #elif defined(__aarch64__)
1357 # if __BYTE_ORDER == __BIG_ENDIAN
1358 return ARM64_BE;
1359 # else
1360 return ARM64;
1361 # endif
1362 #elif defined(__arm__)
1363 # if __BYTE_ORDER == __BIG_ENDIAN
1364 return ARM_BE;
1365 # else
1366 return ARM;
1367 # endif
1368 #elif defined(__sh64__)
1369 return SH64;
1370 #elif defined(__sh__)
1371 return SH;
1372 #elif defined(__loongarch64)
1373 return LOONGARCH64;
1374 #elif defined(__m68k__)
1375 return M68K;
1376 #elif defined(__tilegx__)
1377 return TILEGX;
1378 #elif defined(__cris__)
1379 return CRIS;
1380 #elif defined(__nios2__)
1381 return NIOS2;
1382 #elif defined(__riscv)
1383 # if __SIZEOF_POINTER__ == 4
1384 return RISCV32;
1385 # elif __SIZEOF_POINTER__ == 8
1386 return RISCV64;
1387 # else
1388 # error "Unrecognized riscv architecture variant"
1389 # endif
1390 #elif defined(__arc__)
1391 # if __BYTE_ORDER == __BIG_ENDIAN
1392 return ARC_BE;
1393 # else
1394 return ARC;
1395 # endif
1396 #elif defined(__sw_64__)
1397 return SW_64;
1398 #else
1399 # error "Please register your architecture here!"
1400 #endif
1401 }
1402
1403 DCORE_END_NAMESPACE