File: filetypesview.cpp

package info (click to toggle)
kde-cli-tools 4%3A5.14.5-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 7,064 kB
  • sloc: cpp: 4,218; sh: 71; makefile: 11
file content (495 lines) | stat: -rw-r--r-- 17,611 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
/*  This file is part of the KDE project
    Copyright (C) 2000 - 2008 David Faure <faure@kde.org>
    Copyright (C) 2008 Urs Wolfer <uwolfer @ kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License or ( at
    your option ) version 3 or, at the discretion of KDE e.V. ( which shall
    act as a proxy as in section 14 of the GPLv3 ), any later version.

    This program 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
    General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; see the file COPYING.  If not, write to
    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
    Boston, MA 02110-1301, USA.
*/

// Own
#include "filetypesview.h"
#include "mimetypewriter.h"

// Qt
#include <QLabel>
#include <QLayout>
#include <QTimer>
#include <QBoxLayout>
#include <QPushButton>
#include <QStandardPaths>
#include <qdbusconnection.h>
#include <qdbusmessage.h>
#include <qdebug.h>

// KDE
#include <kbuildsycocaprogressdialog.h>
#include <klineedit.h>
#include <klocalizedstring.h>
#include <kservicetypeprofile.h>

#include <ksycoca.h>

// Local
#include "newtypedlg.h"
#include "filetypedetails.h"
#include "filegroupdetails.h"


K_PLUGIN_FACTORY(FileTypesViewFactory, registerPlugin<FileTypesView>();)


FileTypesView::FileTypesView(QWidget *parent, const QVariantList &)
  : KCModule(parent)
{
  m_fileTypesConfig = KSharedConfig::openConfig(QStringLiteral("filetypesrc"), KConfig::NoGlobals);

  setQuickHelp( i18n("<p><h1>File Associations</h1>"
    " This module allows you to choose which applications are associated"
    " with a given type of file. File types are also referred to as MIME types"
    " (MIME is an acronym which stands for \"Multipurpose Internet Mail"
    " Extensions\").</p><p> A file association consists of the following:"
    " <ul><li>Rules for determining the MIME-type of a file, for example"
    " the filename pattern *.png, which means 'all files with names that end"
    " in .png', is associated with the MIME type \"image/png\";</li>"
    " <li>A short description of the MIME-type, for example the description"
    " of the MIME type \"image/png\" is simply 'PNG image';</li>"
    " <li>An icon to be used for displaying files of the given MIME-type,"
    " so that you can easily identify the type of file in a file"
    " manager or file-selection dialog (at least for the types you use often);</li>"
    " <li>A list of the applications which can be used to open files of the"
    " given MIME-type -- if more than one application can be used then the"
    " list is ordered by priority.</li></ul>"
    " You may be surprised to find that some MIME types have no associated"
    " filename patterns; in these cases, KDE is able to determine the"
    " MIME-type by directly examining the contents of the file.</p>"));

  setButtons(Help | Apply);
  QString wtstr;

  QHBoxLayout* l = new QHBoxLayout(this);
  QVBoxLayout* leftLayout = new QVBoxLayout();
  l->addLayout( leftLayout );

  patternFilterLE = new KLineEdit(this);
  patternFilterLE->setClearButtonShown(true);
  patternFilterLE->setTrapReturnKey(true);
  patternFilterLE->setPlaceholderText(i18n("Find file type or filename pattern"));
  leftLayout->addWidget(patternFilterLE);

  connect(patternFilterLE, SIGNAL(textChanged(const QString &)),
          this, SLOT(slotFilter(const QString &)));

  wtstr = i18n("Enter a part of a filename pattern, and only file types with a "
               "matching file pattern will appear in the list. Alternatively, enter "
               "a part of a file type name as it appears in the list.");

  patternFilterLE->setWhatsThis( wtstr );

  typesLV = new TypesListTreeWidget(this);

  typesLV->setHeaderLabel(i18n("Known Types"));
  leftLayout->addWidget(typesLV);
  connect(typesLV, SIGNAL(currentItemChanged(QTreeWidgetItem *, QTreeWidgetItem *)),
          this, SLOT(updateDisplay(QTreeWidgetItem *)));
  connect(typesLV, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)),
          this, SLOT(slotDoubleClicked(QTreeWidgetItem *)));

  typesLV->setWhatsThis( i18n("Here you can see a hierarchical list of"
    " the file types which are known on your system. Click on the '+' sign"
    " to expand a category, or the '-' sign to collapse it. Select a file type"
    " (e.g. text/html for HTML files) to view/edit the information for that"
    " file type using the controls on the right.") );

  QHBoxLayout* btnsLay = new QHBoxLayout();
  leftLayout->addLayout(btnsLay);
  btnsLay->addStretch(1);
  QPushButton *addTypeB = new QPushButton(i18n("Add..."), this);
  addTypeB->setIcon(QIcon::fromTheme(QStringLiteral("list-add")));
  connect(addTypeB, SIGNAL(clicked()), SLOT(addType()));
  btnsLay->addWidget(addTypeB);

  addTypeB->setWhatsThis( i18n("Click here to add a new file type.") );

  m_removeTypeB = new QPushButton(i18n("&Remove"), this);
  m_removeTypeB->setIcon(QIcon::fromTheme(QStringLiteral("list-remove")));
  connect(m_removeTypeB, SIGNAL(clicked()), SLOT(removeType()));
  btnsLay->addWidget(m_removeTypeB);
  m_removeTypeB->setEnabled(false);
  m_removeButtonSaysRevert = false;

  // For the right panel, prepare a widget stack
  m_widgetStack = new QStackedWidget(this);

  l->addWidget( m_widgetStack );

  // File Type Details
  m_details = new FileTypeDetails( m_widgetStack );
  connect( m_details, SIGNAL( changed(bool) ),
           this, SLOT( setDirty(bool) ) );
  connect( m_details, SIGNAL( embedMajor(const QString &, bool &) ),
           this, SLOT( slotEmbedMajor(const QString &, bool &)));
  m_widgetStack->insertWidget( 1, m_details /*id*/ );

  // File Group Details
  m_groupDetails = new FileGroupDetails( m_widgetStack );
  connect( m_groupDetails, SIGNAL( changed(bool) ),
           this, SLOT( setDirty(bool) ) );
  m_widgetStack->insertWidget( 2,m_groupDetails /*id*/ );

  // Widget shown on startup
  m_emptyWidget = new QLabel( i18n("Select a file type by name or by extension"), m_widgetStack);
  m_emptyWidget->setAlignment( Qt::AlignCenter );
  m_widgetStack->insertWidget( 3,m_emptyWidget );

  m_widgetStack->setCurrentWidget( m_emptyWidget );

  connect(KSycoca::self(), SIGNAL(databaseChanged(QStringList)), SLOT(slotDatabaseChanged(QStringList)));
}

FileTypesView::~FileTypesView()
{
}

void FileTypesView::setDirty(bool state)
{
  emit changed(state);
  m_dirty = state;
}

// To order the mimetype list
static bool mimeTypeLessThan(const QMimeType& m1, const QMimeType& m2)
{
    return m1.name() < m2.name();
}

// Note that this method loses any newly-added (and not saved yet) mimetypes.
// So this is really only for load().
void FileTypesView::readFileTypes()
{
    typesLV->clear();
    m_majorMap.clear();
    m_itemList.clear();

    QMimeDatabase db;
    QList<QMimeType> mimetypes = db.allMimeTypes();
    std::sort(mimetypes.begin(), mimetypes.end(), mimeTypeLessThan);
    auto it2(mimetypes.constBegin());
    for (; it2 != mimetypes.constEnd(); ++it2) {
        const QString mimetype = (*it2).name();
        const int index = mimetype.indexOf(QLatin1Char('/'));
        const QString maj = mimetype.left(index);
        const QString min = mimetype.right(mimetype.length() - index+1);

        TypesListItem* groupItem = m_majorMap.value(maj);
        if ( !groupItem ) {
            groupItem = new TypesListItem(typesLV, maj);
            m_majorMap.insert(maj, groupItem);
        }

        TypesListItem *item = new TypesListItem(groupItem, (*it2));
        m_itemList.append( item );
    }
    updateDisplay(nullptr);
}

void FileTypesView::slotEmbedMajor(const QString &major, bool &embed)
{
    TypesListItem *groupItem = m_majorMap.value(major);
    if (!groupItem)
        return;

    embed = (groupItem->mimeTypeData().autoEmbed() == MimeTypeData::Yes);
}

void FileTypesView::slotFilter(const QString & patternFilter)
{
    for (int i = 0; i < typesLV->topLevelItemCount(); ++i) {
        typesLV->topLevelItem(i)->setHidden(true);
    }

    // insert all items and their group that match the filter
    Q_FOREACH(TypesListItem* it, m_itemList) {
        const MimeTypeData& mimeTypeData = it->mimeTypeData();
        if ( patternFilter.isEmpty() || mimeTypeData.matchesFilter(patternFilter) ) {
            TypesListItem *group = m_majorMap.value( mimeTypeData.majorType() );
            Q_ASSERT(group);
            if (group) {
                group->setHidden(false);
                it->setHidden(false);
            }
        } else {
            it->setHidden(true);
        }
    }
}

void FileTypesView::addType()
{
    const QStringList allGroups = m_majorMap.keys();

    NewTypeDialog dialog(allGroups, this);

    if (dialog.exec()) {
        const QString newMimeType = dialog.group() + QLatin1Char('/') + dialog.text();

        QTreeWidgetItemIterator it(typesLV);

        TypesListItem *group = m_majorMap.value(dialog.group());
        if ( !group ) {
            group = new TypesListItem(typesLV, dialog.group());
            m_majorMap.insert(dialog.group(), group);
        }

        // find out if our group has been filtered out -> insert if necessary
        QTreeWidgetItem *item = typesLV->topLevelItem(0);
        bool insert = true;
        while ( item ) {
            if ( item == group ) {
                insert = false;
                break;
            }
            item = typesLV->itemBelow(item);
        }
        if ( insert )
            typesLV->addTopLevelItem( group );

        TypesListItem *tli = new TypesListItem(group, newMimeType);
        m_itemList.append( tli );

        group->setExpanded(true);
        tli->setSelected(true);

        setDirty(true);
    }
}

void FileTypesView::removeType()
{
    TypesListItem *current = static_cast<TypesListItem *>(typesLV->currentItem());

    if (!current) {
        return;
    }

    const MimeTypeData& mimeTypeData = current->mimeTypeData();

    // Can't delete groups nor essential mimetypes (but the button should be
    // disabled already in these cases, so this is just extra safety).
    if (mimeTypeData.isMeta() || mimeTypeData.isEssential()) {
        return;
    }

    if (!mimeTypeData.isNew()) {
        removedList.append(mimeTypeData.name());
    }
    if (m_removeButtonSaysRevert) {
        // Nothing else to do for now, until saving
        updateDisplay(current);
    } else {
        QTreeWidgetItem *li = typesLV->itemAbove(current);
        if (!li)
            li = typesLV->itemBelow(current);
        if (!li)
            li = current->parent();

        current->parent()->takeChild(current->parent()->indexOfChild(current));
        m_itemList.removeAll(current);
        if (li) {
            li->setSelected(true);
        }
    }
    setDirty(true);
}

void FileTypesView::slotDoubleClicked(QTreeWidgetItem *item)
{
  if ( !item ) return;
  item->setExpanded( !item->isExpanded() );
}

void FileTypesView::updateDisplay(QTreeWidgetItem *item)
{
    TypesListItem *tlitem = static_cast<TypesListItem *>(item);
    updateRemoveButton(tlitem);

    if (!item) {
        m_widgetStack->setCurrentWidget(m_emptyWidget);
        return;
    }

    const bool wasDirty = m_dirty;

    MimeTypeData& mimeTypeData = tlitem->mimeTypeData();

    if (mimeTypeData.isMeta()) { // is a group
        m_widgetStack->setCurrentWidget(m_groupDetails);
        m_groupDetails->setMimeTypeData(&mimeTypeData);
    } else {
        m_widgetStack->setCurrentWidget(m_details);
        m_details->setMimeTypeData(&mimeTypeData);
    }

    // Updating the display indirectly called change(true)
    if (!wasDirty) {
        setDirty(false);
    }
}

void FileTypesView::updateRemoveButton(TypesListItem* tlitem)
{
    bool canRemove = false;
    m_removeButtonSaysRevert = false;

    if (tlitem) {
        const MimeTypeData& mimeTypeData = tlitem->mimeTypeData();
        if (!mimeTypeData.isMeta() && !mimeTypeData.isEssential()) {
            if (mimeTypeData.isNew()) {
                canRemove = true;
            } else {
                // We can only remove mimetypes that we defined ourselves, not those from freedesktop.org
                const QString mimeType = mimeTypeData.name();
                qDebug() << mimeType << "hasDefinitionFile:" << MimeTypeWriter::hasDefinitionFile(mimeType);
                if (MimeTypeWriter::hasDefinitionFile(mimeType)) {
                    canRemove = true;

                    // Is there a global definition for it?
                    const QStringList mimeFiles = QStandardPaths::locateAll(QStandardPaths::GenericDataLocation, QLatin1String("mime/") + mimeType + QStringLiteral(".xml") );
                    qDebug() << mimeFiles;
                    if (mimeFiles.count() >= 2 /*a local and a global*/) {
                        m_removeButtonSaysRevert = true;
                        qDebug() << removedList;
                        if (removedList.contains(mimeType)) {
                            canRemove = false; // already on the "to be reverted" list, user needs to save now
                        }
                    }
                }
            }
        }
    }

    if (m_removeButtonSaysRevert) {
        m_removeTypeB->setText(i18n("&Revert"));
        m_removeTypeB->setToolTip(i18n("Revert this file type to its initial system-wide definition"));
        m_removeTypeB->setWhatsThis(i18n("Click here to revert this file type to its initial system-wide definition, which undoes any changes made to the file type. Note that system-wide file types cannot be deleted. You can however empty their pattern list, to minimize the chances of them being used (but the file type determination from file contents can still end up using them)."));
    } else {
        m_removeTypeB->setText(i18n("&Remove"));
        m_removeTypeB->setToolTip(i18n("Delete this file type definition completely"));
        m_removeTypeB->setWhatsThis(i18n("Click here to delete this file type definition completely. This is only possible for user-defined file types. System-wide file types cannot be deleted. You can however empty their pattern list, to minimize the chances of them being used (but the file type determination from file contents can still end up using them)."));
    }

    m_removeTypeB->setEnabled(canRemove);
}


void FileTypesView::save()
{
    bool needUpdateMimeDb = false;
    bool needUpdateSycoca = false;
    bool didIt = false;
    // first, remove those items which we are asked to remove.
    Q_FOREACH(const QString& mime, removedList) {
        MimeTypeWriter::removeOwnMimeType(mime);
        didIt = true;
        needUpdateMimeDb = true;
        needUpdateSycoca = true; // remove offers for this mimetype
    }
    removedList.clear();

  // now go through all entries and sync those which are dirty.
  // don't use typesLV, it may be filtered
  QMap<QString,TypesListItem*>::iterator it1 = m_majorMap.begin();
  while ( it1 != m_majorMap.end() ) {
    TypesListItem *tli = *it1;
    if (tli->mimeTypeData().isDirty()) {
      qDebug() << "Entry " << tli->name() << " is dirty. Saving.";
      if (tli->mimeTypeData().sync())
          needUpdateMimeDb = true;
      didIt = true;
    }
    ++it1;
  }
    Q_FOREACH(TypesListItem* tli, m_itemList) {
        if (tli->mimeTypeData().isDirty()) {
            if (tli->mimeTypeData().isServiceListDirty())
                needUpdateSycoca = true;
            qDebug() << "Entry " << tli->name() << " is dirty. Saving.";
            if (tli->mimeTypeData().sync())
                needUpdateMimeDb = true;
            didIt = true;
        }
    }

  m_fileTypesConfig->sync();

  setDirty(false);

  if (needUpdateMimeDb) {
      MimeTypeWriter::runUpdateMimeDatabase();
  }
  if (needUpdateSycoca) {
      KBuildSycocaProgressDialog::rebuildKSycoca(this);
  }

  if (didIt) { // TODO make more specific: only if autoEmbed changed? Well, maybe this is useful for icon and glob changes too...
      // Trigger reparseConfiguration of filetypesrc in konqueror
      // TODO: the same for dolphin. Or we should probably define a global signal for this.
      // Or a KGlobalSettings thing.
      QDBusMessage message =
          QDBusMessage::createSignal(QStringLiteral("/KonqMain"), QStringLiteral("org.kde.Konqueror.Main"), QStringLiteral("reparseConfiguration"));
      QDBusConnection::sessionBus().send(message);
  }

  updateDisplay(typesLV->currentItem());
}

void FileTypesView::load()
{
    setEnabled(false);
    setCursor( Qt::WaitCursor );

    readFileTypes();

    unsetCursor();
    setDirty(false);
    setEnabled(true);
}

void FileTypesView::slotDatabaseChanged(const QStringList& changedResources)
{
    qDebug() << changedResources;
    if ( changedResources.contains(QStringLiteral("xdgdata-mime")) // changes in mimetype definitions
         || changedResources.contains(QStringLiteral("services")) ) { // changes in .desktop files

        m_details->refresh();

        // ksycoca has new KMimeTypes objects for us, make sure to update
        // our 'copies' to be in sync with it. Not important for OK, but
        // important for Apply (how to differentiate those 2?).
        // See BR 35071.

        Q_FOREACH(TypesListItem* tli, m_itemList) {
            tli->mimeTypeData().refresh();
        }
    }
}

void FileTypesView::defaults()
{
}

#include "filetypesview.moc"