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 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
|
/* BEGIN_COMMON_COPYRIGHT_HEADER
* (c)LGPL2+
*
* LXQt - a lightweight, Qt based, desktop toolset
* https://lxqt.org
*
* Copyright: 2010-2011 Razor team
* Authors:
* Alexander Sokoloff <sokoloff.a@gmail.com>
*
* This program or library is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General
* Public License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* END_COMMON_COPYRIGHT_HEADER */
#include "desktopenvironment_p.cpp"
#include "xdgdesktopfile.h"
#include "xdgdesktopfile_p.h"
#include "xdgdirs.h"
#include "xdgicon.h"
#include "application_interface.h"
#include <stdlib.h>
#include <unistd.h>
#include <QDebug>
#include <QDBusInterface>
#include <QDBusObjectPath>
#include <QDesktopServices>
#include <QDir>
#include <QSharedData>
#include <QFile>
#include <QFileInfo>
#include <QHash>
#include <QList>
#include <QMimeDatabase>
#include <QMimeType>
#include <QProcess>
#include <QSettings>
#include <QStandardPaths>
#include <QTextStream>
#include <QUrl>
#include <QtAlgorithms>
/**
* See: http://standards.freedesktop.org/desktop-entry-spec
*/
// A list of executables that can't be run with QProcess::startDetached(). They
// will be run with QProcess::start()
static const QStringList nonDetachExecs = QStringList()
<< QLatin1String("pkexec");
static const QLatin1String onlyShowInKey("OnlyShowIn");
static const QLatin1String notShowInKey("NotShowIn");
static const QLatin1String categoriesKey("Categories");
static const QLatin1String actionsKey("Actions");
static const QLatin1String extendPrefixKey("X-");
static const QLatin1String mimeTypeKey("MimeType");
static const QLatin1String applicationsStr("applications");
static const QLatin1String nameKey("Name");
static const QLatin1String typeKey("Type");
static const QLatin1String ApplicationStr("Application");
static const QLatin1String LinkStr("Link");
static const QLatin1String DirectoryStr("Directory");
static const QLatin1String execKey("Exec");
static const QLatin1String urlKey("URL");
static const QLatin1String iconKey("Icon");
static const QLatin1String initialPreferenceKey("InitialPreference");
// Helper functions prototypes
bool checkTryExec(const QString& progName);
QString &doEscape(QString& str, const QHash<QChar,QChar> &repl);
QString &doUnEscape(QString& str, const QHash<QChar,QChar> &repl);
QString &escape(QString& str);
QString &escapeExec(QString& str);
QString expandDynamicUrl(QString url);
QString expandEnvVariables(const QString str);
QStringList expandEnvVariables(const QStringList strs);
QString findDesktopFile(const QString& dirName, const QString& desktopName);
QString findDesktopFile(const QString& desktopName);
static QStringList parseCombinedArgString(const QString &program);
bool read(const QString &prefix);
void replaceVar(QString &str, const QString &varName, const QString &after);
QString &unEscape(QString& str);
QString &unEscapeExec(QString& str);
void loadMimeCacheDir(const QString& dirName, QHash<QString, QList<XdgDesktopFile*> > & cache);
namespace
{
//! Simple helper for getting timeout for starting of DBus activatable applications
class DBusActivateTimeout
{
private:
int mTimeoutMs;
DBusActivateTimeout()
{
bool ok;
mTimeoutMs = qgetenv("QTXDG_DBUSACTIVATE_TIMEOUT").toInt(&ok);
if (!ok)
mTimeoutMs = 1500;
}
static DBusActivateTimeout msInstance;
public:
static const DBusActivateTimeout & instance() { return msInstance; }
operator int() const { return mTimeoutMs; }
};
DBusActivateTimeout DBusActivateTimeout::msInstance;
}
QString &doEscape(QString& str, const QHash<QChar,QChar> &repl)
{
// First we replace slash.
str.replace(QLatin1Char('\\'), QLatin1String("\\\\"));
QHashIterator<QChar,QChar> i(repl);
while (i.hasNext()) {
i.next();
if (i.key() != QLatin1Char('\\'))
str.replace(i.key(), QString::fromLatin1("\\\\%1").arg(i.value()));
}
return str;
}
/************************************************
The escape sequences \s, \n, \t, \r, and \\ are supported for values
of type string and localestring, meaning ASCII space, newline, tab,
carriage return, and backslash, respectively.
************************************************/
QString &escape(QString& str)
{
QHash<QChar,QChar> repl;
repl.insert(QLatin1Char('\n'), QLatin1Char('n'));
repl.insert(QLatin1Char('\t'), QLatin1Char('t'));
repl.insert(QLatin1Char('\r'), QLatin1Char('r'));
return doEscape(str, repl);
}
/************************************************
Quoting must be done by enclosing the argument between double quotes and
escaping the
double quote character,
backtick character ("`"),
dollar sign ("$") and
backslash character ("\")
by preceding it with an additional backslash character.
Implementations must undo quoting before expanding field codes and before
passing the argument to the executable program.
Note that the general escape rule for values of type string states that the
backslash character can be escaped as ("\\") as well and that this escape
rule is applied before the quoting rule. As such, to unambiguously represent a
literal backslash character in a quoted argument in a desktop entry file
requires the use of four successive backslash characters ("\\\\").
Likewise, a literal dollar sign in a quoted argument in a desktop entry file
is unambiguously represented with ("\\$").
************************************************/
QString &escapeExec(QString& str)
{
QHash<QChar,QChar> repl;
// The parseCombinedArgString() splits the string by the space symbols,
// we temporarily replace them on the special characters.
// Replacement will reverse after the splitting.
repl.insert(QLatin1Char('"'), QLatin1Char('"')); // double quote,
repl.insert(QLatin1Char('\''), QLatin1Char('\'')); // single quote ("'"),
repl.insert(QLatin1Char('\\'), QLatin1Char('\\')); // backslash character ("\"),
repl.insert(QLatin1Char('$'), QLatin1Char('$')); // dollar sign ("$"),
return doEscape(str, repl);
}
QString &doUnEscape(QString& str, const QHash<QChar,QChar> &repl)
{
int n = 0;
while (1)
{
n=str.indexOf(QLatin1String("\\"), n);
if (n < 0 || n > str.length() - 2)
break;
if (repl.contains(str.at(n+1)))
{
str.replace(n, 2, repl.value(str.at(n+1)));
}
n++;
}
return str;
}
/************************************************
The escape sequences \s, \n, \t, \r, and \\ are supported for values
of type string and localestring, meaning ASCII space, newline, tab,
carriage return, and backslash, respectively.
************************************************/
QString &unEscape(QString& str)
{
QHash<QChar,QChar> repl;
repl.insert(QLatin1Char('\\'), QLatin1Char('\\'));
repl.insert(QLatin1Char('s'), QLatin1Char(' '));
repl.insert(QLatin1Char('n'), QLatin1Char('\n'));
repl.insert(QLatin1Char('t'), QLatin1Char('\t'));
repl.insert(QLatin1Char('r'), QLatin1Char('\r'));
return doUnEscape(str, repl);
}
/************************************************
Quoting must be done by enclosing the argument between double quotes and
escaping the
double quote character,
backtick character ("`"),
dollar sign ("$") and
backslash character ("\")
by preceding it with an additional backslash character.
Implementations must undo quoting before expanding field codes and before
passing the argument to the executable program.
Reserved characters are
space (" "),
tab,
newline,
double quote,
single quote ("'"),
backslash character ("\"),
greater-than sign (">"),
less-than sign ("<"),
tilde ("~"),
vertical bar ("|"),
ampersand ("&"),
semicolon (";"),
dollar sign ("$"),
asterisk ("*"),
question mark ("?"),
hash mark ("#"),
parenthesis ("(") and (")")
backtick character ("`").
Note that the general escape rule for values of type string states that the
backslash character can be escaped as ("\\") as well and that this escape
rule is applied before the quoting rule. As such, to unambiguously represent a
literal backslash character in a quoted argument in a desktop entry file
requires the use of four successive backslash characters ("\\\\").
Likewise, a literal dollar sign in a quoted argument in a desktop entry file
is unambiguously represented with ("\\$").
************************************************/
QString &unEscapeExec(QString& str)
{
unEscape(str);
QHash<QChar,QChar> repl;
// The parseCombinedArgString() splits the string by the space symbols,
// we temporarily replace them on the special characters.
// Replacement will reverse after the splitting.
repl.insert(QLatin1Char(' '), 01); // space
repl.insert(QLatin1Char('\t'), 02); // tab
repl.insert(QLatin1Char('\n'), 03); // newline,
repl.insert(QLatin1Char('"'), QLatin1Char('"')); // double quote,
repl.insert(QLatin1Char('\''), QLatin1Char('\'')); // single quote ("'"),
repl.insert(QLatin1Char('\\'), QLatin1Char('\\')); // backslash character ("\"),
repl.insert(QLatin1Char('>'), QLatin1Char('>')); // greater-than sign (">"),
repl.insert(QLatin1Char('<'), QLatin1Char('<')); // less-than sign ("<"),
repl.insert(QLatin1Char('~'), QLatin1Char('~')); // tilde ("~"),
repl.insert(QLatin1Char('|'), QLatin1Char('|')); // vertical bar ("|"),
repl.insert(QLatin1Char('&'), QLatin1Char('&')); // ampersand ("&"),
repl.insert(QLatin1Char(';'), QLatin1Char(';')); // semicolon (";"),
repl.insert(QLatin1Char('$'), QLatin1Char('$')); // dollar sign ("$"),
repl.insert(QLatin1Char('*'), QLatin1Char('*')); // asterisk ("*"),
repl.insert(QLatin1Char('?'), QLatin1Char('?')); // question mark ("?"),
repl.insert(QLatin1Char('#'), QLatin1Char('#')); // hash mark ("#"),
repl.insert(QLatin1Char('('), QLatin1Char('(')); // parenthesis ("(")
repl.insert(QLatin1Char(')'), QLatin1Char(')')); // parenthesis (")")
repl.insert(QLatin1Char('`'), QLatin1Char('`')); // backtick character ("`").
return doUnEscape(str, repl);
}
namespace
{
/*!
* Helper class for getting the keys for "Additional applications actions"
* ([Desktop Action %s] sections)
*/
class XdgDesktopAction : public XdgDesktopFile
{
public:
XdgDesktopAction(const XdgDesktopFile & parent, const QString & action)
: XdgDesktopFile(parent)
, m_prefix(QString{QLatin1String("Desktop Action %1")}.arg(action))
{}
protected:
virtual QString prefix() const { return m_prefix; }
private:
const QString m_prefix;
};
}
class XdgDesktopFileData: public QSharedData {
public:
XdgDesktopFileData();
inline void clear() {
mFileName.clear();
mIsValid = false;
mValidIsChecked = false;
mIsShow.clear();
mItems.clear();
mType = XdgDesktopFile::UnknownType;
}
bool read(const QString &prefix);
XdgDesktopFile::Type detectType(XdgDesktopFile *q) const;
bool startApplicationDetached(const XdgDesktopFile *q, const QString & action, const QStringList& urls) const;
bool startLinkDetached(const XdgDesktopFile *q) const;
bool startByDBus(const QString & action, const QStringList& urls) const;
QStringList getListValue(const XdgDesktopFile * q, const QString & key, bool tryExtendPrefix) const;
QString mFileName;
bool mIsValid;
mutable bool mValidIsChecked;
mutable QHash<QString, bool> mIsShow;
QMap<QString, QVariant> mItems;
XdgDesktopFile::Type mType;
};
XdgDesktopFileData::XdgDesktopFileData():
mFileName(),
mIsValid(false),
mValidIsChecked(false),
mIsShow(),
mItems(),
mType(XdgDesktopFile::UnknownType)
{
}
bool XdgDesktopFileData::read(const QString &prefix)
{
QFile file(mFileName);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return false;
QString section;
QTextStream stream(&file);
bool prefixExists = false;
while (!stream.atEnd()) {
QString line = stream.readLine().trimmed();
// Skip comments ......................
if (line.startsWith(QLatin1Char('#')))
continue;
// Section ..............................
if (line.startsWith(QLatin1Char('[')) && line.endsWith(QLatin1Char(']')))
{
section = line.mid(1, line.length()-2);
if (section == prefix)
prefixExists = true;
continue;
}
QString key = line.section(QLatin1Char('='), 0, 0).trimmed();
QString value = line.section(QLatin1Char('='), 1).trimmed();
if (key.isEmpty())
continue;
mItems[section + QLatin1Char('/') + key] = QVariant(value);
}
// Not check for empty prefix
mIsValid = (prefix.isEmpty()) || prefixExists;
return mIsValid;
}
XdgDesktopFile::Type XdgDesktopFileData::detectType(XdgDesktopFile *q) const
{
QString typeStr = q->value(typeKey).toString();
if (typeStr == ApplicationStr)
return XdgDesktopFile::ApplicationType;
if (typeStr == LinkStr)
return XdgDesktopFile::LinkType;
if (typeStr == DirectoryStr)
return XdgDesktopFile::DirectoryType;
if (!q->value(execKey).toString().isEmpty())
return XdgDesktopFile::ApplicationType;
return XdgDesktopFile::UnknownType;
}
bool XdgDesktopFileData::startApplicationDetached(const XdgDesktopFile *q, const QString & action, const QStringList& urls) const
{
//DBusActivatable handling
if (q->value(QLatin1String("DBusActivatable"), false).toBool()) {
/* WARNING: We fallback to use Exec when the DBusActivatable fails.
*
* This is a violation of the standard and we know it!
*
* From the Standard:
* DBusActivatable A boolean value specifying if D-Bus activation is
* supported for this application. If this key is missing, the default
* value is false. If the value is true then implementations should
* ignore the Exec key and send a D-Bus message to launch the
* application. See D-Bus Activation for more information on how this
* works. Applications should still include Exec= lines in their desktop
* files for compatibility with implementations that do not understand
* the DBusActivatable key.
*
* So, why are we doing it ? In the benefit of user experience.
* We first ignore the Exec line and in use the D-Bus to lauch the
* application. But if it fails, we try the Exec method.
*
* We consider that this violation is more acceptable than an failure
* in launching an application.
*/
if (startByDBus(action, urls))
return true;
}
QStringList args = action.isEmpty()
? q->expandExecString(urls)
: XdgDesktopAction{*q, action}.expandExecString(urls);
if (args.isEmpty())
return false;
if (q->value(QLatin1String("Terminal")).toBool())
{
QString term = QString::fromLocal8Bit(qgetenv("TERM"));
if (term.isEmpty())
term = QLatin1String("xterm");
args.prepend(QLatin1String("-e"));
args.prepend(term);
}
bool nonDetach = false;
for (const QString &s : nonDetachExecs)
{
for (const QString &a : const_cast<const QStringList&>(args))
{
if (a.contains(s))
{
nonDetach = true;
}
}
}
QString cmd = args.takeFirst();
QString workingDir = q->value(QLatin1String("Path")).toString();
if (!workingDir.isEmpty() && !QDir(workingDir).exists())
workingDir = QString();
if (nonDetach)
{
QScopedPointer<QProcess> p(new QProcess);
p->setStandardInputFile(QProcess::nullDevice());
p->setProcessChannelMode(QProcess::ForwardedChannels);
if (!workingDir.isEmpty())
p->setWorkingDirectory(workingDir);
p->start(cmd, args);
bool started = p->waitForStarted();
if (started)
{
QProcess* proc = p.take(); //release the pointer(will be selfdestroyed upon finish)
QObject::connect(proc, static_cast<void (QProcess::*)(int, QProcess::ExitStatus)>(&QProcess::finished),
proc, &QProcess::deleteLater);
}
return started;
}
else
{
return QProcess::startDetached(cmd, args, workingDir);
}
}
bool XdgDesktopFileData::startLinkDetached(const XdgDesktopFile *q) const
{
QString url = q->url();
if (url.isEmpty())
{
qWarning() << "XdgDesktopFileData::startLinkDetached: url is empty.";
return false;
}
QString scheme = QUrl(url).scheme();
if (scheme.isEmpty() || scheme == QLatin1String("file"))
{
// Local file
QFileInfo fi(url);
QMimeDatabase db;
QMimeType mimeInfo = db.mimeTypeForFile(fi);
XdgDesktopFile* desktopFile = XdgDesktopFileCache::getDefaultApp(mimeInfo.name());
if (desktopFile)
return desktopFile->startDetached(url);
}
else
{
// Internet URL
return QDesktopServices::openUrl(QUrl::fromEncoded(url.toLocal8Bit()));
}
return false;
}
bool XdgDesktopFileData::startByDBus(const QString & action, const QStringList& urls) const
{
QFileInfo f(mFileName);
QString path(f.completeBaseName());
path = path.replace(QLatin1Char('.'), QLatin1Char('/')).prepend(QLatin1Char('/'));
QVariantMap platformData;
platformData.insert(QLatin1String("desktop-startup-id"), QString::fromLocal8Bit(qgetenv("DESKTOP_STARTUP_ID")));
QDBusObjectPath d_path(path);
if (d_path.path().isEmpty())
{
qWarning() << "XdgDesktopFileData::startByDBus: invalid name" << f.fileName() << "of DBusActivatable .desktop file"
", assembled DBus object path" << path << "is invalid!";
return false;
}
org::freedesktop::Application app{f.completeBaseName(), path, QDBusConnection::sessionBus()};
//Note: after the QDBusInterface construction, it can *invalid* (has reasonable lastError())
// but this can be due to some intermediate DBus call(s) which doesn't need to be fatal and
// our next call() can succeed
// see discussion https://github.com/lxqt/libqtxdg/pull/75
if (app.lastError().isValid())
{
qWarning().noquote() << "XdgDesktopFileData::startByDBus: invalid interface:" << app.lastError().message()
<< ", but trying to continue...";
}
app.setTimeout(DBusActivateTimeout::instance());
QDBusPendingReply<> reply;
if (!action.isEmpty())
{
QList<QVariant> v_urls;
for (const auto & url : urls)
v_urls.append(url);
reply = app.ActivateAction(action, v_urls, platformData);
} else if (urls.isEmpty())
reply = app.Activate(platformData);
else
reply = app.Open(urls, platformData);
reply.waitForFinished();
if (QDBusMessage::ErrorMessage == reply.reply().type())
{
qWarning().noquote().nospace() << "XdgDesktopFileData::startByDBus(timeout=" << DBusActivateTimeout::instance()
<< "): failed to start org.freedesktop.Application" << mFileName << ": " << reply.reply();
return false;
}
return true;
}
QStringList XdgDesktopFileData::getListValue(const XdgDesktopFile * q, const QString & key, bool tryExtendPrefix) const
{
QString used_key = key;
if (!q->contains(used_key) && tryExtendPrefix)
{
used_key = extendPrefixKey + key;
if (!q->contains(used_key))
return QStringList();
}
return q->value(used_key).toString().split(QLatin1Char(';'), QString::SkipEmptyParts);
}
XdgDesktopFile::XdgDesktopFile():
d(new XdgDesktopFileData)
{
}
XdgDesktopFile::XdgDesktopFile(const XdgDesktopFile& other):
d(other.d)
{
}
XdgDesktopFile::XdgDesktopFile(Type type, const QString& name, const QString &value):
d(new XdgDesktopFileData)
{
d->mFileName = name + QLatin1String(".desktop");
d->mType = type;
setValue(QLatin1String("Version"), QLatin1String("1.0"));
setValue(nameKey, name);
if (type == XdgDesktopFile::ApplicationType)
{
setValue(typeKey, ApplicationStr);
setValue(execKey, value);
}
else if (type == XdgDesktopFile::LinkType)
{
setValue(typeKey, LinkStr);
setValue(urlKey, value);
}
else if (type == XdgDesktopFile::DirectoryType)
{
setValue(typeKey, DirectoryStr);
}
d->mIsValid = check();
}
XdgDesktopFile::~XdgDesktopFile()
{
}
XdgDesktopFile& XdgDesktopFile::operator=(const XdgDesktopFile& other)
{
d = other.d;
return *this;
}
bool XdgDesktopFile::operator==(const XdgDesktopFile &other) const
{
return d->mItems == other.d->mItems;
}
bool XdgDesktopFile::load(const QString& fileName)
{
d->clear();
if (fileName.startsWith(QDir::separator())) { // absolute path
QFileInfo f(fileName);
if (f.exists())
d->mFileName = f.canonicalFilePath();
else
return false;
} else { // relative path
const QString r = findDesktopFile(fileName);
if (r.isEmpty())
return false;
else
d->mFileName = r;
}
d->read(prefix());
d->mIsValid = d->mIsValid && check();
d->mType = d->detectType(this);
return isValid();
}
bool XdgDesktopFile::save(QIODevice *device) const
{
QTextStream stream(device);
QMap<QString, QVariant>::const_iterator i = d->mItems.constBegin();
QString section;
while (i != d->mItems.constEnd())
{
QString path = i.key();
QString sect = path.section(QLatin1Char('/'),0,0);
if (sect != section)
{
section = sect;
stream << QLatin1Char('[') << section << QLatin1Char(']') << endl;
}
QString key = path.section(QLatin1Char('/'), 1);
stream << key << QLatin1Char('=') << i.value().toString() << endl;
++i;
}
return true;
}
bool XdgDesktopFile::save(const QString &fileName) const
{
QFile file(fileName);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
return false;
return save(&file);
}
QVariant XdgDesktopFile::value(const QString& key, const QVariant& defaultValue) const
{
QString path = (!prefix().isEmpty()) ? prefix() + QLatin1Char('/') + key : key;
QVariant res = d->mItems.value(path, defaultValue);
if (res.type() == QVariant::String)
{
QString s = res.toString();
return unEscape(s);
}
return res;
}
void XdgDesktopFile::setValue(const QString &key, const QVariant &value)
{
QString path = (!prefix().isEmpty()) ? prefix() + QLatin1Char('/') + key : key;
if (value.type() == QVariant::String)
{
QString s=value.toString();
if (key.toUpper() == QLatin1String("EXEC"))
escapeExec(s);
else
escape(s);
d->mItems[path] = QVariant(s);
if (key.toUpper() == QLatin1String("TYPE"))
d->mType = d->detectType(this);
}
else
{
d->mItems[path] = value;
}
}
void XdgDesktopFile::setLocalizedValue(const QString &key, const QVariant &value)
{
setValue(localizedKey(key), value);
}
/************************************************
LC_MESSAGES value Possible keys in order of matching
lang_COUNTRY@MODIFIER lang_COUNTRY@MODIFIER, lang_COUNTRY, lang@MODIFIER, lang,
default value
lang_COUNTRY lang_COUNTRY, lang, default value
lang@MODIFIER lang@MODIFIER, lang, default value
lang lang, default value
************************************************/
QString XdgDesktopFile::localizedKey(const QString& key) const
{
QString lang = QString::fromLocal8Bit(qgetenv("LC_MESSAGES"));
if (lang.isEmpty())
lang = QString::fromLocal8Bit(qgetenv("LC_ALL"));
if (lang.isEmpty())
lang = QString::fromLocal8Bit(qgetenv("LANG"));
QString modifier = lang.section(QLatin1Char('@'), 1);
if (!modifier.isEmpty())
lang.truncate(lang.length() - modifier.length() - 1);
QString encoding = lang.section(QLatin1Char('.'), 1);
if (!encoding.isEmpty())
lang.truncate(lang.length() - encoding.length() - 1);
QString country = lang.section(QLatin1Char('_'), 1);
if (!country.isEmpty())
lang.truncate(lang.length() - country.length() - 1);
//qDebug() << "LC_MESSAGES: " << qgetenv("LC_MESSAGES");
//qDebug() << "Lang:" << lang;
//qDebug() << "Country:" << country;
//qDebug() << "Encoding:" << encoding;
//qDebug() << "Modifier:" << modifier;
if (!modifier.isEmpty() && !country.isEmpty())
{
QString k = QString::fromLatin1("%1[%2_%3@%4]").arg(key, lang, country, modifier);
//qDebug() << "\t try " << k << contains(k);
if (contains(k))
return k;
}
if (!country.isEmpty())
{
QString k = QString::fromLatin1("%1[%2_%3]").arg(key, lang, country);
//qDebug() << "\t try " << k << contains(k);
if (contains(k))
return k;
}
if (!modifier.isEmpty())
{
QString k = QString::fromLatin1("%1[%2@%3]").arg(key, lang, modifier);
//qDebug() << "\t try " << k << contains(k);
if (contains(k))
return k;
}
QString k = QString::fromLatin1("%1[%2]").arg(key, lang);
//qDebug() << "\t try " << k << contains(k);
if (contains(k))
return k;
//qDebug() << "\t try " << key << contains(key);
return key;
}
QVariant XdgDesktopFile::localizedValue(const QString& key, const QVariant& defaultValue) const
{
return value(localizedKey(key), defaultValue);
}
QStringList XdgDesktopFile::categories() const
{
return d->getListValue(this, categoriesKey, true);
}
QStringList XdgDesktopFile::actions() const
{
return d->getListValue(this, actionsKey, false);
}
void XdgDesktopFile::removeEntry(const QString& key)
{
QString path = (!prefix().isEmpty()) ? prefix() + QLatin1Char('/') + key : key;
d->mItems.remove(path);
}
bool XdgDesktopFile::contains(const QString& key) const
{
QString path = (!prefix().isEmpty()) ? prefix() + QLatin1Char('/') + key : key;
return d->mItems.contains(path);
}
bool XdgDesktopFile::isValid() const
{
return d->mIsValid;
}
QString XdgDesktopFile::fileName() const
{
return d->mFileName;
}
QIcon const XdgDesktopFile::icon(const QIcon& fallback) const
{
QIcon result = XdgIcon::fromTheme(value(iconKey).toString(), fallback);
if (result.isNull() && type() == ApplicationType) {
result = XdgIcon::fromTheme(QLatin1String("application-x-executable.png"));
// TODO Maybe defaults for other desktopfile types as well..
}
return result;
}
QIcon const XdgDesktopFile::actionIcon(const QString & action, const QIcon& fallback) const
{
return d->mType == ApplicationType
? XdgDesktopAction{*this, action}.icon(icon(fallback))
: fallback;
}
QString const XdgDesktopFile::iconName() const
{
return value(iconKey).toString();
}
QString const XdgDesktopFile::actionIconName(const QString & action) const
{
return d->mType == ApplicationType
? XdgDesktopAction{*this, action}.iconName()
: QString{};
}
QStringList XdgDesktopFile::mimeTypes() const
{
return value(mimeTypeKey).toString().split(QLatin1Char(';'), QString::SkipEmptyParts);
}
QString XdgDesktopFile::actionName(const QString & action) const
{
return d->mType == ApplicationType
? XdgDesktopAction{*this, action}.name()
: QString{};
}
XdgDesktopFile::Type XdgDesktopFile::type() const
{
return d->mType;
}
/************************************************
Starts the program defined in this desktop file in a new process, and detaches
from it. Returns true on success; otherwise returns false. If the calling process
exits, the detached process will continue to live.
Urls - the list of URLs or files to open, can be empty (app launched without
argument)
If the function is successful then *pid is set to the process identifier of the
started process.
************************************************/
bool XdgDesktopFile::startDetached(const QStringList& urls) const
{
switch(d->mType)
{
case ApplicationType:
return d->startApplicationDetached(this, QString{}, urls);
break;
case LinkType:
return d->startLinkDetached(this);
break;
default:
return false;
}
}
bool XdgDesktopFile::actionActivate(const QString & action, const QStringList& urls) const
{
return d->mType == ApplicationType ? d->startApplicationDetached(this, action, urls) : false;
}
/************************************************
This is an overloaded function.
************************************************/
bool XdgDesktopFile::startDetached(const QString& url) const
{
if (url.isEmpty())
return startDetached(QStringList());
else
return startDetached(QStringList(url));
}
static QStringList parseCombinedArgString(const QString &program)
{
QStringList args;
QString tmp;
int quoteCount = 0;
bool inQuote = false;
// handle quoting. tokens can be surrounded by double quotes
// "hello world". three consecutive double quotes represent
// the quote character itself.
for (int i = 0; i < program.size(); ++i) {
if (program.at(i) == QLatin1Char('"')) {
++quoteCount;
if (quoteCount == 3) {
// third consecutive quote
quoteCount = 0;
tmp += program.at(i);
}
continue;
}
if (quoteCount) {
if (quoteCount == 1)
inQuote = !inQuote;
quoteCount = 0;
}
if (!inQuote && program.at(i).isSpace()) {
if (!tmp.isEmpty()) {
args += tmp;
tmp.clear();
}
} else {
tmp += program.at(i);
}
}
if (!tmp.isEmpty())
args += tmp;
return args;
}
void replaceVar(QString &str, const QString &varName, const QString &after)
{
str.replace(QRegExp(QString::fromLatin1("\\$%1(?!\\w)").arg(varName)), after);
str.replace(QRegExp(QString::fromLatin1("\\$\\{%1\\}").arg(varName)), after);
}
QString expandEnvVariables(const QString str)
{
QString scheme = QUrl(str).scheme();
if (scheme == QLatin1String("http") || scheme == QLatin1String("https") || scheme == QLatin1String("shttp") ||
scheme == QLatin1String("ftp") || scheme == QLatin1String("ftps") ||
scheme == QLatin1String("pop") || scheme == QLatin1String("pops") ||
scheme == QLatin1String("imap") || scheme == QLatin1String("imaps") ||
scheme == QLatin1String("mailto") ||
scheme == QLatin1String("nntp") ||
scheme == QLatin1String("irc") ||
scheme == QLatin1String("telnet") ||
scheme == QLatin1String("xmpp") ||
scheme == QLatin1String("nfs")
)
return str;
const QString homeDir = QFile::decodeName(qgetenv("HOME"));
QString res = str;
res.replace(QRegExp(QString::fromLatin1("~(?=$|/)")), homeDir);
replaceVar(res, QLatin1String("HOME"), homeDir);
replaceVar(res, QLatin1String("USER"), QString::fromLocal8Bit(qgetenv("USER")));
replaceVar(res, QLatin1String("XDG_DESKTOP_DIR"), XdgDirs::userDir(XdgDirs::Desktop));
replaceVar(res, QLatin1String("XDG_TEMPLATES_DIR"), XdgDirs::userDir(XdgDirs::Templates));
replaceVar(res, QLatin1String("XDG_DOCUMENTS_DIR"), XdgDirs::userDir(XdgDirs::Documents));
replaceVar(res, QLatin1String("XDG_MUSIC_DIR"), XdgDirs::userDir(XdgDirs::Music));
replaceVar(res, QLatin1String("XDG_PICTURES_DIR"), XdgDirs::userDir(XdgDirs::Pictures));
replaceVar(res, QLatin1String("XDG_VIDEOS_DIR"), XdgDirs::userDir(XdgDirs::Videos));
replaceVar(res, QLatin1String("XDG_PHOTOS_DIR"), XdgDirs::userDir(XdgDirs::Pictures));
return res;
}
QStringList expandEnvVariables(const QStringList strs)
{
QStringList res;
for (const QString &s : strs)
res << expandEnvVariables(s);
return res;
}
QStringList XdgDesktopFile::expandExecString(const QStringList& urls) const
{
if (d->mType != ApplicationType)
return QStringList();
QStringList result;
QString execStr = value(execKey).toString();
unEscapeExec(execStr);
const QStringList tokens = parseCombinedArgString(execStr);
for (QString token : tokens)
{
// The parseCombinedArgString() splits the string by the space symbols,
// we temporarily replaced them on the special characters.
// Now we reverse it.
token.replace(01, QLatin1Char(' '));
token.replace(02, QLatin1Char('\t'));
token.replace(03, QLatin1Char('\n'));
// ----------------------------------------------------------
// A single file name, even if multiple files are selected.
if (token == QLatin1String("%f"))
{
if (!urls.isEmpty())
result << expandEnvVariables(urls.at(0));
continue;
}
// ----------------------------------------------------------
// A list of files. Use for apps that can open several local files at once.
// Each file is passed as a separate argument to the executable program.
if (token == QLatin1String("%F"))
{
result << expandEnvVariables(urls);
continue;
}
// ----------------------------------------------------------
// A single URL. Local files may either be passed as file: URLs or as file path.
if (token == QLatin1String("%u"))
{
if (!urls.isEmpty())
{
QUrl url;
url.setUrl(expandEnvVariables(urls.at(0)));
result << ((!url.toLocalFile().isEmpty()) ? url.toLocalFile() : QString::fromUtf8(url.toEncoded()));
}
continue;
}
// ----------------------------------------------------------
// A list of URLs. Each URL is passed as a separate argument to the executable
// program. Local files may either be passed as file: URLs or as file path.
if (token == QLatin1String("%U"))
{
for (const QString &s : urls)
{
QUrl url(expandEnvVariables(s));
result << ((!url.toLocalFile().isEmpty()) ? url.toLocalFile() : QString::fromUtf8(url.toEncoded()));
}
continue;
}
// ----------------------------------------------------------
// The Icon key of the desktop entry expanded as two arguments, first --icon
// and then the value of the Icon key. Should not expand to any arguments if
// the Icon key is empty or missing.
if (token == QLatin1String("%i"))
{
QString icon = value(iconKey).toString();
if (!icon.isEmpty())
result << QLatin1String("-icon") << icon.replace(QLatin1Char('%'), QLatin1String("%%"));
continue;
}
// ----------------------------------------------------------
// The translated name of the application as listed in the appropriate Name key
// in the desktop entry.
if (token == QLatin1String("%c"))
{
result << localizedValue(nameKey).toString().replace(QLatin1Char('%'), QLatin1String("%%"));
continue;
}
// ----------------------------------------------------------
// The location of the desktop file as either a URI (if for example gotten from
// the vfolder system) or a local filename or empty if no location is known.
if (token == QLatin1String("%k"))
{
result << fileName().replace(QLatin1Char('%'), QLatin1String("%%"));
break;
}
// ----------------------------------------------------------
// Deprecated.
// Deprecated field codes should be removed from the command line and ignored.
if (token == QLatin1String("%d") || token == QLatin1String("%D") ||
token == QLatin1String("%n") || token == QLatin1String("%N") ||
token == QLatin1String("%v") || token == QLatin1String("%m")
)
{
continue;
}
// ----------------------------------------------------------
result << expandEnvVariables(token);
}
return result;
}
bool checkTryExec(const QString& progName)
{
if (progName.startsWith(QDir::separator()))
return QFileInfo(progName).isExecutable();
const QStringList dirs = QFile::decodeName(qgetenv("PATH")).split(QLatin1Char(':'));
for (const QString &dir : dirs)
{
if (QFileInfo(QDir(dir), progName).isExecutable())
return true;
}
return false;
}
QString XdgDesktopFile::id(const QString &fileName, bool checkFileExists)
{
const QFileInfo f(fileName);
if (checkFileExists) {
if (!f.exists()) {
return QString();
}
}
QString id = f.absoluteFilePath();
const QStringList dataDirs = XdgDirs::dataDirs();
for (const QString &d : dataDirs) {
if (id.startsWith(d)) {
// remove only the first occurence
id.replace(id.indexOf(d), d.size(), QString());
}
}
const QLatin1Char slash('/');
const QString s = slash + applicationsStr + slash;
if (!id.startsWith(s))
return QString();
id.replace(id.indexOf(s), s.size(), QString());
id.replace(slash, QLatin1Char('-'));
return id;
}
bool XdgDesktopFile::isShown(const QString &environment) const
{
const QString env = environment.toUpper();
if (d->mIsShow.contains(env))
return d->mIsShow.value(env);
d->mIsShow.insert(env, false);
// Means "this application exists, but don't display it in the menus".
if (value(QLatin1String("NoDisplay")).toBool())
return false;
// The file is not suitable to the current environment
if (!isSuitable(true, env))
return false;
d->mIsShow.insert(env, true);
return true;
}
bool XdgDesktopFile::isSuitable(bool excludeHidden, const QString &environment) const
{
// Hidden should have been called Deleted. It means the user deleted
// (at his level) something that was present
if (excludeHidden && value(QLatin1String("Hidden")).toBool())
return false;
// A list of strings identifying the environments that should display/not
// display a given desktop entry.
// OnlyShowIn ........
QString env;
if (environment.isEmpty())
env = QString::fromLocal8Bit(detectDesktopEnvironment());
else {
env = environment.toUpper();
}
QString key;
bool keyFound = false;
if (contains(onlyShowInKey))
{
key = onlyShowInKey;
keyFound = true;
}
else
{
key = extendPrefixKey + onlyShowInKey;
keyFound = contains(key) ? true : false;
}
if (keyFound)
{
QStringList s = value(key).toString().toUpper().split(QLatin1Char(';'));
if (!s.contains(env))
return false;
}
// NotShowIn .........
if (contains(notShowInKey))
{
key = notShowInKey;
keyFound = true;
}
else
{
key = extendPrefixKey + notShowInKey;
keyFound = contains(key) ? true : false;
}
if (keyFound)
{
QStringList s = value(key).toString().toUpper().split(QLatin1Char(';'));
if (s.contains(env))
return false;
}
// actually installed. If not, entry may not show in menus, etc.
QString s = value(QLatin1String("TryExec")).toString();
if (!s.isEmpty() && ! checkTryExec(s))
return false;
return true;
}
QString expandDynamicUrl(QString url)
{
const QStringList env = QProcess::systemEnvironment();
for (const QString &line : env)
{
QString name = line.section(QLatin1Char('='), 0, 0);
QString val = line.section(QLatin1Char('='), 1);
url.replace(QString::fromLatin1("$%1").arg(name), val);
url.replace(QString::fromLatin1("${%1}").arg(name), val);
}
return url;
}
QString XdgDesktopFile::url() const
{
if (type() != LinkType)
return QString();
QString url;
url = value(urlKey).toString();
if (!url.isEmpty())
return url;
// WTF? What standard describes it?
url = expandDynamicUrl(value(QLatin1String("URL[$e]")).toString());
if (!url.isEmpty())
return url;
return QString();
}
QString findDesktopFile(const QString& dirName, const QString& desktopName)
{
QDir dir(dirName);
QFileInfo fi(dir, desktopName);
if (fi.exists())
return fi.canonicalFilePath();
// Working recursively ............
const QFileInfoList dirs = dir.entryInfoList(QStringList(), QDir::Dirs | QDir::NoDotAndDotDot);
for (const QFileInfo &d : dirs)
{
QString cn = d.canonicalFilePath();
if (dirName != cn)
{
QString f = findDesktopFile(cn, desktopName);
if (!f.isEmpty())
return f;
}
}
return QString();
}
QString findDesktopFile(const QString& desktopName)
{
QStringList dataDirs = XdgDirs::dataDirs();
dataDirs.prepend(XdgDirs::dataHome(false));
for (const QString &dirName : const_cast<const QStringList&>(dataDirs))
{
QString f = findDesktopFile(dirName + QLatin1String("/applications"), desktopName);
if (!f.isEmpty())
return f;
}
return QString();
}
XdgDesktopFile* XdgDesktopFileCache::getFile(const QString& fileName)
{
if (fileName.isEmpty())
return nullptr;
if (instance().m_fileCache.contains(fileName))
{
return instance().m_fileCache.value(fileName);
}
QString file;
if (!fileName.startsWith(QDir::separator()))
{
// Relative path
// Search desktop file ..................
file = findDesktopFile(fileName);
if (file.isEmpty())
return nullptr;
}
else
{
file = fileName;
}
XdgDesktopFile* desktopFile;
// The file was found
if (!instance().m_fileCache.contains(file))
{
desktopFile = load(file);
if (desktopFile)
{
instance().m_fileCache.insert(file, desktopFile);
return desktopFile;
}
else
{
return nullptr;
}
}
else
{
// already in the cache
desktopFile = instance().m_fileCache.value(file);
return desktopFile;
}
}
QList<XdgDesktopFile*> XdgDesktopFileCache::getAllFiles()
{
return instance().m_fileCache.values();
}
XdgDesktopFileCache & XdgDesktopFileCache::instance()
{
static XdgDesktopFileCache cache;
if (!cache.m_IsInitialized)
{
cache.initialize();
cache.m_IsInitialized = true;
}
return cache;
}
/*!
* Handles files with a syntax similar to desktopfiles as QSettings files.
* The differences between ini-files and desktopfiles are:
* desktopfiles uses '#' as comment marker, and ';' as list-separator.
* Every key/value must be inside a section (i.e. there is no 'General' pseudo-section)
*/
bool readDesktopFile(QIODevice & device, QSettings::SettingsMap & map)
{
QString section;
QTextStream stream(&device);
while (!stream.atEnd()) {
QString line = stream.readLine().trimmed();
// Skip comments and empty lines
if (line.startsWith(QLatin1Char('#')) || line.isEmpty())
continue;
// Section ..............................
if (line.startsWith(QLatin1Char('[')) && line.endsWith(QLatin1Char(']')))
{
section = line.mid(1, line.length()-2);
continue;
}
QString key = line.section(QLatin1Char('='), 0, 0).trimmed();
QString value = line.section(QLatin1Char('='), 1).trimmed();
if (key.isEmpty())
continue;
if (section.isEmpty())
{
qWarning() << "key=value outside section";
return false;
}
key.prepend(QLatin1Char('/'));
key.prepend(section);
if (value.contains(QLatin1Char(';')))
{
map.insert(key, value.split(QLatin1Char(';'), QString::SkipEmptyParts));
}
else
{
map.insert(key, value);
}
}
return true;
}
/*! See readDesktopFile
*/
bool writeDesktopFile(QIODevice & device, const QSettings::SettingsMap & map)
{
QTextStream stream(&device);
QString section;
for (auto it = map.constBegin(); it != map.constEnd(); ++it)
{
bool isString = it.value().canConvert<QString>();
bool isStringList = (it.value().type() == QVariant::StringList);
if ((! isString) && (! isStringList))
{
return false;
}
QString thisSection = it.key().section(QLatin1Char('/'), 0, 0);
if (thisSection.isEmpty())
{
qWarning() << "No section defined";
return false;
}
if (thisSection != section)
{
stream << QLatin1Char('[') << thisSection << QLatin1Char(']') << QLatin1Char('\n');
section = thisSection;
}
QString remainingKey = it.key().section(QLatin1Char('/'), 1, -1);
if (remainingKey.isEmpty())
{
qWarning() << "Only one level in key..." ;
return false;
}
stream << remainingKey << QLatin1Char('=');
if (isString)
{
stream << it.value().toString() << QLatin1Char(';');
}
else /* if (isStringList) */
{
const auto values = it.value().toStringList();
for (const QString &value : values)
{
stream << value << QLatin1Char(';');
}
}
stream << QLatin1Char('\n');
}
return true;
}
void XdgDesktopFileCache::initialize(const QString& dirName)
{
QDir dir(dirName);
// Directories have the type "application/x-directory", but in the desktop file
// are shown as "inode/directory". To handle these cases, we use this hash.
QHash<QString, QString> specials;
specials.insert(QLatin1String("inode/directory"), QLatin1String("application/x-directory"));
// Working recursively ............
const QFileInfoList files = dir.entryInfoList(QStringList(), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
for (const QFileInfo &f : files)
{
if (f.isDir())
{
initialize(f.absoluteFilePath());
continue;
}
XdgDesktopFile* df = load(f.absoluteFilePath());
if (!df)
continue;
if (! m_fileCache.contains(f.absoluteFilePath()))
{
m_fileCache.insert(f.absoluteFilePath(), df);
}
const QStringList mimes = df->value(mimeTypeKey).toString().split(QLatin1Char(';'), QString::SkipEmptyParts);
for (const QString &mime : mimes)
{
int pref = df->value(initialPreferenceKey, 0).toInt();
// We move the desktopFile forward in the list for this mime, so that
// no desktopfile in front of it have a lower initialPreference.
int position = m_defaultAppsCache[mime].length();
while (position > 0 && m_defaultAppsCache[mime][position - 1]->value(initialPreferenceKey, 0).toInt() < pref)
{
position--;
}
m_defaultAppsCache[mime].insert(position, df);
}
}
}
XdgDesktopFile* XdgDesktopFileCache::load(const QString& fileName)
{
XdgDesktopFile* desktopFile = new XdgDesktopFile();
Q_CHECK_PTR(desktopFile);
if (desktopFile && desktopFile->load(fileName))
return desktopFile;
delete desktopFile;
return nullptr;
}
void loadMimeCacheDir(const QString& dirName, QHash<QString, QList<XdgDesktopFile*> > & cache)
{
QDir dir(dirName);
// Directories have the type "application/x-directory", but in the desktop file
// are shown as "inode/directory". To handle these cases, we use this hash.
QHash<QString, QString> specials;
specials.insert(QLatin1String("inode/directory"), QLatin1String("application/x-directory"));
// Working recursively ............
const QFileInfoList files = dir.entryInfoList(QStringList(), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot);
for (const QFileInfo &f : files)
{
if (f.isDir())
{
loadMimeCacheDir(f.absoluteFilePath(), cache);
continue;
}
XdgDesktopFile* df = XdgDesktopFileCache::getFile(f.absoluteFilePath());
if (!df)
continue;
const QStringList mimes = df->value(mimeTypeKey).toString().split(QLatin1Char(';'), QString::SkipEmptyParts);
for (const QString &mime : mimes)
{
int pref = df->value(initialPreferenceKey, 0).toInt();
// We move the desktopFile forward in the list for this mime, so that
// no desktopfile in front of it have a lower initialPreference.
int position = cache[mime].length();
while (position > 0 && cache[mime][position - 1]->value(initialPreferenceKey, 0).toInt() < pref)
{
position--;
}
cache[mime].insert(position, df);
}
}
}
QSettings::Format XdgDesktopFileCache::desktopFileSettingsFormat()
{
static QSettings::Format format = QSettings::InvalidFormat;
if (format == QSettings::InvalidFormat)
format = QSettings::registerFormat(QLatin1String("*.list"), readDesktopFile, writeDesktopFile);
return format;
}
XdgDesktopFileCache::XdgDesktopFileCache() :
m_IsInitialized(false),
m_defaultAppsCache(),
m_fileCache()
{
}
XdgDesktopFileCache::~XdgDesktopFileCache()
{
}
void XdgDesktopFileCache::initialize()
{
QStringList dataDirs = XdgDirs::dataDirs();
dataDirs.prepend(XdgDirs::dataHome(false));
for (const QString &dirname : const_cast<const QStringList&>(dataDirs))
{
initialize(dirname + QLatin1String("/applications"));
// loadMimeCacheDir(dirname + "/applications", m_defaultAppsCache);
}
}
QList<XdgDesktopFile*> XdgDesktopFileCache::getAppsOfCategory(const QString& category)
{
QList<XdgDesktopFile*> list;
const QString _category = category.toUpper();
const QHash<QString, XdgDesktopFile*> fileCache = instance().m_fileCache;
for (XdgDesktopFile *desktopFile : fileCache)
{
QStringList categories = desktopFile->value(categoriesKey).toString().toUpper().split(QLatin1Char(';'));
if (!categories.isEmpty() && (categories.contains(_category) || categories.contains(QLatin1String("X-") + _category)))
list.append(desktopFile);
}
return list;
}
QList<XdgDesktopFile*> XdgDesktopFileCache::getApps(const QString& mimetype)
{
return instance().m_defaultAppsCache.value(mimetype);
}
XdgDesktopFile* XdgDesktopFileCache::getDefaultApp(const QString& mimetype)
{
// First, we look in following places for a default in specified order:
// ~/.config/mimeapps.list
// /etc/xdg/mimeapps.list
// ~/.local/share/applications/mimeapps.list
// /usr/local/share/applications/mimeapps.list
// /usr/share/applications/mimeapps.list
QStringList mimeDirsList;
mimeDirsList.append(XdgDirs::configHome(false));
mimeDirsList.append(XdgDirs::configDirs());
mimeDirsList.append(XdgDirs::dataHome(false) + QLatin1String("/applications"));
mimeDirsList.append(XdgDirs::dataDirs(QLatin1String("/applications")));
for (const QString &mimeDir : const_cast<const QStringList&>(mimeDirsList))
{
QString defaultsListPath = mimeDir + QLatin1String("/mimeapps.list");
if (QFileInfo::exists(defaultsListPath))
{
QSettings defaults(defaultsListPath, desktopFileSettingsFormat());
defaults.beginGroup(QLatin1String("Default Applications"));
if (defaults.contains(mimetype))
{
QVariant value = defaults.value(mimetype);
if (value.canConvert<QStringList>()) // A single string can also convert to a stringlist
{
const QStringList values = value.toStringList();
for (const QString &desktopFileName : values)
{
XdgDesktopFile* desktopFile = XdgDesktopFileCache::getFile(desktopFileName);
if (desktopFile)
{
return desktopFile;
}
else
{
qWarning() << desktopFileName << "not a valid desktopfile";
}
}
}
}
defaults.endGroup();
}
}
// If we havent found anything up to here, we look for a desktopfile that declares
// the ability to handle the given mimetype. See getApps.
QList<XdgDesktopFile*> apps = getApps(mimetype);
XdgDesktopFile* desktopFile = apps.isEmpty() ? 0 : apps[0];
return desktopFile;
}
|