swift
Loading...
Searching...
No Matches
identifier.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2014 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
4#include "misc/identifier.h"
5
6#include <QCoreApplication>
7#include <QHostInfo>
8#include <QStringBuilder>
9#include <QSysInfo>
10
13#include "misc/stringutils.h"
14
16
17
18QString toDBusPath(const QString &s) { return swift::misc::utfToPercentEncoding(s, "/", '_'); }
19
21QString toDBusPathElement(const QString &s) { return swift::misc::utfToPercentEncoding(s, {}, '_'); }
22
24QString fromDBusPath(const QString &s) { return swift::misc::utfFromPercentEncoding(s.toLatin1(), '_'); }
25
27QString fromDBusPathElement(const QString &s) { return swift::misc::utfFromPercentEncoding(s.toLatin1(), '_'); }
28
30const QString &cachedEscapedApplicationName()
31{
32 static const QString appName = toDBusPathElement(QCoreApplication::applicationName());
33 return appName;
34}
35
37const QString &cachedLocalHostName()
38{
39 static const QString hostName = QHostInfo::localHostName();
40 return hostName;
41}
42
43enum
44{
45 UuidStringLen = sizeof("00000000-0000-0000-0000-000000000000")
46};
47
48QByteArray cachedMachineUniqueId()
49{
50 static const QByteArray machineUniqueId = QSysInfo::machineUniqueId();
51 return machineUniqueId;
52}
53
54namespace swift::misc
55{
56 CIdentifier::CIdentifier(const QString &name)
57 : m_name(name.trimmed()), m_machineIdBase64(cachedMachineUniqueId().toBase64(QByteArray::OmitTrailingEquals)),
58 m_machineName(cachedLocalHostName()), m_processName(cachedEscapedApplicationName()),
59 m_processId(QCoreApplication::applicationPid())
60 {}
61
62 CIdentifier::CIdentifier(const QString &name, QObject *object) : CIdentifier(name)
63 {
64 if (object)
65 {
66 // append object name
67 this->linkWithQObjectName(object);
68 this->appendName(object->objectName());
69 }
70 }
71
72 CIdentifier::CIdentifier(const QString &name, const QString &machineId, const QString &machineName,
73 const QString &processName, qint64 processId)
74 : m_name(name), m_machineIdBase64(machineId), m_machineName(machineName), m_processName(processName),
75 m_processId(processId)
76 {}
77
78 const CIdentifier &CIdentifier::anonymous()
79 {
80 static const CIdentifier id("");
81 return id;
82 }
83
84 const CIdentifier &CIdentifier::null()
85 {
86 static const CIdentifier id("", "", "", "", 0);
87 return id;
88 }
89
90 const CIdentifier &CIdentifier::fake()
91 {
92 static const CIdentifier id(
93 "fake", QByteArrayLiteral("00000000-0000-0000-0000-000000000000").toBase64(QByteArray::OmitTrailingEquals),
94 "fake machine", "fake process", 0);
95 return id;
96 }
97
99 {
100 static const QUuid ns = QUuid::createUuid();
101 QByteArray baseData;
102 baseData.append(getMachineId());
103 baseData.append(reinterpret_cast<const char *>(&m_processId), sizeof(m_processId));
104 baseData.append(getName().toUtf8());
105 return QUuid::createUuidV5(ns, baseData);
106 }
107
109
111 {
112 if (m_name.endsWith(name))
113 {
114 return;
115 }
116 if (name.isEmpty())
117 {
118 return;
119 }
120 const int index = m_name.lastIndexOf(':');
121 if (index >= 0)
122 {
123 m_name = m_name.left(index);
124 }
125 m_name += QStringLiteral(":") + name;
126 }
127
129 {
130 if (!object)
131 {
132 return;
133 }
135 [=, this](const QString &name) { this->appendName(name); });
136 }
137
139 {
140 return *QByteArray::fromBase64Encoding(m_machineIdBase64.toLocal8Bit());
141 }
142
144 {
145 QString path = root;
146 path += '/' % toDBusPathElement(m_machineName) % "__" % toDBusPathElement(m_machineIdBase64);
147 path += '/' % toDBusPathElement(m_processName) % "__" % QString::number(m_processId);
148
149 const QString name = toDBusPath(m_name);
150 Q_ASSERT_X(!name.contains("//") && !name.startsWith('/') && !name.endsWith('/'), Q_FUNC_INFO, "Invalid name");
151 if (!name.isEmpty())
152 {
153 path += '/' % name;
154 }
155 return path;
156 }
157
158 CIdentifier CIdentifier::fromDBusObjectPath(const QString &path, const QString &root)
159 {
160 const QString relative = path.startsWith(root) ? path.mid(root.length()) : path;
161 const QString machine = relative.section('/', 1, 1);
162 const QString process = relative.section('/', 2, 2);
163 const QString name = relative.section('/', 3, -1);
164
165 CIdentifier result(fromDBusPath(name));
166 result.m_machineIdBase64 = fromDBusPathElement(machine.section("__", 1, 1));
167 result.m_machineName = fromDBusPathElement(machine.section("__", 0, 0));
168 result.m_processId = process.section("__", 1, 1).toInt();
169 result.m_processName = fromDBusPathElement(process.section("__", 0, 0));
170 return result;
171 }
172
173 bool CIdentifier::hasSameMachineName(const CIdentifier &other) const
174 {
175 return !other.getMachineName().isEmpty() && other.getMachineName() == this->getMachineName();
176 }
177
178 bool CIdentifier::hasSameMachineId(const CIdentifier &other) const
179 {
180 return !m_machineIdBase64.isEmpty() && m_machineIdBase64 == other.m_machineIdBase64;
181 }
182
183 bool CIdentifier::hasSameMachineNameOrId(const CIdentifier &other) const
184 {
185 return this->hasSameMachineId(other) || this->hasSameMachineName(other);
186 }
187
189 {
191 return cachedMachineUniqueId() == getMachineId();
192 }
193
198
200 {
201 return cachedEscapedApplicationName() == toDBusPathElement(getProcessName());
202 }
203
204 bool CIdentifier::isAnonymous() const { return &anonymous() == this || anonymous() == *this; }
205
206 bool CIdentifier::isNull() const { return &null() == this || null() == *this; }
207
209 {
210 m_machineIdBase64 = cachedMachineUniqueId().toBase64(QByteArray::OmitTrailingEquals);
211 m_machineName = cachedLocalHostName();
212 }
213
219
221 {
222 Q_UNUSED(i18n);
223 const QString s = m_name % u' ' % m_machineIdBase64 % u' ' % m_machineName % u' ' %
224 QString::number(m_processId) % u' ' % m_processName;
225 return s;
226 }
227
229 {
230 if (index.isMyself())
231 {
232 return QVariant::fromValue(*this);
233 }
234
235 const auto i = index.frontCasted<ColumnIndex>();
236
237 switch (i)
238 {
239 case IndexName: return QVariant::fromValue(m_name);
240 case IndexMachineIdBase64: return QVariant::fromValue(m_machineIdBase64);
241 case IndexMachineName: return QVariant::fromValue(getMachineName());
242 case IndexMachineId: return QVariant::fromValue(getMachineId());
243 case IndexProcessId: return QVariant::fromValue(m_processId);
244 case IndexProcessName: return QVariant::fromValue(m_processName);
245 case IndexIsFromLocalMachine: return QVariant::fromValue(isFromLocalMachine());
246 case IndexIsFromSameProcess: return QVariant::fromValue(hasApplicationProcessId());
247 case IndexIsFromSameProcessName: return QVariant::fromValue(hasApplicationProcessName());
248 default: return CValueObject::propertyByIndex(index);
249 }
250 }
251
252 int CIdentifier::comparePropertyByIndex(CPropertyIndexRef index, const CIdentifier &compareValue) const
253 {
254 if (index.isMyself())
255 {
256 return Compare::compare(m_processId, compareValue.m_processId);
257 }
258
259 const auto i = index.frontCasted<ColumnIndex>();
260
261 switch (i)
262 {
263 case IndexName: return m_name.compare(compareValue.m_name, Qt::CaseInsensitive);
264 case IndexMachineIdBase64: return m_machineIdBase64.compare(compareValue.m_machineIdBase64);
265 case IndexMachineName: return m_machineName.compare(compareValue.m_machineName, Qt::CaseInsensitive);
266 case IndexMachineId: return getMachineId().compare(compareValue.getMachineId(), Qt::CaseInsensitive);
267 case IndexProcessId: return Compare::compare(m_processId, compareValue.m_processId);
268 case IndexProcessName: return m_processName.compare(compareValue.m_processName, Qt::CaseInsensitive);
269 case IndexIsFromLocalMachine:
270 return Compare::compare(this->isFromLocalMachine(), compareValue.isFromLocalMachine());
271 case IndexIsFromSameProcess:
273 case IndexIsFromSameProcessName:
275 default: return CValueObject::comparePropertyByIndex(index, compareValue);
276 }
277 }
278
280 {
281 CValueObject::setPropertyByIndex(index, variant);
282 }
283
284} // namespace swift::misc
void setPropertyByIndex(swift::misc::CPropertyIndexRef index, const QVariant &variant)
Set property by index.
bool hasApplicationProcessName() const
Check if originating from the same process name.
static const CIdentifier & anonymous()
Returns an anonymous identifier, which is a valid identifier without name.
bool hasSameMachineId(const CIdentifier &other) const
Check if other identifier is from the same machine id.
void appendName(const QString &name)
Set name or append name.
const QString & getProcessName() const
Get process name.
Definition identifier.h:118
bool isNull() const
Null identifier (no name, ids etc).
const QString & getName() const
Name.
Definition identifier.h:80
ColumnIndex
Properties by index.
Definition identifier.h:33
bool isAnonymous() const
Check if it is anonymous identifier.
qint64 getProcessId() const
Get process id.
Definition identifier.h:115
const QString & getMachineName() const
Machine name.
Definition identifier.h:103
QUuid toUuid() const
Produces a UUID generated from the identifier.
QByteArray getMachineId() const
Get machine id.
bool hasApplicationProcessId() const
Check if originating from the same process id.
static CIdentifier fromDBusObjectPath(const QString &path, const QString &root={})
Reconstruct an identifier from a DBus object path.
static const CIdentifier & fake()
Returns a fake identifier.
bool hasSameMachineName(const CIdentifier &other) const
Check if the other identifier has the same machine name.
void updateToCurrentProcess()
Update to current process.
bool isFromLocalMachine() const
Check if originating from the same local machine.
void updateToCurrentMachine()
Update to current machine.
void linkWithQObjectName(QObject *object)
Reflect changes of QObject::
bool hasSameMachineNameOrId(const CIdentifier &other) const
Same machine or id?
QVariant propertyByIndex(swift::misc::CPropertyIndexRef index) const
Property by index.
static const CIdentifier & null()
Null (empty) identifier.
QString toUuidString() const
UUID string.
QString convertToQString(bool i18n=false) const
Cast as QString.
QString toDBusObjectPath(const QString &root={}) const
Produces a DBus object path from the identifier.
int comparePropertyByIndex(CPropertyIndexRef index, const CIdentifier &compareValue) const
Compare for index.
Non-owning reference to a CPropertyIndex with a subset of its features.
CastType frontCasted() const
First element casted to given type, usually the PropertIndex enum.
bool isMyself() const
Myself index, used with nesting.
int comparePropertyByIndex(CPropertyIndexRef index, const Derived &compareValue) const
Compare for index.
Definition mixinindex.h:203
void setPropertyByIndex(CPropertyIndexRef index, const QVariant &variant)
Set property by index.
Definition mixinindex.h:167
QVariant propertyByIndex(CPropertyIndexRef index) const
Property by index.
Definition mixinindex.h:180
int compare(T a, T b)
Compare arithmetic values.
Free functions in swift::misc.
SWIFT_MISC_EXPORT QByteArray utfToPercentEncoding(const QString &s, const QByteArray &allow={}, char percent='%')
Extended percent encoding supporting UTF-16.
SWIFT_MISC_EXPORT QString utfFromPercentEncoding(const QByteArray &ba, char percent='%')
Reverse utfFromPercentEncoding.
QByteArray & append(QByteArrayView data)
int compare(QByteArrayView bv, Qt::CaseSensitivity cs) const const
QByteArray::FromBase64Result fromBase64Encoding(QByteArray &&base64, QByteArray::Base64Options options)
qint64 applicationPid()
QString localHostName()
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
void objectNameChanged(const QString &objectName)
bool contains(QChar ch, Qt::CaseSensitivity cs) const const
bool endsWith(QChar c, Qt::CaseSensitivity cs) const const
bool isEmpty() const const
qsizetype lastIndexOf(QChar ch, Qt::CaseSensitivity cs) const const
qsizetype length() const const
QString mid(qsizetype position, qsizetype n) &&
QString number(double n, char format, int precision)
QString section(QChar sep, qsizetype start, qsizetype end, QString::SectionFlags flags) const const
bool startsWith(QChar c, Qt::CaseSensitivity cs) const const
int toInt(bool *ok, int base) const const
QByteArray toLatin1() const const
QByteArray machineUniqueId()
CaseInsensitive
QUuid createUuid()
QUuid createUuidV5(QUuid ns, QByteArrayView baseData)
QString toString(QUuid::StringFormat mode) const const
QVariant fromValue(T &&value)
#define SWIFT_DEFINE_VALUEOBJECT_MIXINS(Namespace, Class)
Explicit template definition of mixins for a CValueObject subclass.
Definition valueobject.h:67