File: mimetypedata.cpp

package info (click to toggle)
kde-cli-tools 4%3A6.3.4-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 7,396 kB
  • sloc: cpp: 4,368; sh: 42; makefile: 7
file content (593 lines) | stat: -rw-r--r-- 18,751 bytes parent folder | download
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
/* This file is part of the KDE project
   SPDX-FileCopyrightText: 2003 Waldo Bastian <bastian@kde.org>
   SPDX-FileCopyrightText: 2003, 2007 David Faure <faure@kde.org>

   SPDX-License-Identifier: GPL-2.0-only OR GPL-3.0-only
*/

#include "mimetypedata.h"
#include "mimetypewriter.h"
#include <KApplicationTrader>
#include <KConfigGroup>
#include <KParts/PartLoader>
#include <KProtocolManager>
#include <KService>
#include <KSharedConfig>
#include <QDebug>
#include <QFileInfo>
#include <QMimeDatabase>
#include <QStandardPaths>
#include <QXmlStreamReader>

MimeTypeData::MimeTypeData(const QString &major)
    : m_askSave(AskSaveDefault)
    , m_bNewItem(false)
    , m_bFullInit(true)
    , m_isGroup(true)
    , m_appServicesModified(false)
    , m_embedServicesModified(false)
    , m_userSpecifiedIconModified(false)
    , m_major(major)
{
    m_autoEmbed = readAutoEmbed();
}

MimeTypeData::MimeTypeData(const QMimeType &mime)
    : m_mimetype(mime)
    , m_askSave(AskSaveDefault)
    , // TODO: the code for initializing this is missing. FileTypeDetails initializes the checkbox instead...
    m_bNewItem(false)
    , m_bFullInit(false)
    , m_isGroup(false)
    , m_appServicesModified(false)
    , m_embedServicesModified(false)
    , m_userSpecifiedIconModified(false)
{
    const QString mimeName = m_mimetype.name();
    Q_ASSERT(!mimeName.isEmpty());
    const int index = mimeName.indexOf(QLatin1Char('/'));
    if (index != -1) {
        m_major = mimeName.left(index);
        m_minor = mimeName.mid(index + 1);
    } else {
        m_major = mimeName;
    }
    initFromQMimeType();
}

MimeTypeData::MimeTypeData(const QString &mimeName, bool)
    : m_askSave(AskSaveDefault)
    , m_bNewItem(true)
    , m_bFullInit(false)
    , m_isGroup(false)
    , m_appServicesModified(false)
    , m_embedServicesModified(false)
    , m_userSpecifiedIconModified(false)
{
    const int index = mimeName.indexOf(QLatin1Char('/'));
    if (index != -1) {
        m_major = mimeName.left(index);
        m_minor = mimeName.mid(index + 1);
    } else {
        m_major = mimeName;
    }
    m_autoEmbed = UseGroupSetting;
    // all the rest is empty by default
}

void MimeTypeData::initFromQMimeType()
{
    m_comment = m_mimetype.comment();
    setPatterns(m_mimetype.globPatterns());
    m_autoEmbed = readAutoEmbed();

    // Parse XML file to find out if the user specified a custom icon name
    QString file = name().toLower() + QLatin1String(".xml");
    QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("mime/") + file);
    if (mimeFiles.isEmpty()) {
        // This is for shared-mime-info < 1.3 that did not lowecase mime names
        file = name() + QLatin1String(".xml");
        mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("mime/") + file);
        if (mimeFiles.isEmpty()) {
            qWarning() << "No file found for" << file << ", even though the file appeared in a directory listing.";
            qWarning() << "Either it was just removed, or the directory doesn't have executable permission...";
            qWarning() << QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QStringLiteral("mime"), QStandardPaths::LocateDirectory);
            return;
        }
    }

    // Reverse iterator to get global first, then local.
    for (auto rIt = mimeFiles.crbegin(); rIt != mimeFiles.crend(); ++rIt) {
        const QString fullPath = *rIt;
        QFile qfile(fullPath);
        if (!qfile.open(QFile::ReadOnly)) {
            continue;
        }

        QXmlStreamReader xml(&qfile);
        if (xml.readNextStartElement()) {
            if (xml.name() != QLatin1String("mime-type")) {
                continue;
            }
            const QString mimeName = xml.attributes().value(QLatin1String("type")).toString();
            if (mimeName.isEmpty()) {
                continue;
            }
            if (QString::compare(mimeName, name(), Qt::CaseInsensitive) != 0) {
                qWarning() << "Got name" << mimeName << "in file" << file << "expected" << name();
            }

            while (xml.readNextStartElement()) {
                const auto tag = xml.name();
                if (tag == QLatin1String("icon")) {
                    m_userSpecifiedIcon = xml.attributes().value(QLatin1String("name")).toString();
                }
                xml.skipCurrentElement();
            }
        }
    }
}

MimeTypeData::AutoEmbed MimeTypeData::readAutoEmbed() const
{
    const KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
    const QString key = QStringLiteral("embed-") + name();
    const KConfigGroup group(config, "EmbedSettings");
    if (m_isGroup) {
        // embedding is false by default except for image/*, multipart/* and inode/* (hardcoded in konq)
        const bool defaultValue = (m_major == QLatin1String("image") || m_major == QLatin1String("multipart") || m_major == QLatin1String("inode"));
        return group.readEntry(key, defaultValue) ? Yes : No;
    } else {
        if (group.hasKey(key)) {
            return group.readEntry(key, false) ? Yes : No;
        }
        // TODO if ( !mimetype.property( "X-KDE-LocalProtocol" ).toString().isEmpty() )
        // TODO    return MimeTypeData::Yes; // embed by default for zip, tar etc.
        return MimeTypeData::UseGroupSetting;
    }
}

void MimeTypeData::writeAutoEmbed()
{
    KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
    if (!config->isConfigWritable(true)) {
        return;
    }

    const QString key = QStringLiteral("embed-") + name();
    KConfigGroup group(config, "EmbedSettings");
    if (m_isGroup) {
        group.writeEntry(key, m_autoEmbed == Yes);
    } else {
        if (m_autoEmbed == UseGroupSetting) {
            group.deleteEntry(key);
        } else {
            group.writeEntry(key, m_autoEmbed == Yes);
        }
    }
}

bool MimeTypeData::isEssential() const
{
    // Keep in sync with KMimeType::checkEssentialMimeTypes
    const QString n = name();
    if (n == QLatin1String("application/octet-stream")) {
        return true;
    }
    if (n == QLatin1String("inode/directory")) {
        return true;
    }
    if (n == QLatin1String("inode/blockdevice")) {
        return true;
    }
    if (n == QLatin1String("inode/chardevice")) {
        return true;
    }
    if (n == QLatin1String("inode/socket")) {
        return true;
    }
    if (n == QLatin1String("inode/fifo")) {
        return true;
    }
    if (n == QLatin1String("application/x-shellscript")) {
        return true;
    }
    if (n == QLatin1String("application/x-executable")) {
        return true;
    }
    if (n == QLatin1String("application/x-desktop")) {
        return true;
    }
    return false;
}

void MimeTypeData::setUserSpecifiedIcon(const QString &icon)
{
    if (icon == m_userSpecifiedIcon) {
        return;
    }
    m_userSpecifiedIcon = icon;
    m_userSpecifiedIconModified = true;
}

QStringList MimeTypeData::getAppOffers() const
{
    QStringList serviceIds;
    const KService::List offerList = KApplicationTrader::queryByMimeType(name());
    for (const auto &servicePtr : offerList) {
        serviceIds.append(servicePtr->storageId());
    }
    return serviceIds;
}

QStringList MimeTypeData::getPartOffers() const
{
    QStringList servicesIds;
    // We do not do any sorting, because KParts uses the order in which the entries are saved
    const auto partOfferList = KParts::PartLoader::partsForMimeType(name());
    for (const auto &metaData : partOfferList) {
        servicesIds.append(metaData.pluginId());
    }
    return servicesIds;
}

void MimeTypeData::getMyServiceOffers() const
{
    m_appServices = getAppOffers();
    m_embedParts = getPartOffers();
    m_bFullInit = true;
}

QStringList MimeTypeData::appServices() const
{
    if (!m_bFullInit) {
        getMyServiceOffers();
    }
    return m_appServices;
}

QStringList MimeTypeData::embedParts() const
{
    if (!m_bFullInit) {
        getMyServiceOffers();
    }
    return m_embedParts;
}

bool MimeTypeData::isMimeTypeDirty() const
{
    Q_ASSERT(!m_isGroup);
    if (m_bNewItem) {
        return true;
    }

    if (!m_mimetype.isValid()) {
        qWarning() << "MimeTypeData for" << name() << "says 'not new' but is without a mimetype? Should not happen.";
        return true;
    }

    if (m_mimetype.comment() != m_comment) {
        qDebug() << "Mimetype Comment Dirty: old=" << m_mimetype.comment() << "m_comment=" << m_comment;
        return true;
    }
    if (m_userSpecifiedIconModified) {
        qDebug() << "m_userSpecifiedIcon has changed. Now set to" << m_userSpecifiedIcon;
        return true;
    }

    QStringList storedPatterns = m_mimetype.globPatterns();
    storedPatterns.sort(); // see ctor
    if (storedPatterns != m_patterns) {
        qDebug() << "Mimetype Patterns Dirty: old=" << storedPatterns << "m_patterns=" << m_patterns;
        return true;
    }

    if (readAutoEmbed() != m_autoEmbed) {
        return true;
    }
    return false;
}

bool MimeTypeData::isServiceListDirty() const
{
    return !m_isGroup && (m_appServicesModified || m_embedServicesModified);
}

bool MimeTypeData::isDirty() const
{
    if (m_bNewItem) {
        qDebug() << "New item, need to save it";
        return true;
    }

    if (!m_isGroup) {
        if (isServiceListDirty()) {
            return true;
        }
        if (isMimeTypeDirty()) {
            return true;
        }
    } else { // is a group
        if (readAutoEmbed() != m_autoEmbed) {
            return true;
        }
    }

    if (m_askSave != AskSaveDefault) {
        return true;
    }

    // nothing seems to have changed, it's not dirty.
    return false;
}

bool MimeTypeData::sync()
{
    if (m_isGroup) {
        writeAutoEmbed();
        return false;
    }

    if (m_askSave != AskSaveDefault) {
        KSharedConfig::Ptr config = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);
        if (!config->isConfigWritable(true)) {
            return false;
        }
        KConfigGroup cg = config->group("Notification Messages");
        if (m_askSave == AskSaveYes) {
            // Ask
            cg.deleteEntry(QStringLiteral("askSave") + name());
            cg.deleteEntry(QStringLiteral("askEmbedOrSave") + name());
        } else {
            // Do not ask, open
            cg.writeEntry(QStringLiteral("askSave") + name(), QStringLiteral("no"));
            cg.writeEntry(QStringLiteral("askEmbedOrSave") + name(), QStringLiteral("no"));
        }
    }

    writeAutoEmbed();

    bool needUpdateMimeDb = false;
    if (isMimeTypeDirty()) {
        MimeTypeWriter mimeTypeWriter(name());
        mimeTypeWriter.setComment(m_comment);
        if (!m_userSpecifiedIcon.isEmpty()) {
            mimeTypeWriter.setIconName(m_userSpecifiedIcon);
        }
        mimeTypeWriter.setPatterns(m_patterns);
        if (!mimeTypeWriter.write()) {
            return false;
        }
        m_userSpecifiedIconModified = false;
        needUpdateMimeDb = true;
    }

    syncServices();

    return needUpdateMimeDb;
}

static const char s_DefaultApplications[] = "Default Applications";
static const char s_AddedAssociations[] = "Added Associations";
static const char s_RemovedAssociations[] = "Removed Associations";

void MimeTypeData::syncServices()
{
    if (!m_bFullInit) {
        return;
    }

    KSharedConfig::Ptr profile = KSharedConfig::openConfig(QStringLiteral("mimeapps.list"), KConfig::NoGlobals, QStandardPaths::GenericConfigLocation);

    if (!profile->isConfigWritable(true)) { // warn user if mimeapps.list is root-owned (#155126/#94504)
        return;
    }

    const QStringList oldAppServices = getAppOffers();
    if (oldAppServices != m_appServices) {
        // Save the default application according to mime-apps-spec 1.0
        KConfigGroup defaultApp(profile, s_DefaultApplications);
        saveDefaultApplication(defaultApp, m_appServices);
        // Save preferred services
        KConfigGroup addedApps(profile, s_AddedAssociations);
        saveServices(addedApps, m_appServices);
        KConfigGroup removedApps(profile, s_RemovedAssociations);
        saveRemovedServices(removedApps, m_appServices, oldAppServices);
    }

    KSharedConfig::Ptr kpartsProfile = KSharedConfig::openConfig(QStringLiteral("kpartsrc"), KConfig::NoGlobals);
    const QStringList oldPartServices = getPartOffers();
    if (oldPartServices != m_embedParts) {
        KConfigGroup addedParts(kpartsProfile, "Added KDE Part Associations");
        if (m_embedParts.isEmpty()) {
            addedParts.deleteEntry(name());
        } else {
            addedParts.writeXdgListEntry(name(), m_embedParts);
        }
        KConfigGroup removedParts(kpartsProfile, "Removed KDE Part Associations");
        saveRemovedServices(removedParts, m_embedParts, oldPartServices);
    }

    // Clean out any kde-mimeapps.list which would take precedence any cancel our changes.
    const QString desktops = QString::fromLocal8Bit(qgetenv("XDG_CURRENT_DESKTOP"));
    const auto desktopsSplit = desktops.split(QLatin1Char(':'), Qt::SkipEmptyParts);
    for (const QString &desktop : desktopsSplit) {
        const QString file =
            QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation) + QLatin1Char('/') + desktop.toLower() + QLatin1String("-mimeapps.list");
        if (QFileInfo::exists(file)) {
            qDebug() << "Cleaning up" << file;
            KConfig conf(file, KConfig::NoGlobals);
            KConfigGroup(&conf, s_DefaultApplications).deleteEntry(name());
            KConfigGroup(&conf, s_AddedAssociations).deleteEntry(name());
            KConfigGroup(&conf, s_RemovedAssociations).deleteEntry(name());
        }
    }

    m_appServicesModified = false;
    m_embedServicesModified = false;
}

static QStringList collectStorageIds(const QStringList &services)
{
    QStringList storageIds;

    for (const QString &service : services) {
        KService::Ptr pService = KService::serviceByStorageId(service);
        if (!pService) {
            qWarning() << "service with storage id" << service << "not found";
            continue; // Where did that one go?
        }

        storageIds.append(pService->storageId());
    }

    return storageIds;
}

void MimeTypeData::saveRemovedServices(KConfigGroup &config, const QStringList &services, const QStringList &oldServices)
{
    QStringList removedServiceList = config.readXdgListEntry(name());

    for (const QString &service : services) {
        // If removedServiceList.contains(service), then it was previously removed but has been added back
        removedServiceList.removeAll(service);
    }
    for (const QString &oldService : oldServices) {
        if (!services.contains(oldService)) {
            // The service was in m_appServices (or m_embedServices) but has been removed
            removedServiceList.append(oldService);
        }
    }
    if (removedServiceList.isEmpty()) {
        config.deleteEntry(name());
    } else {
        config.writeXdgListEntry(name(), removedServiceList);
    }
}

void MimeTypeData::saveServices(KConfigGroup &config, const QStringList &services)
{
    if (services.isEmpty()) {
        config.deleteEntry(name());
    } else {
        config.writeXdgListEntry(name(), collectStorageIds(services));
    }
}

void MimeTypeData::saveDefaultApplication(KConfigGroup &config, const QStringList &services)
{
    if (services.isEmpty()) {
        config.deleteEntry(name());
        return;
    }

    const QStringList storageIds = collectStorageIds(services);
    if (!storageIds.isEmpty()) {
        const QString firstStorageId = storageIds.at(0);
        config.writeXdgListEntry(name(), {firstStorageId});
    }
}

void MimeTypeData::refresh()
{
    if (m_isGroup) {
        return;
    }
    QMimeDatabase db;
    m_mimetype = db.mimeTypeForName(name());
    if (m_mimetype.isValid()) {
        if (m_bNewItem) {
            qDebug() << "OK, created" << name();
            m_bNewItem = false; // if this was a new mimetype, we just created it
        }
        if (!isMimeTypeDirty()) {
            // Update from the xml, in case something was changed from out of this kcm
            // (e.g. using KOpenWithDialog, or keditfiletype + kcmshell filetypes)
            initFromQMimeType();
        }
        if (!m_appServicesModified && !m_embedServicesModified) {
            m_bFullInit = false; // refresh services too
        }
    }
}

void MimeTypeData::getAskSave(bool &_askSave)
{
    if (m_askSave == AskSaveYes) {
        _askSave = true;
    }
    if (m_askSave == AskSaveNo) {
        _askSave = false;
    }
}

void MimeTypeData::setAskSave(bool _askSave)
{
    m_askSave = _askSave ? AskSaveYes : AskSaveNo;
}

bool MimeTypeData::canUseGroupSetting() const
{
    // "Use group settings" isn't available for zip, tar etc.; those have a builtin default...
    if (!m_mimetype.isValid()) { // e.g. new mimetype
        return true;
    }
    const bool hasLocalProtocolRedirect = !KProtocolManager::protocolForArchiveMimetype(name()).isEmpty();
    return !hasLocalProtocolRedirect;
}

void MimeTypeData::setPatterns(const QStringList &p)
{
    m_patterns = p;
    // Sort them, since update-mime-database doesn't respect order (order of globs file != order of xml),
    // and this code says things like if (m_mimetype.patterns() == m_patterns).
    // We could also sort in KMimeType::setPatterns but this would just slow down the
    // normal use case (anything else than this KCM) for no good reason.
    m_patterns.sort();
}

bool MimeTypeData::matchesFilter(const QString &filter) const
{
    if (name().contains(filter, Qt::CaseInsensitive)) {
        return true;
    }

    if (m_comment.contains(filter, Qt::CaseInsensitive)) {
        return true;
    }

    if (!m_patterns.filter(filter, Qt::CaseInsensitive).isEmpty()) {
        return true;
    }

    return false;
}

void MimeTypeData::setAppServices(const QStringList &dsl)
{
    if (!m_bFullInit) {
        getMyServiceOffers(); // so that m_bFullInit is true
    }
    m_appServices = dsl;
    m_appServicesModified = true;
}

void MimeTypeData::setEmbedParts(const QStringList &dsl)
{
    if (!m_bFullInit) {
        getMyServiceOffers(); // so that m_bFullInit is true
    }
    m_embedParts = dsl;
    m_embedServicesModified = true;
}

QString MimeTypeData::icon() const
{
    if (!m_userSpecifiedIcon.isEmpty()) {
        return m_userSpecifiedIcon;
    }
    if (m_mimetype.isValid()) {
        return m_mimetype.iconName();
    }
    return QString();
}