-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcpumodel.cpp
109 lines (87 loc) · 2.68 KB
/
cpumodel.cpp
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
#include "cpumodel.h"
#include <QFile>
#include <QTextStream>
#include <QStringList>
#include <QDebug>
#define CPUINFO_FILE "/proc/cpuinfo"
#define PROCESSOR_SECTION_START "processor"
CpuModel::CpuModel(QObject *parent)
: QAbstractListModel(parent)
{
}
void CpuModel::populateModel()
{
emit beginResetModel();
m_roleNames.clear();
m_data.clear();
QFile file(CPUINFO_FILE);
file.open(QIODevice::ReadOnly);
QTextStream stream(&file);
// read cpuinfo line by line
QString line = stream.readLine();
// cpuNum points to a current processor section inside cpuinfo
int cpuNum = -1;
while (!line.isNull()) {
if (line.isEmpty()) {
line = stream.readLine();
continue;
}
QStringList keyValue = line.split(':');
if (keyValue.count() > 0) {
QString keyString = keyValue.at(0).trimmed();
QByteArray key = keyString.replace(' ','_').toLatin1();
if (!m_roleNames.values().contains(key)) {
m_roleNames.insert(Qt::UserRole + m_roleNames.count() + 1, key);
}
if (keyValue.count() == 2) {
QString value = keyValue.at(1).trimmed();
// starting new processor section
if (keyString == PROCESSOR_SECTION_START) {
cpuNum++;
m_data.append(QMap<QString,QString>());
}
if (cpuNum >= m_data.count()) {
qWarning() << "CPU core" << cpuNum << "not inserted";
} else {
m_data[cpuNum].insert(keyString, value);
}
} else {
qWarning() << "Unexpected format:" << line;
}
}
line = stream.readLine();
}
file.close();
emit endResetModel();
}
int CpuModel::rowCount(const QModelIndex & /*parent*/) const
{
return m_data.count();
}
QVariant CpuModel::data(const QModelIndex & index, int role) const
{
if (index.row() < 0 || index.row() >= m_data.count() || !m_roleNames.contains(role)) {
return QVariant();
}
return m_data.at(index.row()).value(m_roleNames.value(role));
}
QHash<int, QByteArray> CpuModel::roleNames() const
{
return m_roleNames;
}
QString CpuModel::prettyFormat(int index) const
{
QString result;
if (index < 0 || index >= m_data.count()) {
return result;
}
QList<QByteArray> keys = m_roleNames.values();
qSort(keys);
foreach (const QByteArray& key, keys) {
result.append("<b>" + key + "</b>");
result.append(" : ");
result.append(m_data.at(index).value(key));
result.append("<br>");
}
return result;
}