-
Notifications
You must be signed in to change notification settings - Fork 9
/
widget.cpp
435 lines (366 loc) · 13.6 KB
/
widget.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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
#include "widget.h"
#include <QFile>
#include <QDebug>
#include <QDir>
#include <QTreeWidget>
#include <QListWidget>
#include <QHBoxLayout>
#include <QGridLayout>
#include <QStandardPaths>
#include <QPushButton>
#include <QMessageBox>
#include <QDirIterator>
#include <QGuiApplication>
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
for (const QString &dirPath : QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation)) {
qDebug() << "Loading applications from" << dirPath;
QDir applicationsDir(dirPath);
for (const QFileInfo &file : applicationsDir.entryInfoList(QStringList("*.desktop"))) {
loadDesktopFile(file);
}
}
// Check that we shit with multiple .desktop files, but some nodisplay files
for (const QString &appId : m_supportedMimetypes.keys()) {
if (!m_desktopFileNames.contains(appId)) {
qWarning() << appId << "does not have an associated desktop file!";
continue;
}
if (m_applicationNames[appId].isEmpty()) {
qWarning() << "Missing name" << appId;
m_applicationNames[appId] = appId;
}
}
// Preload up front, so it doesn't get sluggish when selecting applications supporting a lot
const QIcon unknownIcon = QIcon::fromTheme("unknown");
// TODO: check if QT_QPA_PLATFORMTHEME is set to plasma or sandsmark,
// if so just use the functioning QIcon::fromTheme()
// We do this manually because non-Plasma-platforms icon loading is extremely slow (I blame GTK and its crappy icon cache)
for (const QString &searchPath : (QIcon::themeSearchPaths() + QIcon::fallbackSearchPaths())) {
loadIcons(searchPath + QIcon::themeName());
loadIcons(searchPath);
}
for (const QString &mimetypeName : m_supportedMimetypes.values()) {
if (m_mimeTypeIcons.contains(mimetypeName)) {
continue;
}
const QMimeType mimetype = m_mimeDb.mimeTypeForName(mimetypeName);
QString iconName = mimetype.iconName();
QIcon icon(m_iconPaths.value(iconName));
if (!icon.isNull()) {
m_mimeTypeIcons[mimetypeName] = icon;
continue;
}
icon = QIcon(m_iconPaths.value(mimetype.genericIconName()));
if (!icon.isNull()) {
m_mimeTypeIcons[mimetypeName] = icon;
continue;
}
int split = iconName.lastIndexOf('+');
if (split != -1) {
iconName.truncate(split);
icon = QIcon(m_iconPaths.value(iconName));
if (!icon.isNull()) {
m_mimeTypeIcons[mimetypeName] = icon;
continue;
}
}
split = iconName.lastIndexOf('-');
if (split != -1) {
iconName.truncate(split);
icon = QIcon(m_iconPaths.value(iconName));
if (!icon.isNull()) {
m_mimeTypeIcons[mimetypeName] = icon;
continue;
}
}
icon = QIcon(m_iconPaths.value(mimetype.genericIconName()));
if (!icon.isNull()) {
m_mimeTypeIcons[mimetypeName] = icon;
continue;
}
m_mimeTypeIcons[mimetypeName] = unknownIcon;
}
QHBoxLayout *mainLayout = new QHBoxLayout;
setLayout(mainLayout);
m_applicationList = new QTreeWidget;
mainLayout->addWidget(m_applicationList);
QGridLayout *rightLayout = new QGridLayout;
mainLayout->addLayout(rightLayout);
m_setDefaultButton = new QPushButton(tr("Set as default application for these file types"));
m_setDefaultButton->setEnabled(false);
m_mimetypeList = new QListWidget;
m_mimetypeList->setSelectionMode(QAbstractItemView::MultiSelection);
rightLayout->addWidget(m_mimetypeList);
rightLayout->addWidget(m_setDefaultButton);
QStringList types = m_applications.keys();
std::sort(types.begin(), types.end());
for (const QString &type : types) {
QTreeWidgetItem *typeItem = new QTreeWidgetItem(QStringList(type));
QStringList applications = m_applications[type].values();
std::sort(applications.begin(), applications.end(), [=](const QString &a, const QString &b) {
return m_applicationNames[a] < m_applicationNames[b];
});
for (const QString &application : applications) {
QTreeWidgetItem *appItem = new QTreeWidgetItem(QStringList(m_applicationNames[application]));
appItem->setData(0, Qt::UserRole, application);
appItem->setIcon(0, QIcon::fromTheme(m_applicationIcons[application]));
typeItem->addChild(appItem);
}
m_applicationList->addTopLevelItem(typeItem);
}
m_applicationList->setHeaderHidden(true);
connect(m_applicationList, &QTreeWidget::itemSelectionChanged, this, &Widget::onMimetypeSelected);
connect(m_setDefaultButton, &QPushButton::clicked, this, &Widget::onSetDefaultClicked);
}
Widget::~Widget()
{
}
void Widget::onMimetypeSelected()
{
m_setDefaultButton->setEnabled(false);
m_mimetypeList->clear();
QList<QTreeWidgetItem*> selectedItems = m_applicationList->selectedItems();
if (selectedItems.count() != 1) {
return;
}
const QTreeWidgetItem *item = selectedItems.first();
if (!item->parent()) {
return;
}
const QString mimetypeGroup = item->parent()->text(0);
const QString application = item->data(0, Qt::UserRole).toString();
QStringList supported = m_supportedMimetypes.values(application);
// E. g. kwrite and kate only indicate support for "text/plain", but
// they're nice for things like c source files.
QSet<QString> secondary;
const QStringList currentSupported = m_supportedMimetypes.values(application);
for (const QString &mimetype : currentSupported) {
for (const QString &child : m_childMimeTypes.values(mimetype)) {
supported.append(child);
secondary.insert(child);
}
}
supported.removeDuplicates();
for (const QString &supportedMime : supported) {
if (!supportedMime.startsWith(mimetypeGroup)) {
continue;
}
const QMimeType mimetype = m_mimeDb.mimeTypeForName(supportedMime);
const QString mimeName = mimetype.name();
QString name = mimetype.filterString().trimmed();
if (name.isEmpty()) {
name = mimetype.comment().trimmed();
}
if (name.isEmpty()) {
name = mimeName;
} else {
name += '\n' + mimeName;
}
QListWidgetItem *item = new QListWidgetItem(name);
item->setData(Qt::UserRole, mimeName);
item->setIcon(m_mimeTypeIcons[supportedMime]);
m_mimetypeList->addItem(item);
item->setSelected(!secondary.contains(mimeName));
}
m_setDefaultButton->setEnabled(m_mimetypeList->count() > 0);
}
void Widget::onSetDefaultClicked()
{
QList<QTreeWidgetItem*> selectedItems = m_applicationList->selectedItems();
if (selectedItems.count() != 1) {
return;
}
const QTreeWidgetItem *item = selectedItems.first();
if (!item->parent()) {
return;
}
const QString application = item->data(0, Qt::UserRole).toString();
if (application.isEmpty()) {
return;
}
QSet<QString> unselected;
QSet<QString> selected;
for (int i=0; i<m_mimetypeList->count(); i++) {
QListWidgetItem *item = m_mimetypeList->item(i);
const QString name = item->data(Qt::UserRole).toString();
if (item->isSelected()) {
selected.insert(name);
} else {
unselected.insert(name);
}
}
setDefault(application, selected, unselected);
}
void Widget::loadDesktopFile(const QFileInfo &fileInfo)
{
// Ugliest implementation of .desktop file reading ever
QFile file(fileInfo.absoluteFilePath());
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << "Failed to open" << fileInfo.fileName();
return;
}
QStringList mimetypes;
QString appName;
QString appId = fileInfo.fileName();
QString iconName;
bool inCorrectGroup = false;
bool noDisplay = false;
while (!file.atEnd()) {
QString line = file.readLine().simplified();
if (line.startsWith('[')) {
inCorrectGroup = (line == "[Desktop Entry]");
continue;
}
if (!inCorrectGroup) {
continue;
}
if (line.startsWith("MimeType")) {
line.remove(0, line.indexOf('=') + 1);
mimetypes = line.split(';', Qt::SkipEmptyParts);
continue;
}
if (line.startsWith("Name") && !line.contains('[')) {
line.remove(0, line.indexOf('=') + 1);
appName = line;
continue;
}
if (line.startsWith("Icon")) {
line.remove(0, line.indexOf('=') + 1);
iconName = line;
continue;
}
if (line.startsWith("Exec")) {
line.remove(0, line.indexOf('=') + 1);
if (line.isEmpty()) {
continue;
}
QStringList parts = line.split(' ');
if (parts.first() == "env" && parts.count() > 2) {
line = parts[2];
}
appId = line;
continue;
}
if (line.startsWith("NoDisplay=") && line.contains("true", Qt::CaseInsensitive)) {
noDisplay = true;
}
}
if (!iconName.isEmpty() && m_applicationIcons[appId].isEmpty()) {
m_applicationIcons[appId] = iconName;
}
// If an application has a .desktop file without NoDisplay use that, otherwise use one of the ones with NoDisplay anyways
if (!noDisplay || !m_desktopFileNames.contains(appId)) {
m_desktopFileNames[appId] = fileInfo.fileName();
}
if (!appName.isEmpty() && m_applicationNames[appId].isEmpty()) {
m_applicationNames[appId] = appName;
}
if (mimetypes.isEmpty()) {
return;
}
const QMimeType octetStream = m_mimeDb.mimeTypeForName("application/octet-stream");
for (const QString &readMimeName : mimetypes) {
// Resolve aliases etc
const QMimeType mimetype = m_mimeDb.mimeTypeForName(readMimeName.trimmed());
if (!mimetype.isValid()) {
continue;
}
const QString mimetypeName = mimetype.name();
for (const QString &parent : mimetype.parentMimeTypes()) {
if (parent == "application/octet-stream") {
break;
}
m_childMimeTypes.insert(parent, mimetypeName);
}
if (m_supportedMimetypes.contains(appId, mimetypeName)) {
continue;
}
const QStringList parts = mimetypeName.split('/');
if (parts.count() != 2) {
continue;
}
const QString type = parts[0].trimmed();
m_applications[type].insert(appId);
m_supportedMimetypes.insert(appId, mimetypeName);
}
}
void Widget::setDefault(const QString &appName, const QSet<QString> &mimetypes, const QSet<QString> &unselectedMimetypes)
{
QString desktopFile = m_desktopFileNames.value(appName);
if (desktopFile.isEmpty()) {
qWarning() << "invalid" << appName;
return;
}
const QString filePath = QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)).absoluteFilePath("mimeapps.list");
QFile file(filePath);
// Read in existing mimeapps.list, skipping the lines for the mimetypes we're updating
QList<QByteArray> existingContent;
QList<QByteArray> existingAssociations;
if (file.open(QIODevice::ReadOnly)) {
bool inCorrectGroup = false;
while (!file.atEnd()) {
const QByteArray line = file.readLine().trimmed();
if (line.isEmpty()) {
continue;
}
if (line.startsWith('[')) {
inCorrectGroup = (line == "[Default Applications]");
if (!inCorrectGroup) {
existingContent.append(line);
}
continue;
}
if (!inCorrectGroup) {
existingContent.append(line);
continue;
}
if (!line.contains('=')) {
existingAssociations.append(line);
continue;
}
const QString mimetype = m_mimeDb.mimeTypeForName(line.split('=').first().trimmed()).name();
if (!mimetypes.contains(mimetype) && !unselectedMimetypes.contains(mimetype)) {
existingAssociations.append(line);
}
}
file.close();
} else {
qDebug() << "Unable to open file for reading";
}
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::warning(this, tr("Failed to store settings"), file.errorString());
return;
}
for (const QByteArray &line : existingContent) {
file.write(line + '\n');
}
file.write("\n[Default Applications]\n");
for (const QByteArray &line : existingAssociations) {
file.write(line + '\n');
}
for (const QString &mimetype : mimetypes) {
file.write(QString(mimetype + '=' + m_desktopFileNames[appName] + '\n').toUtf8());
}
return;
}
void Widget::loadIcons(const QString &path)
{
QFileInfo fi(path);
if (!fi.exists() || !fi.isDir()) {
return;
}
// TODO: avoid hardcoding
QStringList imageTypes({"*.svg", "*.svgz", "*.png", "*.xpm"});
QDirIterator it(path, imageTypes, QDir::Files, QDirIterator::Subdirectories);
while (it.hasNext()) {
it.next();
fi = it.fileInfo();
const QString name = fi.completeBaseName();
if (m_iconPaths.contains(name)) {
continue;
}
m_iconPaths[name] = fi.filePath();
}
}