Debian Codegraph @

src/ddesktopentry.cpp

raw
1 // SPDX-FileCopyrightText: 2019 - 2022 UnionTech Software Technology Co., Ltd.
2 //
3 // SPDX-License-Identifier: LGPL-3.0-or-later
4
5 #include "ddesktopentry.h"
6
7 #include <QDir>
8 #include <QFileInfo>
9 #include <QMutex>
10 #include <QTemporaryFile>
11 #include <QDebug>
12 #include <QSaveFile>
13
14 DCORE_BEGIN_NAMESPACE
15
16 enum { Space = 0x1, Special = 0x2 };
17
18 static const char charTraits[256] = {
19 // Space: '\t', '\n', '\r', ' '
20 // Special: '\n', '\r', ';', '=', '\\', '#'
21 // Please note that '"' is NOT a special character
22
23 0, 0, 0, 0, 0, 0, 0, 0, 0, Space, Space | Special, 0, 0, Space | Special, 0, 0,
24 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
25 Space, 0, 0, Special, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
26 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Special, 0, Special, 0, 0,
27 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
28 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, Special, 0, 0, 0,
29 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
30 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
31
32 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
33 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
34 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
35 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
36 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
37 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
38 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
39 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
40 };
41
42 bool readLineFromData(const QByteArray &data, int &dataPos, int &lineStart, int &lineLen, int &equalsPos)
43 {
44 int dataLen = data.length();
45
46 equalsPos = -1;
47
48 lineStart = dataPos;
49 while (lineStart < dataLen && (charTraits[uint(uchar(data.at(lineStart)))] & Space))
50 ++lineStart;
51
52 int i = lineStart;
53 while (i < dataLen) {
54 while (!(charTraits[uint(uchar(data.at(i)))] & Special)) {
55 if (++i == dataLen)
56 goto break_out_of_outer_loop;
57 }
58
59 char ch = data.at(i++);
60 if (ch == '=') {
61 if (equalsPos == -1)
62 equalsPos = i - 1;
63 } else if (ch == '\n' || ch == '\r') {
64 if (i == lineStart + 1) {
65 ++lineStart;
66 } else {
67 --i;
68 goto break_out_of_outer_loop;
69 }
70 } else if (ch == '\\') {
71 if (i < dataLen) {
72 char ch = data.at(i++);
73 if (i < dataLen) {
74 char ch2 = data.at(i);
75 // \n, \r, \r\n, and \n\r are legitimate line terminators in INI files
76 if ((ch == '\n' && ch2 == '\r') || (ch == '\r' && ch2 == '\n'))
77 ++i;
78 }
79 }
80 } else if (ch == ';') {
81 // The multiple values should be separated by a semicolon and the value of the key
82 // may be optionally terminated by a semicolon. Trailing empty strings must always
83 // be terminated with a semicolon. Semicolons in these values need to be escaped
84 // using \; .
85 // Don't need to do anything here.
86 } else {
87 Q_ASSERT(ch == '#');
88
89 if (i == lineStart + 1) {
90 char ch;
91 while (i < dataLen && (((ch = data.at(i)) != '\n') && ch != '\r'))
92 ++i;
93 lineStart = i;
94 }
95 }
96 }
97
98 break_out_of_outer_loop:
99 dataPos = i;
100 lineLen = i - lineStart;
101 return lineLen > 0;
102 }
103
104 QString &doEscape(QString& str, const QHash<QChar,QChar> &repl)
105 {
106 // First we replace slash.
107 str.replace(QLatin1Char('\\'), QLatin1String("\\\\"));
108
109 QHashIterator<QChar,QChar> i(repl);
110 while (i.hasNext()) {
111 i.next();
112 if (i.key() != QLatin1Char('\\'))
113 str.replace(i.key(), QString::fromLatin1("\\\\%1").arg(i.value()));
114 }
115
116 return str;
117 }
118
119 QString &doUnescape(QString& str, const QHash<QChar,QChar> &repl)
120 {
121 int n = 0;
122 while (1) {
123 n=str.indexOf(QLatin1String("\\"), n);
124 if (n < 0 || n > str.length() - 2)
125 break;
126
127 if (repl.contains(str.at(n+1))) {
128 str.replace(n, 2, repl.value(str.at(n+1)));
129 }
130
131 n++;
132 }
133
134 return str;
135 }
136
137 /*! \internal */
138 class DDesktopEntrySection
139 {
140 public:
141 DDesktopEntrySection() {}
142
143 QString name;
144 QMap<QString, QString> valuesMap;
145 QByteArray unparsedDatas;
146 int sectionPos = 99;
147
148 inline operator QString() const {
149 return QLatin1String("DDesktopEntrySection(") + name + QLatin1String(")");
150 }
151
152 QByteArray sectionData() const {
153 if (unparsedDatas.isEmpty()) {
154 // construct data and return
155 QByteArray data;
156
157 data.append(QString("[%1]\n").arg(name).toLocal8Bit());
158
159 QMap<QString, QString>::const_iterator i;
160 for (i = valuesMap.begin(); i != valuesMap.end(); i++) {
161 data.append(QString("%1=%2\n").arg(i.key(), i.value()).toLocal8Bit());
162 }
163
164 return data;
165 } else {
166 return unparsedDatas;
167 }
168 }
169
170 bool ensureSectionDataParsed() {
171 if (unparsedDatas.isEmpty()) return true;
172
173 valuesMap.clear();
174
175 // for readLineFromFileData()
176 int dataPos = 0;
177 int lineStart;
178 int lineLen;
179 int equalsPos;
180
181 while(readLineFromData(unparsedDatas, dataPos, lineStart, lineLen, equalsPos)) {
182 if (unparsedDatas.at(lineStart) == '[') continue; // section name already parsed
183
184 if (equalsPos != -1) {
185 QString key = unparsedDatas.mid(lineStart, equalsPos - lineStart).trimmed();
186 QString rawValue = unparsedDatas.mid(equalsPos + 1, lineStart + lineLen - equalsPos - 1).trimmed();
187
188 valuesMap[key] = rawValue;
189 }
190 }
191
192 unparsedDatas.clear();
193
194 return true;
195 }
196
197 bool contains(const QString &key) const {
198 const_cast<DDesktopEntrySection*>(this)->ensureSectionDataParsed();
199 return valuesMap.contains(key);
200 }
201
202 QStringList allKeys() const {
203 const_cast<DDesktopEntrySection*>(this)->ensureSectionDataParsed();
204 return valuesMap.keys();
205 }
206
207 QString get(const QString &key, QString &defaultValue) {
208 if (this->contains(key)) {
209 return valuesMap[key];
210 } else {
211 return defaultValue;
212 }
213 }
214
215 bool set(const QString &key, const QString &value) {
216 if (this->contains(key)) {
217 valuesMap.remove(key);
218 }
219 valuesMap[key] = value;
220 return true;
221 }
222
223 bool remove(const QString &key) {
224 if (this->contains(key)) {
225 valuesMap.remove(key);
226 return true;
227 }
228 return false;
229 }
230 };
231
232 typedef QMap<QString, DDesktopEntrySection> SectionMap;
233
234 class DDesktopEntryPrivate
235 {
236 public:
237 DDesktopEntryPrivate(const QString &filePath, DDesktopEntry *qq);
238 ~DDesktopEntryPrivate();
239
240 bool isWritable() const;
241 bool fuzzyLoad();
242 bool initSectionsFromData(const QByteArray &data);
243 void setStatus(const DDesktopEntry::Status &newStatus) const;
244 bool write(QIODevice &device) const;
245
246 int sectionPos(const QString &sectionName) const;
247 bool contains(const QString &sectionName, const QString &key) const;
248 QStringList keys(const QString &sectionName) const;
249 bool get(const QString &sectionName, const QString &key, QString *value);
250 bool set(const QString &sectionName, const QString &key, const QString &value);
251 bool remove(const QString &sectionName, const QString &key);
252
253 protected:
254 QString filePath;
255 QMutex fileMutex;
256 SectionMap sectionsMap;
257 mutable DDesktopEntry::Status status;
258
259 private:
260 bool __padding[4];
261 DDesktopEntry *q_ptr = nullptr;
262
263 Q_DECLARE_PUBLIC(DDesktopEntry)
264 };
265
266 DDesktopEntryPrivate::DDesktopEntryPrivate(const QString &filePath, DDesktopEntry *qq)
267 : filePath(filePath), q_ptr(qq)
268 {
269 fuzzyLoad();
270 }
271
272 DDesktopEntryPrivate::~DDesktopEntryPrivate()
273 {
274
275 }
276
277 bool DDesktopEntryPrivate::isWritable() const
278 {
279 QFileInfo fileInfo(filePath);
280
281 #ifndef QT_NO_TEMPORARYFILE
282 if (fileInfo.exists()) {
283 #endif
284 QFile file(filePath);
285 return file.open(QFile::ReadWrite);
286 #ifndef QT_NO_TEMPORARYFILE
287 } else {
288 // Create the directories to the file.
289 QDir dir(fileInfo.absolutePath());
290 if (!dir.exists()) {
291 if (!dir.mkpath(dir.absolutePath()))
292 return false;
293 }
294
295 // we use a temporary file to avoid race conditions
296 QTemporaryFile file(filePath);
297 return file.open();
298 }
299 #endif
300 }
301
302 bool DDesktopEntryPrivate::fuzzyLoad()
303 {
304 QFile file(filePath);
305 QFileInfo fileInfo(filePath);
306
307 if (fileInfo.exists() && !file.open(QFile::ReadOnly)) {
308 setStatus(DDesktopEntry::AccessError);
309 return false;
310 }
311
312 if (file.isReadable() && file.size() != 0) {
313 bool ok = false;
314 QByteArray data = file.readAll();
315
316 ok = initSectionsFromData(data);
317
318 if (!ok) {
319 setStatus(DDesktopEntry::FormatError);
320 return false;
321 }
322 }
323
324 setStatus(DDesktopEntry::NoError);
325 return true;
326 }
327
328 bool DDesktopEntryPrivate::initSectionsFromData(const QByteArray &data)
329 {
330 sectionsMap.clear();
331
332 QString lastSectionName;
333 int lastSectionStart = 0;
334 bool formatOk = true;
335 int sectionIdx = 0;
336 // for readLineFromFileData()
337 int dataPos = 0;
338 int lineStart;
339 int lineLen;
340 int equalsPos;
341
342 auto commitSection = [=](const QString &name, int sectionStartPos, int sectionLength, int sectionIndex) {
343 DDesktopEntrySection lastSection;
344 lastSection.name = name;
345 lastSection.unparsedDatas = data.mid(sectionStartPos, sectionLength);
346 lastSection.sectionPos = sectionIndex;
347 sectionsMap[name] = lastSection;
348 };
349
350 // TODO: here we only need to find the section start, so things like equalsPos are useless here.
351 // maybe we can do some optimization here via adding extra argument to readLineFromData().
352 while(readLineFromData(data, dataPos, lineStart, lineLen, equalsPos)) {
353 // qDebug() << "CurrentLine:" << data.mid(lineStart, lineLen);
354 if (data.at(lineStart) == '[') {
355 // commit the last section we've ever read before we read the new one.
356 if (!lastSectionName.isEmpty()) {
357 commitSection(lastSectionName, lastSectionStart, lineStart - lastSectionStart, sectionIdx);
358 sectionIdx++;
359 }
360 // process section name line
361 QByteArray sectionName;
362 int idx = data.indexOf(']', lineStart);
363 if (idx == -1 || idx >= lineStart + lineLen) {
364 qWarning() << "Bad desktop file format while reading line:" << data.mid(lineStart, lineLen);
365 formatOk = false;
366 sectionName = data.mid(lineStart + 1, lineLen - 1).trimmed();
367 } else {
368 sectionName = data.mid(lineStart + 1, idx - lineStart - 1).trimmed();
369 }
370 lastSectionName = sectionName;
371 lastSectionStart = lineStart;
372 }
373 }
374
375 Q_ASSERT(lineStart == data.length());
376 if (!lastSectionName.isEmpty()) {
377 commitSection(lastSectionName, lastSectionStart, lineStart - lastSectionStart, sectionIdx);
378 }
379
380 return formatOk;
381 }
382
383 // Always keep the first meet error status. and allowed clear the status.
384 void DDesktopEntryPrivate::setStatus(const DDesktopEntry::Status &newStatus) const
385 {
386 if (newStatus == DDesktopEntry::NoError || this->status == DDesktopEntry::NoError) {
387 this->status = newStatus;
388 }
389 }
390
391 bool DDesktopEntryPrivate::write(QIODevice &device) const
392 {
393 Q_Q(const DDesktopEntry);
394
395 QStringList sortedKeys = q->allGroups(true);
396
397 for (const QString &key : sortedKeys) {
398 qint64 ret = device.write(sectionsMap[key].sectionData());
399 if (ret == -1) return false;
400 }
401
402 return true;
403 }
404
405 int DDesktopEntryPrivate::sectionPos(const QString &sectionName) const
406 {
407 if (sectionsMap.contains(sectionName)) {
408 return sectionsMap[sectionName].sectionPos;
409 }
410
411 return -1;
412 }
413
414 bool DDesktopEntryPrivate::contains(const QString &sectionName, const QString &key) const
415 {
416 if (sectionName.isNull() || key.isNull()) {
417 return false;
418 }
419
420 if (sectionsMap.contains(sectionName)) {
421 return sectionsMap[sectionName].contains(key);
422 }
423
424 return false;
425 }
426
427 QStringList DDesktopEntryPrivate::keys(const QString &sectionName) const
428 {
429 if (sectionName.isNull()) {
430 return {};
431 }
432
433 if (sectionsMap.contains(sectionName)) {
434 return sectionsMap[sectionName].allKeys();
435 }
436
437 return {};
438 }
439
440 // return true if we found the value, and set the value to *value
441 bool DDesktopEntryPrivate::get(const QString &sectionName, const QString &key, QString *value)
442 {
443 if (!this->contains(sectionName, key)) {
444 return false;
445 }
446
447 if (sectionsMap.contains(sectionName)) {
448 QString &&result = sectionsMap[sectionName].get(key, *value);
449 *value = result;
450 return true;
451 }
452
453 return false;
454 }
455
456 bool DDesktopEntryPrivate::set(const QString &sectionName, const QString &key, const QString &value)
457 {
458 if (sectionsMap.contains(sectionName)) {
459 bool result = sectionsMap[sectionName].set(key, value);
460 return result;
461 } else {
462 // create new section.
463 DDesktopEntrySection newSection;
464 newSection.name = sectionName;
465 newSection.set(key, value);
466 sectionsMap[sectionName] = newSection;
467 return true;
468 }
469
470 return false;
471 }
472
473 bool DDesktopEntryPrivate::remove(const QString &sectionName, const QString &key)
474 {
475 if (this->contains(sectionName, key)) {
476 return sectionsMap[sectionName].remove(key);
477 }
478 return false;
479 }
480
481 /*!
482 @~english
483 @class Dtk::Core::DDesktopEntry
484 \inmodule dtkcore
485 @brief Handling desktop entry files.
486
487 DDesktopEntry provide method for handling XDG desktop entry read and write. The interface
488 of this class is similar to QSettings.
489
490 For more details about the spec itself, please refer to:
491 https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html
492 */
493
494 DDesktopEntry::DDesktopEntry(const QString &filePath) noexcept
495 : d_ptr(new DDesktopEntryPrivate(filePath, this))
496 {
497
498 }
499
500 DDesktopEntry::~DDesktopEntry()
501 {
502
503 }
504
505 /*!
506 @~english
507 @brief Write back data to the desktop entry file.
508 @return true if write success; otherwise returns false.
509 */
510 bool DDesktopEntry::save() const
511 {
512 Q_D(const DDesktopEntry);
513
514 // write to file.
515 if (d->isWritable()) {
516 bool ok = false;
517 bool createFile = false;
518 QFileInfo fileInfo(d->filePath);
519
520 #if !defined(QT_BOOTSTRAPPED) && QT_CONFIG(temporaryfile)
521 QSaveFile sf(d->filePath);
522 sf.setDirectWriteFallback(true);
523 #else
524 QFile sf(d->filePath);
525 #endif
526 if (!sf.open(QIODevice::WriteOnly)) {
527 d->setStatus(DDesktopEntry::AccessError);
528 return false;
529 }
530
531 ok = d->write(sf);
532
533 #if !defined(QT_BOOTSTRAPPED) && QT_CONFIG(temporaryfile)
534 if (ok) {
535 ok = sf.commit();
536 }
537 #endif
538
539 if (ok) {
540 // If we have created the file, apply the file perms
541 if (createFile) {
542 QFile::Permissions perms = fileInfo.permissions() | QFile::ReadOwner | QFile::WriteOwner
543 | QFile::ReadGroup | QFile::ReadOther;
544 QFile(d->filePath).setPermissions(perms);
545 }
546 return true;
547 } else {
548 d->setStatus(DDesktopEntry::AccessError);
549 return false;
550 }
551 }
552
553 return false;
554 }
555
556 /*!
557 @~english
558 @brief Get data parse status
559
560 @return Returns a status code indicating the first error that was met by DDesktopEntry, or QSettings::NoError if no error occurred.
561
562 Be aware that DDesktopEntry delays performing some operations.
563 */
564 DDesktopEntry::Status DDesktopEntry::status() const
565 {
566 Q_D(const DDesktopEntry);
567 return d->status;
568 }
569
570 /*!
571 @~english
572 @brief Get a list of all section keys inside the given \a section.
573
574 @return all available section keys.
575 */
576 QStringList DDesktopEntry::keys(const QString &section) const
577 {
578 Q_D(const DDesktopEntry);
579
580 if (section.isEmpty()) {
581 qWarning("DDesktopEntry::keys: Empty section name passed");
582 return {};
583 }
584
585 return d->keys(section);
586 }
587
588 /*!
589 @~english
590 @brief Get a list of all section groups inside the desktop entry.
591
592 If \a sorted is set to true, the returned result will keep the order as-is when reading the entry file.
593
594 @return all available section groups.
595 */
596 QStringList DDesktopEntry::allGroups(bool sorted) const
597 {
598 Q_D(const DDesktopEntry);
599
600 if (!sorted) {
601 return d->sectionsMap.keys();
602 } else {
603 using StrIntPair = QPair<QString, int>;
604
605 QStringList keys = d->sectionsMap.keys();
606 QList<StrIntPair> result;
607
608 for (const QString & key : keys) {
609 result << StrIntPair(key, d->sectionPos(key));
610 }
611
612 std::sort(result.begin(), result.end(), [](const StrIntPair& a, const StrIntPair& b) -> bool {
613 return a.second < b.second;
614 });
615
616 keys.clear();
617
618 for (const StrIntPair& pair : result) {
619 keys << pair.first;
620 }
621
622 return keys;
623 }
624 }
625
626 /*!
627 @~english
628 @brief Check if the desktop entry file have the given \a section contains the given \a key
629
630 @return true if the desktop entry contains the \a key in \a section; otherwise returns false.
631 */
632 bool DDesktopEntry::contains(const QString &key, const QString &section) const
633 {
634 Q_D(const DDesktopEntry);
635
636 if (key.isEmpty() || section.isEmpty()) {
637 qWarning("DDesktopEntry::contains: Empty key or section passed");
638 return false;
639 }
640
641 return d->contains(section, key);
642 }
643
644 /*!
645 @~english
646 @brief Returns the localized string value of the "Name" key under "Desktop Entry" section.
647
648 It's equivalent to calling localizedValue("Name").
649
650 @return Returns the localized string value of the "Name" key under "Desktop Entry" section.
651
652 @sa localizedValue(), genericName(), ddeDisplayName()
653 */
654 QString DDesktopEntry::name() const
655 {
656 return localizedValue(QStringLiteral("Name"));
657 }
658
659 /*!
660 @~english
661 @brief Returns the localized string value of the "GenericName" key under "Desktop Entry" section.
662
663 It's equivalent to calling localizedValue("GenericName"). It will NOT fallback to "Name" if "GenericName"
664 is not existed.
665
666 @return Returns the localized string value of the "GenericName" key under "Desktop Entry" section.
667
668 @sa localizedValue(), name(), ddeDisplayName()
669 */
670 QString DDesktopEntry::genericName() const
671 {
672 return localizedValue(QStringLiteral("GenericName"));
673 }
674
675 /*!
676 @~english
677 @brief Display name specially for DDE applications.
678
679 This will check "X-Deepin-Vendor" and will return the localized string value of "GenericName" if
680 "X-Deepin-Vendor" is "deepin", or it will return the localized string value of "Name".
681
682 @return Returns the display name specially for DDE applications.
683
684 @sa localizedValue(), name(), genericName()
685 */
686 QString DDesktopEntry::ddeDisplayName() const
687 {
688 QString deepinVendor = stringValue("X-Deepin-Vendor");
689 QString genericNameStr = genericName();
690 if (deepinVendor == QStringLiteral("deepin") && !genericNameStr.isEmpty()) {
691 return genericNameStr;
692 }
693
694 return name();
695 }
696
697 /*!
698 @~english
699 @brief Returns the localized string value of the "Comment" key under "Desktop Entry" section.
700
701 It's equivalent to calling localizedValue("Comment").
702
703 @return Returns the localized string value of the "Comment" key under "Desktop Entry" section.
704
705 @sa localizedValue()
706 */
707 QString DDesktopEntry::comment() const
708 {
709 return localizedValue(QStringLiteral("Comment"));
710 }
711
712 /*!
713 @~english
714 @brief Returns the raw string value associated with the given \a key in \a section.
715
716 If the entry contains no item with the key, the function returns a constructed \a defaultValue.
717
718 @return Returns the raw string value associated with the given \a key in \a section.
719
720 @sa stringValue() localizedValue() stringListValue()
721 */
722 QString DDesktopEntry::rawValue(const QString &key, const QString &section, const QString &defaultValue) const
723 {
724 Q_D(const DDesktopEntry);
725 QString result = defaultValue;
726 if (key.isEmpty() || section.isEmpty()) {
727 qWarning("DDesktopEntry::value: Empty key or section passed");
728 return result;
729 }
730 const_cast<DDesktopEntryPrivate *>(d)->get(section, key, &result); // FIXME: better way than const_cast?
731 return result;
732 }
733
734 /*!
735 @~english
736 @brief Returns the unescaped string value associated with the given \a key in \a section.
737
738 If the entry contains no item with the key, the function returns a constructed \a defaultValue.
739
740 @return Returns the unescaped string value associated with the given \a key in \a section.
741
742 @sa rawValue() localizedValue() stringListValue()
743 */
744 QString DDesktopEntry::stringValue(const QString &key, const QString &section, const QString &defaultValue) const
745 {
746 QString rawResult = rawValue(key, section, defaultValue);
747 rawResult = DDesktopEntry::unescape(rawResult);
748 return rawResult;
749 }
750
751 /*!
752 @~english
753 @brief Returns the localized string value associated with the given \a key and \a localeKey in \a section.
754
755 If the given \a localeKey can't be found, it will fallback to "C", if still cannot found, will fallback to the
756 key without localeKey.
757
758 If the entry contains no item with the key, the function returns a constructed \a defaultValue.
759
760 @return Returns the localized string value associated with the given \a key and \a localeKey in \a section.
761
762 @sa rawValue() stringValue() stringListValue()
763 */
764 QString DDesktopEntry::localizedValue(const QString &key, const QString &localeKey, const QString &section, const QString &defaultValue) const
765 {
766 Q_D(const DDesktopEntry);
767 QString result = defaultValue;
768 QString actualLocaleKey = QLatin1String("C");
769 if (key.isEmpty() || section.isEmpty()) {
770 qWarning("DDesktopEntry::localizedValue: Empty key or section passed");
771 return result;
772 }
773
774 QStringList possibleKeys;
775
776 // 此处添加 bcp47Name() 是为了兼容 desktop 文件中的语言长短名解析。
777 // 比如芬兰语,有 [fi] 和 [fi_FI] 两种情况,QLocale::name() 对应 fi_FI,QLocale::bcp47Name() 对应 fi。
778 if (!localeKey.isEmpty()) {
779 if (localeKey == "empty") {
780 possibleKeys << key;
781 } else if (localeKey == "default") {
782 possibleKeys << QString("%1[%2]").arg(key, QLocale().name());
783 possibleKeys << QString("%1[%2]").arg(key, QLocale().bcp47Name());
784 } else if (localeKey == "system") {
785 possibleKeys << QString("%1[%2]").arg(key, QLocale::system().name());
786 possibleKeys << QString("%1[%2]").arg(key, QLocale::system().bcp47Name());
787 } else {
788 possibleKeys << QString("%1[%2]").arg(key, localeKey);
789 }
790 }
791
792 if (!actualLocaleKey.isEmpty()) {
793 possibleKeys << QString("%1[%2]").arg(key, actualLocaleKey);
794 }
795 possibleKeys << QString("%1[%2]").arg(key, "C");
796 possibleKeys << key;
797
798 for (const QString &oneKey : possibleKeys) {
799 if (d->contains(section, oneKey)) {
800 const_cast<DDesktopEntryPrivate *>(d)->get(section, oneKey, &result);
801 break;
802 }
803 }
804
805 return result;
806 }
807
808 /*!
809 @~english
810 @brief Returns the localized string value associated with the given \a key and \a locale in \a section.
811
812 If the given \a locale can't be found, it will fallback to "C", if still cannot found, will fallback to the
813 key without a locale key.
814
815 If the entry contains no item with the key, the function returns a default-constructed value.
816
817 @return Returns the localized string value associated with the given \a key and \a locale in \a section.
818
819 @sa rawValue() stringValue() stringListValue()
820 */
821 QString DDesktopEntry::localizedValue(const QString &key, const QLocale &locale, const QString &section, const QString &defaultValue) const
822 {
823 return localizedValue(key, locale.name(), section, defaultValue);
824 }
825
826 /*!
827 @~english
828 @brief Returns a list of strings associated with the given \a key in the given \a section.
829
830 If the entry contains no item with the key, the function returns a empty string list.
831
832 @return Returns a list of strings associated with the given \a key in the given \a section.
833
834 @sa rawValue() stringValue() localizedValue()
835 */
836 QStringList DDesktopEntry::stringListValue(const QString &key, const QString &section) const
837 {
838 Q_D(const DDesktopEntry);
839
840 QString value;
841
842 const_cast<DDesktopEntryPrivate *>(d)->get(section, key, &value);
843
844 if (value.endsWith(';')) {
845 value = value.left(value.length() - 1);
846 }
847 QStringList&& strings = value.split(';');
848
849 QString combine;
850 QStringList result;
851 for (QString oneStr : strings) {
852 if (oneStr.endsWith('\\')) {
853 combine = combine + oneStr + ';';
854 continue;
855 }
856 if (!combine.isEmpty()) {
857 oneStr = combine + oneStr;
858 combine.clear();
859 }
860 result << DDesktopEntry::unescape(oneStr, true);
861 }
862
863 return result;
864 }
865
866 bool DDesktopEntry::setRawValue(const QString &value, const QString &key, const QString &section)
867 {
868 Q_D(DDesktopEntry);
869 if (key.isEmpty() || section.isEmpty()) {
870 qWarning("DDesktopEntry::setRawValue: Empty key or section passed");
871 return false;
872 }
873
874 bool result = d->set(section, key, value);
875 return result;
876 }
877
878 bool DDesktopEntry::setStringValue(const QString &value, const QString &key, const QString &section)
879 {
880 QString escapedValue = value;
881 DDesktopEntry::escape(escapedValue);
882 bool result = setRawValue(escapedValue, key, section);
883 return result;
884 }
885
886 bool DDesktopEntry::setLocalizedValue(const QString &value, const QString &localeKey, const QString &key, const QString &section)
887 {
888 Q_D(DDesktopEntry);
889 if (key.isEmpty() || section.isEmpty()) {
890 qWarning("DDesktopEntry::setLocalizedValue: Empty key or section passed");
891 return false;
892 }
893
894 QString actualKey = localeKey.isEmpty() ? key : QString("%1[%2]").arg(key, localeKey);
895
896 bool result = d->set(section, actualKey, value);
897 return result;
898 }
899
900 bool DDesktopEntry::removeEntry(const QString &key, const QString &section)
901 {
902 Q_D(DDesktopEntry);
903 if (key.isEmpty() || section.isEmpty()) {
904 qWarning("DDesktopEntry::setLocalizedValue: Empty key or section passed");
905 return false;
906 }
907 bool result = d->remove(section, key);
908 return result;
909 }
910
911 /************************************************
912 The escape sequences \s, \n, \t, \r, and \\ are supported for values
913 of type string and localestring, meaning ASCII space, newline, tab,
914 carriage return, and backslash, respectively.
915 ************************************************/
916 QString &DDesktopEntry::escape(QString &str)
917 {
918 QHash<QChar,QChar> repl;
919 repl.insert(QLatin1Char('\n'), QLatin1Char('n'));
920 repl.insert(QLatin1Char('\t'), QLatin1Char('t'));
921 repl.insert(QLatin1Char('\r'), QLatin1Char('r'));
922
923 return doEscape(str, repl);
924 }
925
926 /************************************************
927 Quoting must be done by enclosing the argument between double quotes and
928 escaping the
929 double quote character,
930 backtick character ("`"),
931 dollar sign ("$") and
932 backslash character ("\")
933 by preceding it with an additional backslash character.
934 Implementations must undo quoting before expanding field codes and before
935 passing the argument to the executable program.
936
937 Note that the general escape rule for values of type string states that the
938 backslash character can be escaped as ("\\") as well and that this escape
939 rule is applied before the quoting rule. As such, to unambiguously represent a
940 literal backslash character in a quoted argument in a desktop entry file
941 requires the use of four successive backslash characters ("\\\\").
942 Likewise, a literal dollar sign in a quoted argument in a desktop entry file
943 is unambiguously represented with ("\\$").
944 ************************************************/
945 QString &DDesktopEntry::escapeExec(QString &str)
946 {
947 QHash<QChar,QChar> repl;
948 // The parseCombinedArgString() splits the string by the space symbols,
949 // we temporarily replace them on the special characters.
950 // Replacement will reverse after the splitting.
951 repl.insert(QLatin1Char('"'), QLatin1Char('"')); // double quote,
952 repl.insert(QLatin1Char('\''), QLatin1Char('\'')); // single quote ("'"),
953 repl.insert(QLatin1Char('\\'), QLatin1Char('\\')); // backslash character ("\"),
954 repl.insert(QLatin1Char('$'), QLatin1Char('$')); // dollar sign ("$"),
955
956 return doEscape(str, repl);
957 }
958
959 /*
960 The escape sequences \s, \n, \t, \r, and \\ are supported for values of type string and localestring,
961 meaning ASCII space, newline, tab, carriage return, and backslash, respectively.
962
963 Some keys can have multiple values. In such a case, the value of the key is specified as a plural: for
964 example, string(s). The multiple values should be separated by a semicolon and the value of the key may
965 be optionally terminated by a semicolon. Trailing empty strings must always be terminated with a semicolon.
966 Semicolons in these values need to be escaped using \;.
967
968 https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#value-types
969 */
970 QString &DDesktopEntry::unescape(QString &str, bool unescapeSemicolons)
971 {
972 QHash<QChar,QChar> repl;
973 repl.insert(QLatin1Char('\\'), QLatin1Char('\\'));
974 repl.insert(QLatin1Char('s'), QLatin1Char(' '));
975 repl.insert(QLatin1Char('n'), QLatin1Char('\n'));
976 repl.insert(QLatin1Char('t'), QLatin1Char('\t'));
977 repl.insert(QLatin1Char('r'), QLatin1Char('\r'));
978
979 if (unescapeSemicolons) {
980 repl.insert(QLatin1Char(';'), QLatin1Char(';'));
981 }
982
983 return doUnescape(str, repl);
984 }
985
986 /************************************************
987 Quoting must be done by enclosing the argument between double quotes and
988 escaping the
989 double quote character,
990 backtick character ("`"),
991 dollar sign ("$") and
992 backslash character ("\")
993 by preceding it with an additional backslash character.
994 Implementations must undo quoting before expanding field codes and before
995 passing the argument to the executable program.
996
997 Reserved characters are
998 space (" "),
999 tab,
1000 newline,
1001 double quote,
1002 single quote ("'"),
1003 backslash character ("\"),
1004 greater-than sign (">"),
1005 less-than sign ("<"),
1006 tilde ("~"),
1007 vertical bar ("|"),
1008 ampersand ("&"),
1009 semicolon (";"),
1010 dollar sign ("$"),
1011 asterisk ("*"),
1012 question mark ("?"),
1013 hash mark ("#"),
1014 parenthesis ("(") and (")")
1015 backtick character ("`").
1016
1017 Note that the general escape rule for values of type string states that the
1018 backslash character can be escaped as ("\\") as well and that this escape
1019 rule is applied before the quoting rule. As such, to unambiguously represent a
1020 literal backslash character in a quoted argument in a desktop entry file
1021 requires the use of four successive backslash characters ("\\\\").
1022 Likewise, a literal dollar sign in a quoted argument in a desktop entry file
1023 is unambiguously represented with ("\\$").
1024 ************************************************/
1025 QString &DDesktopEntry::unescapeExec(QString &str)
1026 {
1027 unescape(str);
1028 QHash<QChar,QChar> repl;
1029 // The parseCombinedArgString() splits the string by the space symbols,
1030 // we temporarily replace them on the special characters.
1031 // Replacement will reverse after the splitting.
1032 repl.insert(QLatin1Char(' '), QChar::fromLatin1(01)); // space
1033 repl.insert(QLatin1Char('\t'), QChar::fromLatin1(02)); // tab
1034 repl.insert(QLatin1Char('\n'), QChar::fromLatin1(03)); // newline,
1035
1036 repl.insert(QLatin1Char('"'), QLatin1Char('"')); // double quote,
1037 repl.insert(QLatin1Char('\''), QLatin1Char('\'')); // single quote ("'"),
1038 repl.insert(QLatin1Char('\\'), QLatin1Char('\\')); // backslash character ("\"),
1039 repl.insert(QLatin1Char('>'), QLatin1Char('>')); // greater-than sign (">"),
1040 repl.insert(QLatin1Char('<'), QLatin1Char('<')); // less-than sign ("<"),
1041 repl.insert(QLatin1Char('~'), QLatin1Char('~')); // tilde ("~"),
1042 repl.insert(QLatin1Char('|'), QLatin1Char('|')); // vertical bar ("|"),
1043 repl.insert(QLatin1Char('&'), QLatin1Char('&')); // ampersand ("&"),
1044 repl.insert(QLatin1Char(';'), QLatin1Char(';')); // semicolon (";"),
1045 repl.insert(QLatin1Char('$'), QLatin1Char('$')); // dollar sign ("$"),
1046 repl.insert(QLatin1Char('*'), QLatin1Char('*')); // asterisk ("*"),
1047 repl.insert(QLatin1Char('?'), QLatin1Char('?')); // question mark ("?"),
1048 repl.insert(QLatin1Char('#'), QLatin1Char('#')); // hash mark ("#"),
1049 repl.insert(QLatin1Char('('), QLatin1Char('(')); // parenthesis ("(")
1050 repl.insert(QLatin1Char(')'), QLatin1Char(')')); // parenthesis (")")
1051 repl.insert(QLatin1Char('`'), QLatin1Char('`')); // backtick character ("`").
1052
1053 return doUnescape(str, repl);
1054 }
1055
1056 bool DDesktopEntry::setStatus(const DDesktopEntry::Status &status)
1057 {
1058 Q_D(DDesktopEntry);
1059 d->setStatus(status);
1060
1061 return true;
1062 }
1063
1064 DCORE_END_NAMESPACE