refact: Desktop file parsing process and Application methods to

Properties

Signed-off-by: ComixHe <heyuming@deepin.org>
This commit is contained in:
ComixHe 2023-08-25 10:47:17 +08:00 committed by Comix
parent 9f2a8b6798
commit ccfb245419
11 changed files with 329 additions and 245 deletions

View File

@ -61,6 +61,30 @@
<annotation name="org.qtproject.QtDBus.QtTypeName" value="IconMap"/> <annotation name="org.qtproject.QtDBus.QtTypeName" value="IconMap"/>
</property> </property>
<property name="ActionName" type="a{ss}" access="read">
<annotation
name="org.freedesktop.DBus.Description"
value="The type of ActionName is a Map, where the key represents the locale and the value is the corresponding content."
/>
<annotation name="org.qtproject.QtDBus.QtTypeName" value="PropMap"/>
</property>
<property name="IconName" type="a{ss}" access="read">
<annotation
name="org.freedesktop.DBus.Description"
value="The type of IconName is a Map, where the key represents the action and the value is the corresponding content."
/>
<annotation name="org.qtproject.QtDBus.QtTypeName" value="PropMap"/>
</property>
<property name="DisplayName" type="a{ss}" access="read">
<annotation
name="org.freedesktop.DBus.Description"
value="The meaning of this property's type is same as which in ActionName."
/>
<annotation name="org.qtproject.QtDBus.QtTypeName" value="PropMap"/>
</property>
<method name="Launch"> <method name="Launch">
<arg type="s" name="action" direction="in" /> <arg type="s" name="action" direction="in" />
<arg type="as" name="fields" direction="in" /> <arg type="as" name="fields" direction="in" />
@ -84,38 +108,5 @@
This option might request a polikit authentication." This option might request a polikit authentication."
/> />
</method> </method>
<method name="GetActionName">
<arg name="identifier" type="s" direction="in"/>
<arg name="env" type="as" direction="in"/>
<arg name="name" type="s" direction="out"/>
<annotation
name="org.freedesktop.DBus.Description"
value="Given an action identifier
and optional locale-releate environments,
this method return the localized value of Name of
that action.
If env is not passed,
this method will use the locale config of that user."
/>
</method>
<method name="GetIconName">
<arg name="action" type="s" direction="in"/>
<arg name="name" type="s" direction="out"/>
<annotation
name="org.freedesktop.DBus.Description"
value="The meaning of arg `env` is same as which in GetActionName."
/>
</method>
<method name="GetDisplayName">
<arg name="env" type="as" direction="in"/>
<arg name="name" type="s" direction="out"/>
<annotation
name="org.freedesktop.DBus.Description"
value="The meaning of arg `env` is same as which in GetActionName."
/>
</method>
</interface> </interface>
</node> </node>

View File

@ -2,13 +2,14 @@
<node> <node>
<interface name="org.desktopspec.DBus.ObjectManager"> <interface name="org.desktopspec.DBus.ObjectManager">
<method name="GetManagedObjects"> <method name="GetManagedObjects">
<arg name="objectpath_and_interfaces" type="a{oas}" direction="out" /> <arg name="objpath_interfaces_and_properties" type="a{oa{sa{sv}}}" direction="out" />
<annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="ObjectMap"/> <annotation name="org.qtproject.QtDBus.QtTypeName.Out0" value="ObjectMap"/>
</method> </method>
<signal name="InterfacesAdded"> <signal name="InterfacesAdded">
<arg name="object_path" type="o" /> <arg name="object_path" type="o" />
<arg name="interfaces" type="as" /> <arg name="interfaces_and_properties" type="a{sa{sv}}" />
<annotation name="org.qtproject.QtDBus.QtTypeName.Out1" value="ObjectInterfaceMap"/>
</signal> </signal>
<signal name="InterfacesRemoved"> <signal name="InterfacesRemoved">

View File

@ -19,7 +19,13 @@ void registerComplexDbusType()
qDBusRegisterMetaType<QMap<QString, QDBusUnixFileDescriptor>>(); qDBusRegisterMetaType<QMap<QString, QDBusUnixFileDescriptor>>();
qDBusRegisterMetaType<QMap<uint, QMap<QString, QDBusUnixFileDescriptor>>>(); qDBusRegisterMetaType<QMap<uint, QMap<QString, QDBusUnixFileDescriptor>>>();
qDBusRegisterMetaType<IconMap>(); qDBusRegisterMetaType<IconMap>();
qRegisterMetaType<ObjectInterfaceMap>();
qDBusRegisterMetaType<ObjectInterfaceMap>();
qRegisterMetaType<ObjectMap>();
qDBusRegisterMetaType<ObjectMap>(); qDBusRegisterMetaType<ObjectMap>();
qDBusRegisterMetaType<QMap<QString, QString>>();
qRegisterMetaType<PropMap>();
qDBusRegisterMetaType<PropMap>();
} }
} // namespace } // namespace
@ -48,7 +54,7 @@ int main(int argc, char *argv[])
return false; return false;
} }
if (!AMService.addApplication(std::move(ret).value())) { if (!AMService.addApplication(std::move(ret).value())) {
qWarning() << "add Application failed:" << ret->sourcePath() << "skip..."; qWarning() << "add Application failed, skip...";
} }
return false; // means to apply this function to the rest of the files return false; // means to apply this function to the rest of the files
}); });

View File

@ -16,6 +16,7 @@ constexpr auto DDEApplicationManager1ServiceName =
#endif #endif
constexpr auto DDEApplicationManager1ObjectPath = u8"/org/deepin/dde/ApplicationManager1"; constexpr auto DDEApplicationManager1ObjectPath = u8"/org/deepin/dde/ApplicationManager1";
constexpr auto DDEAutoStartManager1ObjectPath = u8"/org/deepin/dde/AutoStartManager1";
constexpr auto DDEApplicationManager1JobManagerObjectPath = u8"/org/deepin/dde/ApplicationManager1/JobManager1"; constexpr auto DDEApplicationManager1JobManagerObjectPath = u8"/org/deepin/dde/ApplicationManager1/JobManager1";
constexpr auto DesktopFileEntryKey = u8"Desktop Entry"; constexpr auto DesktopFileEntryKey = u8"Desktop Entry";
constexpr auto DesktopFileActionKey = u8"Desktop Action "; constexpr auto DesktopFileActionKey = u8"Desktop Action ";

View File

@ -135,7 +135,7 @@ bool ApplicationManager1Service::addApplication(DesktopFile desktopFileSource) n
return false; return false;
} }
m_applicationList.insert(application->applicationPath(), application); m_applicationList.insert(application->applicationPath(), application);
emit InterfacesAdded(application->applicationPath(), getInterfacesListFromObject(ptr)); emit InterfacesAdded(application->applicationPath(), getChildInterfacesAndPropertiesFromObject(ptr));
return true; return true;
} }
@ -143,7 +143,7 @@ bool ApplicationManager1Service::addApplication(DesktopFile desktopFileSource) n
void ApplicationManager1Service::removeOneApplication(const QDBusObjectPath &application) noexcept void ApplicationManager1Service::removeOneApplication(const QDBusObjectPath &application) noexcept
{ {
if (auto it = m_applicationList.find(application); it != m_applicationList.cend()) { if (auto it = m_applicationList.find(application); it != m_applicationList.cend()) {
emit InterfacesRemoved(application, getInterfacesListFromObject(it->data())); emit InterfacesRemoved(application, getChildInterfacesFromObject(it->data()));
unregisterObjectFromDBus(application.path()); unregisterObjectFromDBus(application.path());
m_applicationList.remove(application); m_applicationList.remove(application);
} }
@ -225,7 +225,7 @@ void ApplicationManager1Service::updateApplication(const QSharedPointer<Applicat
} }
auto err = newEntry->parse(destApp->desktopFileSource()); auto err = newEntry->parse(destApp->desktopFileSource());
if (err != DesktopErrorCode::NoError and err != DesktopErrorCode::EntryKeyInvalid) { if (err != DesktopErrorCode::NoError) {
qWarning() << "update desktop file failed:" << err << ", content wouldn't change."; qWarning() << "update desktop file failed:" << err << ", content wouldn't change.";
return; return;
} }

View File

@ -46,7 +46,7 @@ public Q_SLOTS:
[[nodiscard]] ObjectMap GetManagedObjects() const; [[nodiscard]] ObjectMap GetManagedObjects() const;
Q_SIGNALS: Q_SIGNALS:
void InterfacesAdded(const QDBusObjectPath &object_path, const QStringList &interfaces); void InterfacesAdded(const QDBusObjectPath &object_path, const ObjectInterfaceMap &interfaces);
void InterfacesRemoved(const QDBusObjectPath &object_path, const QStringList &interfaces); void InterfacesRemoved(const QDBusObjectPath &object_path, const QStringList &interfaces);
private: private:

View File

@ -63,10 +63,8 @@ QSharedPointer<ApplicationService> ApplicationService::createApplicationService(
auto error = entry->parse(sourceStream); auto error = entry->parse(sourceStream);
if (error != DesktopErrorCode::NoError) { if (error != DesktopErrorCode::NoError) {
if (error != DesktopErrorCode::EntryKeyInvalid) { qWarning() << "parse failed:" << error << app->desktopFileSource().sourcePath();
qWarning() << "parse failed:" << error; return nullptr;
return nullptr;
}
} }
if (auto val = entry->value(DesktopFileEntryKey, "Hidden"); val.has_value()) { if (auto val = entry->value(DesktopFileEntryKey, "Hidden"); val.has_value()) {
@ -89,110 +87,6 @@ QSharedPointer<ApplicationService> ApplicationService::createApplicationService(
return app; return app;
} }
QString ApplicationService::GetActionName(const QString &identifier, const QStringList &env) const
{
const auto &supportedActions = actions();
if (supportedActions.isEmpty()) {
return {};
}
if (auto index = supportedActions.indexOf(identifier); index == -1) {
qWarning() << "can't find " << identifier << " in supported actions List.";
return {};
}
const auto &actionHeader = QString{"%1%2"}.arg(DesktopFileActionKey, identifier);
const auto &actionName = m_entry->value(actionHeader, "Name");
if (!actionName) {
return {};
}
QString locale{""};
bool ok;
if (!env.isEmpty()) {
QString lcStr;
for (const auto &lc : env) {
if (lc.startsWith("LANG")) {
locale = lc.split('=').last();
}
if (lc.startsWith("LC_ALL")) {
locale = lc.split('=').last();
break;
}
}
}
QLocale lc = locale.isEmpty() ? getUserLocale() : QLocale{locale};
const auto &name = actionName->toLocaleString(lc, ok);
if (!ok) {
qWarning() << "convert to locale string failed, dest locale:" << lc;
return {};
}
return name;
}
QString ApplicationService::GetDisplayName(const QStringList &env) const
{
const auto &displayName = m_entry->value(DesktopFileEntryKey, "Name");
if (!displayName) {
return {};
}
QString locale{""};
bool ok;
if (!env.isEmpty()) {
QString lcStr;
for (const auto &lc : env) {
if (lc.startsWith("LANG")) {
locale = lc.split('=').last();
}
if (lc.startsWith("LC_ALL")) {
locale = lc.split('=').last();
break;
}
}
}
QLocale lc = locale.isEmpty() ? getUserLocale() : QLocale{locale};
const auto &name = displayName->toLocaleString(lc, ok);
if (!ok) {
qWarning() << "convert to locale string failed, dest locale:" << lc;
return {};
}
return name;
}
QString ApplicationService::GetIconName(const QString &action) const
{
std::optional<DesktopEntry::Value> iconName{std::nullopt};
if (action.isEmpty()) {
iconName = m_entry->value(DesktopFileEntryKey, "Icon");
} else {
const auto &supportedActions = actions();
if (auto index = supportedActions.indexOf(action); index == -1) {
qWarning() << "can't find " << action << " in supported actions List.";
return {};
}
const auto &actionHeader = QString{"%1%2"}.arg(DesktopFileActionKey, action);
iconName = m_entry->value(actionHeader, "Icon");
}
if (!iconName) {
return {};
}
bool ok{false};
const auto &name = iconName->toIconString(ok);
return ok ? name : "";
}
QDBusObjectPath ApplicationService::Launch(const QString &action, const QStringList &fields, const QVariantMap &options) QDBusObjectPath ApplicationService::Launch(const QString &action, const QStringList &fields, const QVariantMap &options)
{ {
QString execStr; QString execStr;
@ -325,12 +219,55 @@ QStringList ApplicationService::actions() const noexcept
return {}; return {};
} }
auto actionList = str.split(";"); auto actionList = str.split(";", Qt::SkipEmptyParts);
actionList.removeAll("");
return actionList; return actionList;
} }
PropMap ApplicationService::actionName() const noexcept
{
PropMap ret;
auto actionList = actions();
for (auto &action : actionList) {
action.prepend(DesktopFileActionKey);
auto value = m_entry->value(action, "Name");
if (!value.has_value()) {
continue;
}
ret.insert(action, {std::move(value).value()});
}
return ret;
}
PropMap ApplicationService::displayName() const noexcept
{
PropMap ret;
auto value = std::move(m_entry->value(DesktopFileEntryKey, "Name")).value();
ret.insert(QString{"Name"}, {std::move(value)});
return ret;
}
PropMap ApplicationService::iconName() const noexcept
{
PropMap ret;
auto actionList = actions();
for (const auto &action : actionList) {
auto value = m_entry->value(QString{action}.prepend(DesktopFileActionKey), "Icon");
if (!value.has_value()) {
continue;
}
ret.insert(action, {std::move(value).value()});
}
auto mainIcon = m_entry->value(DesktopFileEntryKey, "Icon");
if (mainIcon.has_value()) {
ret.insert(defaultKeyStr, {std::move(mainIcon).value()});
}
return ret;
}
ObjectMap ApplicationService::GetManagedObjects() const ObjectMap ApplicationService::GetManagedObjects() const
{ {
return dumpDBusObject(m_Instances); return dumpDBusObject(m_Instances);
@ -384,7 +321,7 @@ bool ApplicationService::addOneInstance(const QString &instanceId, const QString
m_Instances.insert(QDBusObjectPath{objectPath}, QSharedPointer<InstanceService>{service}); m_Instances.insert(QDBusObjectPath{objectPath}, QSharedPointer<InstanceService>{service});
service->moveToThread(this->thread()); service->moveToThread(this->thread());
adaptor->moveToThread(this->thread()); adaptor->moveToThread(this->thread());
emit InterfacesAdded(QDBusObjectPath{objectPath}, getInterfacesListFromObject(service)); emit InterfacesAdded(QDBusObjectPath{objectPath}, getChildInterfacesAndPropertiesFromObject(service));
return true; return true;
} }
@ -396,7 +333,7 @@ bool ApplicationService::addOneInstance(const QString &instanceId, const QString
void ApplicationService::removeOneInstance(const QDBusObjectPath &instance) noexcept void ApplicationService::removeOneInstance(const QDBusObjectPath &instance) noexcept
{ {
if (auto it = m_Instances.find(instance); it != m_Instances.cend()) { if (auto it = m_Instances.find(instance); it != m_Instances.cend()) {
emit InterfacesRemoved(instance, getInterfacesListFromObject(it->data())); emit InterfacesRemoved(instance, getChildInterfacesFromObject(it->data()));
unregisterObjectFromDBus(instance.path()); unregisterObjectFromDBus(instance.path());
m_Instances.remove(instance); m_Instances.remove(instance);
} }

View File

@ -36,9 +36,18 @@ public:
Q_PROPERTY(QStringList Actions READ actions) Q_PROPERTY(QStringList Actions READ actions)
[[nodiscard]] QStringList actions() const noexcept; [[nodiscard]] QStringList actions() const noexcept;
Q_PROPERTY(PropMap ActionName READ actionName)
[[nodiscard]] PropMap actionName() const noexcept;
Q_PROPERTY(QString ID READ id CONSTANT) Q_PROPERTY(QString ID READ id CONSTANT)
[[nodiscard]] QString id() const noexcept; [[nodiscard]] QString id() const noexcept;
Q_PROPERTY(PropMap DisplayName READ displayName)
[[nodiscard]] PropMap displayName() const noexcept;
Q_PROPERTY(PropMap IconName READ iconName)
[[nodiscard]] PropMap iconName() const noexcept;
Q_PROPERTY(qulonglong LastLaunchedTime READ lastLaunchedTime) Q_PROPERTY(qulonglong LastLaunchedTime READ lastLaunchedTime)
[[nodiscard]] qulonglong lastLaunchedTime() const noexcept; [[nodiscard]] qulonglong lastLaunchedTime() const noexcept;
@ -71,14 +80,11 @@ public:
void resetEntry(DesktopEntry *newEntry) noexcept; void resetEntry(DesktopEntry *newEntry) noexcept;
public Q_SLOTS: public Q_SLOTS:
[[nodiscard]] QString GetActionName(const QString &identifier, const QStringList &env) const;
QDBusObjectPath Launch(const QString &action, const QStringList &fields, const QVariantMap &options); QDBusObjectPath Launch(const QString &action, const QStringList &fields, const QVariantMap &options);
[[nodiscard]] QString GetIconName(const QString &action) const;
[[nodiscard]] QString GetDisplayName(const QStringList &env) const;
[[nodiscard]] ObjectMap GetManagedObjects() const; [[nodiscard]] ObjectMap GetManagedObjects() const;
Q_SIGNALS: Q_SIGNALS:
void InterfacesAdded(const QDBusObjectPath &object_path, const QStringList &interfaces); void InterfacesAdded(const QDBusObjectPath &object_path, const ObjectInterfaceMap &interfaces);
void InterfacesRemoved(const QDBusObjectPath &object_path, const QStringList &interfaces); void InterfacesRemoved(const QDBusObjectPath &object_path, const QStringList &interfaces);
private: private:

View File

@ -17,26 +17,52 @@
auto DesktopEntry::parserGroupHeader(const QString &str) noexcept auto DesktopEntry::parserGroupHeader(const QString &str) noexcept
{ {
auto groupHeader = str.sliced(1, str.size() - 2); auto groupHeader = str.sliced(1, str.size() - 2).trimmed();
auto it = m_entryMap.find(groupHeader); decltype(m_entryMap)::iterator it{m_entryMap.end()};
if (it == m_entryMap.cend()) {
return m_entryMap.insert(groupHeader, {}); QRegularExpression re{R"([^\x20-\x5a-\x5e-\x7e\x5c])"};
auto matcher = re.match(groupHeader);
if (matcher.hasMatch()) {
return it;
} }
auto tmp = m_entryMap.find(groupHeader);
if (tmp == m_entryMap.end()) {
it = m_entryMap.insert(groupHeader, {});
}
return it; return it;
} }
QString DesktopFile::sourcePath() const noexcept QString DesktopFile::sourcePath() const noexcept
{ {
if (!m_fileSource) {
return "";
}
QFileInfo info(*m_fileSource); QFileInfo info(*m_fileSource);
return info.absoluteFilePath(); return info.absoluteFilePath();
} }
DesktopErrorCode DesktopEntry::parseEntry(const QString &str, decltype(m_entryMap)::iterator &currentGroup) noexcept bool DesktopEntry::isInvalidLocaleString(const QString &str) noexcept
{ {
if (str.startsWith("#")) { constexpr auto Language = R"((?:[a-z]+))"; // language of locale postfix. eg.(en, zh)
return DesktopErrorCode::NoError; constexpr auto Country = R"((?:_[A-Z]+))"; // country of locale postfix. eg.(US, CN)
} constexpr auto Encoding = R"((?:\.[0-9A-Z-]+))"; // encoding of locale postfix. eg.(UFT-8)
constexpr auto Modifier = R"((?:@[a-z=;]+))"; // modifier of locale postfix. eg.(euro;collation=traditional)
const static auto validKey = QString(R"(^%1%2?%3?%4?$)").arg(Language, Country, Encoding, Modifier);
// example: https://regex101.com/r/hylOay/2
static QRegularExpression re = []() -> QRegularExpression {
QRegularExpression tmp{validKey};
tmp.optimize();
return tmp;
}();
return re.match(str).hasMatch();
}
QPair<QString, QString> DesktopEntry::processEntry(const QString &str) noexcept
{
auto splitCharIndex = str.indexOf(']'); auto splitCharIndex = str.indexOf(']');
if (splitCharIndex != -1) { if (splitCharIndex != -1) {
for (; splitCharIndex < str.size(); ++splitCharIndex) { for (; splitCharIndex < str.size(); ++splitCharIndex) {
@ -49,56 +75,97 @@ DesktopErrorCode DesktopEntry::parseEntry(const QString &str, decltype(m_entryMa
} }
auto keyStr = str.first(splitCharIndex).trimmed(); auto keyStr = str.first(splitCharIndex).trimmed();
auto valueStr = str.sliced(splitCharIndex + 1).trimmed(); auto valueStr = str.sliced(splitCharIndex + 1).trimmed();
return qMakePair(std::move(keyStr), std::move(valueStr));
}
std::optional<QPair<QString, QString>> DesktopEntry::processEntryKey(const QString &keyStr) noexcept
{
QString key; QString key;
QString valueKey{defaultKeyStr}; QString localeStr;
if (auto index = keyStr.indexOf('['); index != -1) {
constexpr auto MainKey = R"re((?<MainKey>[0-9a-zA-Z-]+))re"; // main key. eg.(Name, X-CUSTOM-KEY). key = keyStr.sliced(0, index);
constexpr auto Language = R"re((?:[a-z]+))re"; // language of locale postfix. eg.(en, zh) localeStr = keyStr.sliced(index + 1, keyStr.length() - 1 - index - 1); // strip '[' and ']'
constexpr auto Country = R"re((?:_[A-Z]+))re"; // country of locale postfix. eg.(US, CN) } else {
constexpr auto Encoding = R"re((?:\.[0-9A-Z-]+))re"; // encoding of locale postfix. eg.(UFT-8) key = keyStr;
constexpr auto Modifier = R"re((?:@[a-z=;]+))re"; // modifier of locale postfix. eg(euro;collation=traditional)
const static auto validKey =
QString("^%1(?:\\[(?<LOCALE>%2%3?%4?%5?)\\])?$").arg(MainKey).arg(Language).arg(Country).arg(Encoding).arg(Modifier);
// example: https://regex101.com/r/hylOay/1
static QRegularExpression re = []() -> QRegularExpression {
QRegularExpression tmp{validKey};
tmp.optimize();
return tmp;
}();
auto matcher = re.match(keyStr);
if (!matcher.hasMatch()) {
#ifdef DEBUG_MODE
qWarning() << "invalid key: " << keyStr;
#endif
return DesktopErrorCode::EntryKeyInvalid;
} }
key = matcher.captured("MainKey"); QRegularExpression re{"R([^A-Za-z0-9-])"};
if (re.match(key).hasMatch()) {
if (auto locale = matcher.captured("LOCALE"); !locale.isEmpty()) { qWarning() << "keyName's format is invalid.";
valueKey = locale; return std::nullopt;
} }
auto cur = currentGroup->find(key); return qMakePair(std::move(key), std::move(localeStr));
if (cur == currentGroup->end()) { }
currentGroup->insert(keyStr, {{valueKey, valueStr}});
DesktopErrorCode DesktopEntry::parseEntry(const QString &str, decltype(m_entryMap)::iterator &currentGroup) noexcept
{
auto [key, value] = processEntry(str);
auto keyPair = processEntryKey(key);
if (!keyPair.has_value()) {
return DesktopErrorCode::InvalidFormat;
}
auto [keyName, localeStr] = std::move(keyPair).value();
if (localeStr.isEmpty()) {
localeStr = defaultKeyStr;
}
auto valueIt = currentGroup->find(keyName);
if (valueIt == currentGroup->end()) {
currentGroup->insert(keyName, {{localeStr, value}});
return DesktopErrorCode::NoError; return DesktopErrorCode::NoError;
} }
auto value = cur->find(valueKey); auto innerIt = valueIt->find(localeStr);
if (value == cur->end()) { if (innerIt == valueIt->end()) {
cur->insert(valueKey, valueStr); valueIt->insert(localeStr, value);
return DesktopErrorCode::NoError; return DesktopErrorCode::NoError;
} }
qWarning() << "duplicated postfix and this line will be aborted, maybe format is invalid.\n" qWarning() << "duplicated postfix and this line will be aborted, maybe format is invalid.\n"
<< "exist: " << value.key() << "[" << value.value() << "]" << "exist: " << innerIt.key() << "[" << innerIt.value() << "]"
<< "current: " << str; << "current: " << keyName << "[" << localeStr << "]";
return DesktopErrorCode::NoError; return DesktopErrorCode::NoError;
} }
bool DesktopEntry::checkMainEntryValidation() const noexcept
{
auto it = m_entryMap.find(DesktopFileEntryKey);
if (it == m_entryMap.end()) {
return false;
}
if (auto name = it->find("Name"); name == it->end()) {
qWarning() << "No Name.";
return false;
}
auto type = it->find("Type");
if (type == it->end()) {
qWarning() << "No Type.";
for (const auto &[k, v] : it->asKeyValueRange()) {
qInfo() << "keyName:" << k;
for (const auto &[key, value] : v.asKeyValueRange()) {
qInfo() << key << value;
}
}
return false;
}
const auto &typeStr = *type->find(defaultKeyStr);
if (typeStr == "Link") {
if (it->find("URL") == it->end()) {
return false;
}
}
return true;
}
std::optional<DesktopFile> DesktopFile::createTemporaryDesktopFile(std::unique_ptr<QFile> temporaryFile) noexcept std::optional<DesktopFile> DesktopFile::createTemporaryDesktopFile(std::unique_ptr<QFile> temporaryFile) noexcept
{ {
auto mtime = getFileModifiedTime(*temporaryFile); auto mtime = getFileModifiedTime(*temporaryFile);
@ -228,9 +295,17 @@ DesktopErrorCode DesktopEntry::parse(DesktopFile &file) noexcept
return parse(stream); return parse(stream);
} }
bool DesktopEntry::skipCheck(const QString &line) noexcept
{
return line.startsWith('#') or line.isEmpty();
}
DesktopErrorCode DesktopEntry::parse(QTextStream &stream) noexcept DesktopErrorCode DesktopEntry::parse(QTextStream &stream) noexcept
{ {
if (stream.atEnd()) { if (stream.atEnd()) {
if (m_context == EntryContext::Done) {
return DesktopErrorCode::NoError;
}
return DesktopErrorCode::OpenFailed; return DesktopErrorCode::OpenFailed;
} }
@ -238,28 +313,74 @@ DesktopErrorCode DesktopEntry::parse(QTextStream &stream) noexcept
decltype(m_entryMap)::iterator currentGroup; decltype(m_entryMap)::iterator currentGroup;
DesktopErrorCode err{DesktopErrorCode::NoError}; DesktopErrorCode err{DesktopErrorCode::NoError};
bool mainEntryParsed{false};
QString line;
while (!stream.atEnd()) { while (!stream.atEnd()) {
auto line = stream.readLine().trimmed(); switch (m_context) {
case EntryContext::Unknown: {
qWarning() << "entry context is unknown,abort.";
err = DesktopErrorCode::InvalidFormat;
return err;
} break;
case EntryContext::EntryOuter: {
if (skipCheck(line)) {
line = stream.readLine().trimmed();
continue;
}
if (line.isEmpty()) { if (line.startsWith('[')) {
continue; auto group = parserGroupHeader(line);
}
if (line[0] == '[') { if (group == m_entryMap.end()) {
if (!(line[line.size() - 1] == ']')) { qWarning() << "groupName format error or already exists:" << line;
return DesktopErrorCode::GroupHeaderInvalid; return DesktopErrorCode::InvalidFormat;
} }
currentGroup = parserGroupHeader(line); currentGroup = group;
continue; bool isMainEntry = (currentGroup.key() == DesktopFileEntryKey);
}
if (auto error = parseEntry(line, currentGroup); error != DesktopErrorCode::NoError) { if ((!mainEntryParsed and isMainEntry) or (mainEntryParsed and !isMainEntry)) {
err = error; m_context = EntryContext::Entry;
#ifdef DEBUG_MODE continue;
qWarning() << "an error occurred,this line will be skipped:" << line; }
#endif }
qWarning() << "groupName format error:" << line;
err = DesktopErrorCode::InvalidFormat;
return err;
} break;
case EntryContext::Entry: {
line = stream.readLine().trimmed();
if (skipCheck(line)) {
continue;
}
if (line.startsWith('[')) {
m_context = EntryContext::EntryOuter;
if (currentGroup.key() == DesktopFileEntryKey) {
mainEntryParsed = true;
}
continue;
}
err = parseEntry(line, currentGroup);
if (err != DesktopErrorCode::NoError) {
qWarning() << "Entry format error:" << line;
return err;
}
} break;
case EntryContext::Done:
break;
} }
} }
m_context = EntryContext::Done;
if (!checkMainEntryValidation()) {
qWarning() << "invalid MainEntry, abort.";
err = DesktopErrorCode::MissingInfo;
}
return err; return err;
} }
@ -425,12 +546,12 @@ QDebug operator<<(QDebug debug, const DesktopErrorCode &v)
errMsg = "couldn't open the file."; errMsg = "couldn't open the file.";
break; break;
} }
case DesktopErrorCode::GroupHeaderInvalid: { case DesktopErrorCode::InvalidFormat: {
errMsg = "groupHead syntax is invalid."; errMsg = "the format of desktopEntry file is invalid.";
break; break;
} }
case DesktopErrorCode::EntryKeyInvalid: { case DesktopErrorCode::MissingInfo: {
errMsg = "key syntax is invalid."; errMsg = "missing required infomation.";
break; break;
} }
} }

View File

@ -15,15 +15,9 @@
constexpr static auto defaultKeyStr = "default"; constexpr static auto defaultKeyStr = "default";
enum class DesktopErrorCode { enum class DesktopErrorCode { NoError, NotFound, MismatchedFile, InvalidLocation, InvalidFormat, OpenFailed, MissingInfo };
NoError,
NotFound, enum class EntryContext { Unknown, EntryOuter, Entry, Done };
MismatchedFile,
InvalidLocation,
OpenFailed,
GroupHeaderInvalid,
EntryKeyInvalid
};
struct DesktopFileGuard; struct DesktopFileGuard;
@ -104,18 +98,10 @@ private:
class DesktopEntry class DesktopEntry
{ {
public: public:
class Value final : private QMap<QString, QString> class Value final : public QMap<QString, QString>
{ {
public: public:
using QMap<QString, QString>::QMap; using QMap<QString, QString>::QMap;
using QMap<QString, QString>::find;
using QMap<QString, QString>::insert;
using QMap<QString, QString>::cbegin;
using QMap<QString, QString>::cend;
using QMap<QString, QString>::begin;
using QMap<QString, QString>::end;
using QMap<QString, QString>::asKeyValueRange;
QString toString(bool &ok) const noexcept; QString toString(bool &ok) const noexcept;
bool toBoolean(bool &ok) const noexcept; bool toBoolean(bool &ok) const noexcept;
QString toIconString(bool &ok) const noexcept; QString toIconString(bool &ok) const noexcept;
@ -138,11 +124,18 @@ public:
[[nodiscard]] DesktopErrorCode parse(QTextStream &stream) noexcept; [[nodiscard]] DesktopErrorCode parse(QTextStream &stream) noexcept;
[[nodiscard]] std::optional<QMap<QString, Value>> group(const QString &key) const noexcept; [[nodiscard]] std::optional<QMap<QString, Value>> group(const QString &key) const noexcept;
[[nodiscard]] std::optional<Value> value(const QString &key, const QString &valueKey) const noexcept; [[nodiscard]] std::optional<Value> value(const QString &key, const QString &valueKey) const noexcept;
static bool isInvalidLocaleString(const QString &str) noexcept;
private: private:
EntryContext m_context{EntryContext::EntryOuter};
QMap<QString, QMap<QString, Value>> m_entryMap; QMap<QString, QMap<QString, Value>> m_entryMap;
auto parserGroupHeader(const QString &str) noexcept; auto parserGroupHeader(const QString &str) noexcept;
[[nodiscard]] bool checkMainEntryValidation() const noexcept;
static bool skipCheck(const QString &line) noexcept;
static DesktopErrorCode parseEntry(const QString &str, decltype(m_entryMap)::iterator &currentGroup) noexcept; static DesktopErrorCode parseEntry(const QString &str, decltype(m_entryMap)::iterator &currentGroup) noexcept;
static QPair<QString, QString> processEntry(const QString &str) noexcept;
static std::optional<QPair<QString, QString>> processEntryKey(const QString &keyStr) noexcept;
}; };
QDebug operator<<(QDebug debug, const DesktopEntry::Value &v); QDebug operator<<(QDebug debug, const DesktopEntry::Value &v);

View File

@ -27,7 +27,13 @@
Q_DECLARE_LOGGING_CATEGORY(DDEAMProf) Q_DECLARE_LOGGING_CATEGORY(DDEAMProf)
using IconMap = QMap<QString, QMap<uint, QMap<QString, QDBusUnixFileDescriptor>>>; using IconMap = QMap<QString, QMap<uint, QMap<QString, QDBusUnixFileDescriptor>>>;
using ObjectMap = QMap<QDBusObjectPath, QStringList>; using ObjectInterfaceMap = QMap<QString, QVariantMap>;
using ObjectMap = QMap<QDBusObjectPath, ObjectInterfaceMap>;
using PropMap = QMap<QString, QMap<QString, QString>>;
Q_DECLARE_METATYPE(ObjectInterfaceMap)
Q_DECLARE_METATYPE(ObjectMap)
Q_DECLARE_METATYPE(PropMap)
inline QString getApplicationLauncherBinary() inline QString getApplicationLauncherBinary()
{ {
@ -200,17 +206,39 @@ inline QString getDBusInterface(const QMetaType &meta)
return {}; return {};
} }
inline QStringList getInterfacesListFromObject(QObject *o) inline ObjectInterfaceMap getChildInterfacesAndPropertiesFromObject(QObject *o)
{ {
auto childs = o->children(); auto childs = o->children();
QStringList interfaces; ObjectInterfaceMap ret;
std::for_each(childs.cbegin(), childs.cend(), [&interfaces](QObject *app) {
std::for_each(childs.cbegin(), childs.cend(), [&ret](QObject *app) {
if (app->inherits("QDBusAbstractAdaptor")) { if (app->inherits("QDBusAbstractAdaptor")) {
interfaces.emplace_back(getDBusInterface(app->metaObject()->metaType())); auto interface = getDBusInterface(app->metaObject()->metaType());
QVariantMap properties;
const auto *mo = app->metaObject();
for (int i = mo->propertyOffset(); i < mo->propertyCount(); ++i) {
auto prop = mo->property(i);
properties.insert(prop.name(), prop.read(app));
}
ret.insert(interface, properties);
} }
}); });
return interfaces; return ret;
}
inline QStringList getChildInterfacesFromObject(QObject *o)
{
auto childs = o->children();
QStringList ret;
std::for_each(childs.cbegin(), childs.cend(), [&ret](QObject *app) {
if (app->inherits("QDBusAbstractAdaptor")) {
ret.append(getDBusInterface(app->metaObject()->metaType()));
}
});
return ret;
} }
inline uid_t getCurrentUID() inline uid_t getCurrentUID()
@ -399,8 +427,8 @@ ObjectMap dumpDBusObject(const QMap<QDBusObjectPath, QSharedPointer<T>> &map)
ObjectMap objs; ObjectMap objs;
for (const auto &[key, value] : map.asKeyValueRange()) { for (const auto &[key, value] : map.asKeyValueRange()) {
auto interfaces = getInterfacesListFromObject(value.data()); auto interAndProps = getChildInterfacesAndPropertiesFromObject(value.data());
objs.insert(key, interfaces); objs.insert(key, interAndProps);
} }
return objs; return objs;