diff options
author | Eike Ziller <eike.ziller@theqtcompany.com> | 2015-02-04 09:32:46 +0100 |
---|---|---|
committer | Eike Ziller <eike.ziller@theqtcompany.com> | 2015-02-17 13:00:07 +0000 |
commit | 5a3a940ad3b3984b308b539e7f0456ce11d4d90e (patch) | |
tree | 539ac730a9291e9630c5772d78e5de1d9d4ece1e /src | |
parent | 365c1ddb903ebb8f183195244669499a300431d2 (diff) | |
download | qt-creator-5a3a940ad3b3984b308b539e7f0456ce11d4d90e.tar.gz |
Use new mime database
Change-Id: I4305872b6b11ef3e8a364280ffa5209a5a793600
Reviewed-by: Eike Ziller <eike.ziller@theqtcompany.com>
Diffstat (limited to 'src')
112 files changed, 623 insertions, 3240 deletions
diff --git a/src/plugins/android/Android.mimetypes.xml b/src/plugins/android/Android.mimetypes.xml new file mode 100644 index 0000000000..684fdc9971 --- /dev/null +++ b/src/plugins/android/Android.mimetypes.xml @@ -0,0 +1,8 @@ +<?xml version="1.0"?> +<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> + <mime-type type="application/vnd.google.android.android_manifest"> + <comment>Android manifest file</comment> + <sub-class-of type="application/xml"/> + <glob pattern="AndroidManifest.xml"/> + </mime-type> +</mime-info> diff --git a/src/plugins/android/Java.mimetypes.xml b/src/plugins/android/Java.mimetypes.xml deleted file mode 100644 index e3c6f49d2a..0000000000 --- a/src/plugins/android/Java.mimetypes.xml +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="text/x-java"> - <sub-class-of type="text/x-csrc"/> - <comment>Java Source file</comment> - <glob pattern="*.java"/> - </mime-type> -</mime-info> diff --git a/src/plugins/android/android.qrc b/src/plugins/android/android.qrc index 0cdbc5e010..26eb13809d 100644 --- a/src/plugins/android/android.qrc +++ b/src/plugins/android/android.qrc @@ -2,6 +2,6 @@ <qresource prefix="/android"> <file>images/QtAndroid.png</file> <file>images/download.png</file> - <file>Java.mimetypes.xml</file> + <file>Android.mimetypes.xml</file> </qresource> </RCC> diff --git a/src/plugins/android/androidplugin.cpp b/src/plugins/android/androidplugin.cpp index df7afe5392..4d33dea654 100644 --- a/src/plugins/android/androidplugin.cpp +++ b/src/plugins/android/androidplugin.cpp @@ -50,10 +50,10 @@ # include "androidqbspropertyprovider.h" #endif -#include <coreplugin/mimedatabase.h> #include <coreplugin/icore.h> #include <projectexplorer/kitmanager.h> #include <qtsupport/qtversionmanager.h> +#include <utils/mimetypes/mimedatabase.h> #include <QtPlugin> @@ -82,22 +82,9 @@ bool AndroidPlugin::initialize(const QStringList &arguments, QString *errorMessa addAutoReleasedObject(new Internal::JavaEditorFactory); ProjectExplorer::KitManager::registerKitInformation(new Internal::AndroidGdbServerKitInformation); - // AndroidManifest.xml editor - Core::MimeGlobPattern androidManifestGlobPattern(QLatin1String("AndroidManifest.xml"), Core::MimeGlobPattern::MaxWeight); - Core::MimeType androidManifestMimeType; - androidManifestMimeType.setType(QLatin1String(Constants::ANDROID_MANIFEST_MIME_TYPE)); - androidManifestMimeType.setComment(tr("Android Manifest file")); - androidManifestMimeType.setGlobPatterns(QList<Core::MimeGlobPattern>() << androidManifestGlobPattern); - androidManifestMimeType.setSubClassesOf(QStringList() << QLatin1String("application/xml")); - - if (!Core::MimeDatabase::addMimeType(androidManifestMimeType)) { - *errorMessage = tr("Could not add mime-type for AndroidManifest.xml editor."); - return false; - } - addAutoReleasedObject(new Internal::AndroidManifestEditorFactory); + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/android/Android.mimetypes.xml")); - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":android/Java.mimetypes.xml"), errorMessage)) - return false; + addAutoReleasedObject(new Internal::AndroidManifestEditorFactory); connect(ProjectExplorer::KitManager::instance(), SIGNAL(kitsLoaded()), this, SLOT(kitsRestored())); diff --git a/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.mimetypes.xml b/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.mimetypes.xml deleted file mode 100644 index 6e32748d2c..0000000000 --- a/src/plugins/autotoolsprojectmanager/AutotoolsProjectManager.mimetypes.xml +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="text/x-makefile"> - <sub-class-of type="text/plain"/> - <comment>Automake based Makefile</comment> - <glob weight="10" pattern="Makefile.am"/> - </mime-type> -</mime-info> diff --git a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp index 708f016056..620a487db4 100644 --- a/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp +++ b/src/plugins/autotoolsprojectmanager/autotoolsbuildconfiguration.cpp @@ -40,7 +40,6 @@ #include "configurestep.h" #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/buildinfo.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/kitinformation.h> @@ -48,6 +47,7 @@ #include <projectexplorer/target.h> #include <projectexplorer/toolchain.h> #include <qtsupport/customexecutablerunconfiguration.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QFileInfo> @@ -104,8 +104,10 @@ QList<BuildInfo *> AutotoolsBuildConfigurationFactory::availableBuilds(const Tar int AutotoolsBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const { - return (k && Core::MimeDatabase::findByFile(QFileInfo(projectPath)) - .matchesType(QLatin1String(Constants::MAKEFILE_MIMETYPE))) ? 0 : -1; + Utils::MimeDatabase mdb; + if (k && mdb.mimeTypeForFile(projectPath).matchesName(QLatin1String(Constants::MAKEFILE_MIMETYPE))) + return 0; + return -1; } QList<BuildInfo *> AutotoolsBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro b/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro index 6cd7856448..2c259f6c61 100644 --- a/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro +++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectmanager.pro @@ -29,4 +29,3 @@ SOURCES = autotoolsprojectplugin.cpp\ configurestep.cpp\ makefileparserthread.cpp\ makefileparser.cpp -RESOURCES += autotoolsproject.qrc diff --git a/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp b/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp index 95baa9d973..c9d568ff1b 100644 --- a/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp +++ b/src/plugins/autotoolsprojectmanager/autotoolsprojectplugin.cpp @@ -39,8 +39,6 @@ #include "configurestep.h" #include "autotoolsprojectconstants.h" -#include <coreplugin/mimedatabase.h> - #include <QStringList> #include <QtPlugin> @@ -57,10 +55,8 @@ void AutotoolsProjectPlugin::extensionsInitialized() bool AutotoolsProjectPlugin::initialize(const QStringList &arguments, QString *errorString) { - Q_UNUSED(arguments); - - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":autotoolsproject/AutotoolsProjectManager.mimetypes.xml"), errorString)) - return false; + Q_UNUSED(arguments) + Q_UNUSED(errorString) addAutoReleasedObject(new AutotoolsBuildConfigurationFactory); addAutoReleasedObject(new MakeStepFactory); diff --git a/src/plugins/bineditor/bineditorplugin.cpp b/src/plugins/bineditor/bineditorplugin.cpp index d8b0bfdac1..a47ddf9e92 100644 --- a/src/plugins/bineditor/bineditorplugin.cpp +++ b/src/plugins/bineditor/bineditorplugin.cpp @@ -56,7 +56,6 @@ #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/find/ifindsupport.h> #include <coreplugin/idocument.h> -#include <coreplugin/mimedatabase.h> #include <extensionsystem/pluginmanager.h> #include <utils/reloadpromptutils.h> #include <utils/qtcassert.h> diff --git a/src/plugins/clangcodemodel/clangcompletion.cpp b/src/plugins/clangcodemodel/clangcompletion.cpp index c9816a73ad..513d009312 100644 --- a/src/plugins/clangcodemodel/clangcompletion.cpp +++ b/src/plugins/clangcodemodel/clangcompletion.cpp @@ -34,7 +34,6 @@ #include <coreplugin/icore.h> #include <coreplugin/idocument.h> -#include <coreplugin/mimedatabase.h> #include <cplusplus/BackwardsScanner.h> #include <cplusplus/ExpressionUnderCursor.h> @@ -58,6 +57,7 @@ #include <texteditor/completionsettings.h> #include <utils/algorithm.h> +#include <utils/mimetypes/mimedatabase.h> #include <QCoreApplication> #include <QDirIterator> @@ -1095,7 +1095,8 @@ bool ClangCompletionAssistProcessor::completeInclude(const QTextCursor &cursor) if (!headerPaths.contains(currentFilePath)) headerPaths.append(currentFilePath); - const Core::MimeType mimeType = Core::MimeDatabase::findByType(QLatin1String("text/x-c++hdr")); + Utils::MimeDatabase mdb; + const Utils::MimeType mimeType = mdb.mimeTypeForName(QLatin1String("text/x-c++hdr")); const QStringList suffixes = mimeType.suffixes(); foreach (const ProjectPart::HeaderPath &headerPath, headerPaths) { diff --git a/src/plugins/clearcase/clearcaseplugin.cpp b/src/plugins/clearcase/clearcaseplugin.cpp index cb9445bbce..28df2e2d14 100644 --- a/src/plugins/clearcase/clearcaseplugin.cpp +++ b/src/plugins/clearcase/clearcaseplugin.cpp @@ -52,13 +52,13 @@ #include <coreplugin/icore.h> #include <coreplugin/infobar.h> #include <coreplugin/messagemanager.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/progressmanager/progressmanager.h> #include <coreplugin/locator/commandlocator.h> #include <projectexplorer/session.h> #include <projectexplorer/project.h> #include <projectexplorer/iprojectmanager.h> #include <utils/algorithm.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/synchronousprocess.h> #include <utils/parameteraction.h> #include <utils/fileutils.h> @@ -441,6 +441,7 @@ static const VcsBaseSubmitEditorParameters submitParameters = { bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *errorMessage) { + Q_UNUSED(errorMessage) using namespace Constants; using namespace Core::Constants; @@ -453,8 +454,7 @@ bool ClearCasePlugin::initialize(const QStringList & /*arguments */, QString *er connect(ProgressManager::instance(), SIGNAL(allTasksFinished(Core::Id)), this, SLOT(tasksFinished(Core::Id))); - if (!MimeDatabase::addMimeTypes(QLatin1String(":/clearcase/ClearCase.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/clearcase/ClearCase.mimetypes.xml")); m_settings.fromSettings(ICore::settings()); diff --git a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp index 87a523c6fc..79f796d9a2 100644 --- a/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp +++ b/src/plugins/cmakeprojectmanager/cmakebuildconfiguration.cpp @@ -37,7 +37,6 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/kit.h> @@ -45,6 +44,7 @@ #include <projectexplorer/projectmacroexpander.h> #include <projectexplorer/target.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QInputDialog> @@ -161,8 +161,10 @@ QList<ProjectExplorer::BuildInfo *> CMakeBuildConfigurationFactory::availableBui int CMakeBuildConfigurationFactory::priority(const ProjectExplorer::Kit *k, const QString &projectPath) const { - return (k && Core::MimeDatabase::findByFile(QFileInfo(projectPath)) - .matchesType(QLatin1String(Constants::CMAKEPROJECTMIMETYPE))) ? 0 : -1; + Utils::MimeDatabase mdb; + if (k && mdb.mimeTypeForFile(projectPath).matchesName(QLatin1String(Constants::CMAKEPROJECTMIMETYPE))) + return 0; + return -1; } QList<ProjectExplorer::BuildInfo *> CMakeBuildConfigurationFactory::availableSetups(const ProjectExplorer::Kit *k, diff --git a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp index 6ec413b613..7215e36a8b 100644 --- a/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp +++ b/src/plugins/cmakeprojectmanager/cmakeprojectplugin.cpp @@ -41,7 +41,7 @@ #include "cmakesettingspage.h" #include <coreplugin/featureprovider.h> -#include <coreplugin/mimedatabase.h> +#include <utils/mimetypes/mimedatabase.h> #include <QtPlugin> #include <QDebug> @@ -59,8 +59,8 @@ CMakeProjectPlugin::~CMakeProjectPlugin() bool CMakeProjectPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage) { - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":cmakeproject/CMakeProjectManager.mimetypes.xml"), errorMessage)) - return false; + Q_UNUSED(errorMessage) + Utils::MimeDatabase::addMimeTypes(QLatin1String(":cmakeproject/CMakeProjectManager.mimetypes.xml")); CMakeSettingsPage *cmp = new CMakeSettingsPage(); addAutoReleasedObject(cmp); diff --git a/src/plugins/coreplugin/basefilewizardfactory.cpp b/src/plugins/coreplugin/basefilewizardfactory.cpp index c11912334c..72357bd654 100644 --- a/src/plugins/coreplugin/basefilewizardfactory.cpp +++ b/src/plugins/coreplugin/basefilewizardfactory.cpp @@ -34,14 +34,14 @@ #include "icontext.h" #include "icore.h" #include "ifilewizardextension.h" -#include "mimedatabase.h" #include "editormanager/editormanager.h" #include "dialogs/promptoverwritedialog.h" #include <extensionsystem/pluginmanager.h> #include <utils/filewizardpage.h> -#include <utils/wizard.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/stringutils.h> +#include <utils/wizard.h> #include <QDir> #include <QFileInfo> @@ -476,7 +476,11 @@ QString BaseFileWizardFactory::buildFileName(const QString &path, QString BaseFileWizardFactory::preferredSuffix(const QString &mimeType) { - const QString rc = MimeDatabase::preferredSuffixByType(mimeType); + QString rc; + Utils::MimeDatabase mdb; + Utils::MimeType mt = mdb.mimeTypeForName(mimeType); + if (mt.isValid()) + rc = mt.preferredSuffix(); if (rc.isEmpty()) qWarning("%s: WARNING: Unable to find a preferred suffix for %s.", Q_FUNC_INFO, mimeType.toUtf8().constData()); diff --git a/src/plugins/coreplugin/core.qrc b/src/plugins/coreplugin/core.qrc index 35ae643470..549a1cdd55 100644 --- a/src/plugins/coreplugin/core.qrc +++ b/src/plugins/coreplugin/core.qrc @@ -63,7 +63,6 @@ <file>images/category_core.png</file> <file>images/category_texteditor.png</file> <file>images/category_design.png</file> - <file>editormanager/BinFiles.mimetypes.xml</file> <file>images/progressbar.png</file> <file>images/progressbar@2x.png</file> <file>images/help.png</file> diff --git a/src/plugins/coreplugin/corejsextensions.cpp b/src/plugins/coreplugin/corejsextensions.cpp index 2bc1d746d3..6924d877b6 100644 --- a/src/plugins/coreplugin/corejsextensions.cpp +++ b/src/plugins/coreplugin/corejsextensions.cpp @@ -30,9 +30,8 @@ #include "corejsextensions.h" -#include "mimedatabase.h" - #include <utils/fileutils.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QDir> @@ -90,7 +89,11 @@ QString UtilsJsExtension::absoluteFilePath(const QString &in) const QString UtilsJsExtension::preferredSuffix(const QString &mimetype) const { - return MimeDatabase::preferredSuffixByType(mimetype); + Utils::MimeDatabase mdb; + Utils::MimeType mt = mdb.mimeTypeForName(mimetype); + if (mt.isValid()) + return mt.preferredSuffix(); + return QString(); } QString UtilsJsExtension::fileName(const QString &path, const QString &extension) const diff --git a/src/plugins/coreplugin/coreplugin.cpp b/src/plugins/coreplugin/coreplugin.cpp index 471de54346..746f650dd0 100644 --- a/src/plugins/coreplugin/coreplugin.cpp +++ b/src/plugins/coreplugin/coreplugin.cpp @@ -33,7 +33,6 @@ #include "editmode.h" #include "helpmanager.h" #include "mainwindow.h" -#include "mimedatabase.h" #include "modemanager.h" #include "infobar.h" #include "iwizardfactory.h" @@ -212,7 +211,8 @@ bool CorePlugin::initialize(const QStringList &arguments, QString *errorMessage) void CorePlugin::extensionsInitialized() { - MimeDatabase::syncUserModifiedMimeTypes(); + // TODO +// MimeDatabase::syncUserModifiedMimeTypes(); if (m_designMode->designModeIsRequired()) addObject(m_designMode); m_findPlugin->extensionsInitialized(); diff --git a/src/plugins/coreplugin/coreplugin.pro b/src/plugins/coreplugin/coreplugin.pro index 08f9f34a5a..a868a4c2cc 100644 --- a/src/plugins/coreplugin/coreplugin.pro +++ b/src/plugins/coreplugin/coreplugin.pro @@ -72,7 +72,6 @@ SOURCES += corejsextensions.cpp \ rightpane.cpp \ sidebar.cpp \ fileiconprovider.cpp \ - mimedatabase.cpp \ icore.cpp \ infobar.cpp \ editormanager/ieditor.cpp \ @@ -196,7 +195,6 @@ HEADERS += corejsextensions.h \ rightpane.h \ sidebar.h \ fileiconprovider.h \ - mimedatabase.h \ settingsdatabase.h \ editormanager/systemeditor.h \ designmode.h \ diff --git a/src/plugins/coreplugin/documentmanager.cpp b/src/plugins/coreplugin/documentmanager.cpp index 7a31b5bba5..165b44b04f 100644 --- a/src/plugins/coreplugin/documentmanager.cpp +++ b/src/plugins/coreplugin/documentmanager.cpp @@ -32,7 +32,6 @@ #include "icore.h" #include "idocument.h" -#include "mimedatabase.h" #include "coreconstants.h" #include <coreplugin/dialogs/readonlyfilesdialog.h> @@ -46,6 +45,7 @@ #include <utils/fileutils.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/pathchooser.h> #include <utils/reloadpromptutils.h> @@ -740,7 +740,9 @@ QString DocumentManager::getSaveAsFileName(const IDocument *document, const QStr QString filterString; if (filter.isEmpty()) { - if (const MimeType &mt = MimeDatabase::findByFile(fi)) + Utils::MimeDatabase mdb; + const Utils::MimeType &mt = mdb.mimeTypeForFile(fi); + if (mt.isValid()) filterString = mt.filterString(); selectedFilter = &filterString; } else { @@ -1391,7 +1393,9 @@ void DocumentManager::populateOpenWithMenu(QMenu *menu, const QString &fileName) bool anyMatches = false; - if (const MimeType mt = MimeDatabase::findByFile(QFileInfo(fileName))) { + Utils::MimeDatabase mdb; + const Utils::MimeType mt = mdb.mimeTypeForFile(fileName); + if (mt.isValid()) { const EditorFactoryList factories = EditorManager::editorFactories(mt, false); const ExternalEditorList externalEditors = EditorManager::externalEditors(mt, false); anyMatches = !factories.empty() || !externalEditors.empty(); diff --git a/src/plugins/coreplugin/editormanager/BinFiles.mimetypes.xml b/src/plugins/coreplugin/editormanager/BinFiles.mimetypes.xml deleted file mode 100644 index 670ff3c481..0000000000 --- a/src/plugins/coreplugin/editormanager/BinFiles.mimetypes.xml +++ /dev/null @@ -1,18 +0,0 @@ -<?xml version="1.0"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="application/octet-stream"> - <comment>unknown</comment> - <glob pattern="*.a"/> - <glob pattern="*.dll"/> - <glob pattern="*.exe"/> - <glob pattern="*.lib"/> - <glob pattern="*.o"/> - <glob pattern="*.obj"/> - <glob pattern="*.out"/> - <glob pattern="*.so"/> - <!-- Magic for ELF binaries --> - <magic priority="99"> - <match type="byte" offset="0" value="\0x7f\0x45\0x4c\0x46"/> - </magic> - </mime-type> -</mime-info> diff --git a/src/plugins/coreplugin/editormanager/editormanager.cpp b/src/plugins/coreplugin/editormanager/editormanager.cpp index ea4ab16256..39b24cb058 100644 --- a/src/plugins/coreplugin/editormanager/editormanager.cpp +++ b/src/plugins/coreplugin/editormanager/editormanager.cpp @@ -54,7 +54,6 @@ #include <coreplugin/imode.h> #include <coreplugin/infobar.h> #include <coreplugin/iversioncontrol.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/modemanager.h> #include <coreplugin/outputpane.h> #include <coreplugin/outputpanemanager.h> @@ -68,6 +67,7 @@ #include <utils/fileutils.h> #include <utils/hostosinfo.h> #include <utils/macroexpander.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QClipboard> @@ -774,10 +774,11 @@ void EditorManagerPrivate::showPopupOrSelectDocument() Id EditorManagerPrivate::getOpenWithEditorId(const QString &fileName, bool *isExternalEditor) { // Collect editors that can open the file - MimeType mt = MimeDatabase::findByFile(fileName); + Utils::MimeDatabase mdb; + Utils::MimeType mt = mdb.mimeTypeForFile(fileName); //Unable to determine mime type of fileName. Falling back to text/plain", - if (!mt) - mt = MimeDatabase::findByType(QLatin1String("text/plain")); + if (!mt.isValid()) + mt = mdb.mimeTypeForName(QLatin1String("text/plain")); QList<Id> allEditorIds; QStringList allEditorDisplayNames; QList<Id> externalEditorIds; @@ -889,16 +890,17 @@ IEditor *EditorManagerPrivate::createEditor(Id editorId, const QString &fileName if (!editorId.isValid()) { const QFileInfo fileInfo(fileName); // Find by mime type - MimeType mimeType = MimeDatabase::findByFile(fileInfo); - if (!mimeType) { + Utils::MimeDatabase mdb; + Utils::MimeType mimeType = mdb.mimeTypeForFile(fileInfo); + if (!mimeType.isValid()) { qWarning("%s unable to determine mime type of %s/%s. Falling back to text/plain", Q_FUNC_INFO, fileName.toUtf8().constData(), editorId.name().constData()); - mimeType = MimeDatabase::findByType(QLatin1String("text/plain")); + mimeType = mdb.mimeTypeForName(QLatin1String("text/plain")); } // open text files > 48 MB in binary editor if (fileInfo.size() > EditorManager::maxTextFileSize() - && mimeType.type().startsWith(QLatin1String("text"))) { - mimeType = MimeDatabase::findByType(QLatin1String("application/octet-stream")); + && mimeType.name().startsWith(QLatin1String("text"))) { + mimeType = mdb.mimeTypeForName(QLatin1String("application/octet-stream")); } factories = EditorManager::editorFactories(mimeType, true); } else { @@ -1692,11 +1694,12 @@ bool EditorManagerPrivate::saveDocumentAs(IDocument *document) if (!document) return false; - const QString filter = MimeDatabase::allFiltersString(); + Utils::MimeDatabase mdb; + const QString filter = Utils::MimeDatabase::allFiltersString(); QString selectedFilter = - MimeDatabase::findByFile(document->filePath().toFileInfo()).filterString(); + mdb.mimeTypeForFile(document->filePath().toFileInfo()).filterString(); if (selectedFilter.isEmpty()) - selectedFilter = MimeDatabase::findByType(document->mimeType()).filterString(); + selectedFilter = mdb.mimeTypeForName(document->mimeType()).filterString(); const QString &absoluteFilePath = DocumentManager::getSaveAsFileName(document, filter, &selectedFilter); @@ -2192,54 +2195,58 @@ IEditor *EditorManager::activateEditorForDocument(IDocument *document, OpenEdito * or IExternalEditor), find the one best matching the mimetype passed in. * Recurse over the parent classes of the mimetype to find them. */ template <class EditorFactoryLike> -static void mimeTypeFactoryRecursion(const MimeType &mimeType, +static void mimeTypeFactoryRecursion(const Utils::MimeType &mimeType, const QList<EditorFactoryLike*> &allFactories, bool firstMatchOnly, QList<EditorFactoryLike*> *list) { typedef typename QList<EditorFactoryLike*>::const_iterator EditorFactoryLikeListConstIterator; // Loop factories to find type - const QString type = mimeType.type(); const EditorFactoryLikeListConstIterator fcend = allFactories.constEnd(); for (EditorFactoryLikeListConstIterator fit = allFactories.constBegin(); fit != fcend; ++fit) { // Exclude duplicates when recursing over xml or C++ -> C -> text. EditorFactoryLike *factory = *fit; - if (!list->contains(factory) && factory->mimeTypes().contains(type)) { - list->push_back(*fit); - if (firstMatchOnly) - return; + if (!list->contains(factory)) { + foreach (const QString &mt, factory->mimeTypes()) { + if (mimeType.matchesName(mt)) { + list->push_back(*fit); + if (firstMatchOnly) + return; + } + } } } // Any parent mime type classes? -> recurse - QStringList parentTypes = mimeType.subClassesOf(); - if (parentTypes.empty()) + QStringList parentNames = mimeType.parentMimeTypes(); + if (parentNames.empty()) return; - const QStringList::const_iterator pcend = parentTypes .constEnd(); - for (QStringList::const_iterator pit = parentTypes .constBegin(); pit != pcend; ++pit) { - if (const MimeType parent = MimeDatabase::findByType(*pit)) + Utils::MimeDatabase mdb; + foreach (const QString &parentName, parentNames) { + const Utils::MimeType parent = mdb.mimeTypeForName(parentName); + if (parent.isValid()) mimeTypeFactoryRecursion(parent, allFactories, firstMatchOnly, list); } } EditorManager::EditorFactoryList - EditorManager::editorFactories(const MimeType &mimeType, bool bestMatchOnly) + EditorManager::editorFactories(const Utils::MimeType &mimeType, bool bestMatchOnly) { EditorFactoryList rc; const EditorFactoryList allFactories = ExtensionSystem::PluginManager::getObjects<IEditorFactory>(); mimeTypeFactoryRecursion(mimeType, allFactories, bestMatchOnly, &rc); if (debugEditorManager) - qDebug() << Q_FUNC_INFO << mimeType.type() << " returns " << rc; + qDebug() << Q_FUNC_INFO << mimeType.name() << " returns " << rc; return rc; } EditorManager::ExternalEditorList - EditorManager::externalEditors(const MimeType &mimeType, bool bestMatchOnly) + EditorManager::externalEditors(const Utils::MimeType &mimeType, bool bestMatchOnly) { ExternalEditorList rc; const ExternalEditorList allEditors = ExtensionSystem::PluginManager::getObjects<IExternalEditor>(); mimeTypeFactoryRecursion(mimeType, allEditors, bestMatchOnly, &rc); if (debugEditorManager) - qDebug() << Q_FUNC_INFO << mimeType.type() << " returns " << rc; + qDebug() << Q_FUNC_INFO << mimeType.name() << " returns " << rc; return rc; } @@ -2308,7 +2315,7 @@ bool EditorManager::openExternalEditor(const QString &fileName, Id editorId) QStringList EditorManager::getOpenFileNames() { QString selectedFilter; - const QString &fileFilters = MimeDatabase::allFiltersString(&selectedFilter); + const QString &fileFilters = Utils::MimeDatabase::allFiltersString(&selectedFilter); return DocumentManager::getOpenFileNames(fileFilters, QString(), &selectedFilter); } diff --git a/src/plugins/coreplugin/editormanager/editormanager.h b/src/plugins/coreplugin/editormanager/editormanager.h index 1e63748e3a..2a09104cbb 100644 --- a/src/plugins/coreplugin/editormanager/editormanager.h +++ b/src/plugins/coreplugin/editormanager/editormanager.h @@ -37,6 +37,7 @@ #include <coreplugin/id.h> #include <coreplugin/idocument.h> // enumerations +#include <utils/mimetypes/mimetype.h> #include <QList> #include <QWidget> @@ -53,7 +54,6 @@ class IContext; class IEditor; class IEditorFactory; class IExternalEditor; -class MimeType; class IDocument; class IMode; class IVersionControl; @@ -157,8 +157,8 @@ public: QObject *object = 0, const char *member = 0); static void hideEditorStatusBar(const QString &id); - static EditorFactoryList editorFactories(const MimeType &mimeType, bool bestMatchOnly = true); - static ExternalEditorList externalEditors(const MimeType &mimeType, bool bestMatchOnly = true); + static EditorFactoryList editorFactories(const Utils::MimeType &mimeType, bool bestMatchOnly = true); + static ExternalEditorList externalEditors(const Utils::MimeType &mimeType, bool bestMatchOnly = true); static bool isAutoSaveFile(const QString &fileName); diff --git a/src/plugins/coreplugin/fileiconprovider.cpp b/src/plugins/coreplugin/fileiconprovider.cpp index d8d53d183d..d7f8579a9c 100644 --- a/src/plugins/coreplugin/fileiconprovider.cpp +++ b/src/plugins/coreplugin/fileiconprovider.cpp @@ -29,9 +29,9 @@ ****************************************************************************/ #include "fileiconprovider.h" -#include "mimedatabase.h" #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QApplication> @@ -91,7 +91,7 @@ public: m_cache.insert(suffix, fileIconPixmap); } - void registerIconOverlayForMimeType(const QIcon &icon, const MimeType &mimeType) + void registerIconOverlayForMimeType(const QIcon &icon, const Utils::MimeType &mimeType) { foreach (const QString &suffix, mimeType.suffixes()) registerIconOverlayForSuffix(icon, suffix); @@ -181,7 +181,9 @@ void registerIconOverlayForSuffix(const char *path, const char *suffix) */ void registerIconOverlayForMimeType(const QIcon &icon, const char *mimeType) { - instance()->registerIconOverlayForMimeType(icon, MimeDatabase::findByType(QString::fromLatin1(mimeType))); + Utils::MimeDatabase mdb; + instance()->registerIconOverlayForMimeType(icon, + mdb.mimeTypeForName(QString::fromLatin1(mimeType))); } /*! @@ -189,7 +191,9 @@ void registerIconOverlayForMimeType(const QIcon &icon, const char *mimeType) */ void registerIconOverlayForMimeType(const char *path, const char *mimeType) { - instance()->registerIconOverlayForMimeType(QIcon(QLatin1String(path)), MimeDatabase::findByType(QString::fromLatin1(mimeType))); + Utils::MimeDatabase mdb; + instance()->registerIconOverlayForMimeType(QIcon(QLatin1String(path)), + mdb.mimeTypeForName(QString::fromLatin1(mimeType))); } } // namespace FileIconProvider diff --git a/src/plugins/coreplugin/fileiconprovider.h b/src/plugins/coreplugin/fileiconprovider.h index 019f396ad4..d8d4012c53 100644 --- a/src/plugins/coreplugin/fileiconprovider.h +++ b/src/plugins/coreplugin/fileiconprovider.h @@ -38,8 +38,6 @@ namespace Core { -class MimeType; - namespace FileIconProvider { // Access to the single instance diff --git a/src/plugins/coreplugin/icore.cpp b/src/plugins/coreplugin/icore.cpp index a60db0d722..41ee44deb4 100644 --- a/src/plugins/coreplugin/icore.cpp +++ b/src/plugins/coreplugin/icore.cpp @@ -101,12 +101,6 @@ /*! - \fn MimeDatabase *ICore::mimeDatabase() - - Uses the MIME database to manage MIME types. -*/ - -/*! \fn QSettings *ICore::settings(QSettings::Scope scope = QSettings::UserScope) Returns the application's main settings object. diff --git a/src/plugins/coreplugin/idocument.h b/src/plugins/coreplugin/idocument.h index 0f19eb8a94..c5e4fa79f9 100644 --- a/src/plugins/coreplugin/idocument.h +++ b/src/plugins/coreplugin/idocument.h @@ -40,7 +40,6 @@ namespace Core { -class MimeType; class InfoBar; namespace Internal { diff --git a/src/plugins/coreplugin/mainwindow.cpp b/src/plugins/coreplugin/mainwindow.cpp index 04dc515d3b..00134e9e98 100644 --- a/src/plugins/coreplugin/mainwindow.cpp +++ b/src/plugins/coreplugin/mainwindow.cpp @@ -42,7 +42,6 @@ #include "idocumentfactory.h" #include "messagemanager.h" #include "modemanager.h" -#include "mimedatabase.h" #include "outputpanemanager.h" #include "plugindialog.h" #include "vcsmanager.h" @@ -77,6 +76,7 @@ #include <utils/algorithm.h> #include <utils/historycompleter.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/stylehelper.h> #include <utils/theme/theme.h> @@ -124,7 +124,6 @@ MainWindow::MainWindow() : m_vcsManager(new VcsManager), m_statusBarManager(0), m_modeManager(0), - m_mimeDatabase(new MimeDatabase), m_helpManager(new HelpManager), m_modeStack(new FancyTabWidget(this)), m_navigationWidget(0), @@ -298,8 +297,6 @@ MainWindow::~MainWindow() delete m_modeManager; m_modeManager = 0; - delete m_mimeDatabase; - m_mimeDatabase = 0; delete m_helpManager; m_helpManager = 0; @@ -311,9 +308,6 @@ bool MainWindow::init(QString *errorMessage) { Q_UNUSED(errorMessage) - if (!MimeDatabase::addMimeTypes(QLatin1String(":/core/editormanager/BinFiles.mimetypes.xml"), errorMessage)) - return false; - PluginManager::addObject(m_coreImpl); m_statusBarManager->init(); m_modeManager->init(); @@ -751,10 +745,12 @@ void MainWindow::openFile() static IDocumentFactory *findDocumentFactory(const QList<IDocumentFactory*> &fileFactories, const QFileInfo &fi) { - if (const MimeType mt = MimeDatabase::findByFile(fi)) { - const QString type = mt.type(); + Utils::MimeDatabase mdb; + const Utils::MimeType mt = mdb.mimeTypeForFile(fi); + if (mt.isValid()) { + const QString typeName = mt.name(); foreach (IDocumentFactory *factory, fileFactories) { - if (factory->mimeTypes().contains(type)) + if (factory->mimeTypes().contains(typeName)) return factory; } } diff --git a/src/plugins/coreplugin/mainwindow.h b/src/plugins/coreplugin/mainwindow.h index aeed763ebe..7ee205f792 100644 --- a/src/plugins/coreplugin/mainwindow.h +++ b/src/plugins/coreplugin/mainwindow.h @@ -58,7 +58,6 @@ class IDocument; class IWizardFactory; class JsExpander; class MessageManager; -class MimeDatabase; class ModeManager; class ProgressManager; class NavigationWidget; @@ -172,7 +171,6 @@ private: VcsManager *m_vcsManager; StatusBarManager *m_statusBarManager; ModeManager *m_modeManager; - MimeDatabase *m_mimeDatabase; HelpManager *m_helpManager; FancyTabWidget *m_modeStack; NavigationWidget *m_navigationWidget; diff --git a/src/plugins/coreplugin/mimedatabase.cpp b/src/plugins/coreplugin/mimedatabase.cpp deleted file mode 100644 index f1b950c91f..0000000000 --- a/src/plugins/coreplugin/mimedatabase.cpp +++ /dev/null @@ -1,2038 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms and -** conditions see http://www.qt.io/terms-conditions. For further information -** use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -****************************************************************************/ - -#include "mimedatabase.h" -#include "coreconstants.h" -#include "icore.h" - -#include <utils/qtcassert.h> -#include <utils/algorithm.h> - -#include <QByteArray> -#include <QCoreApplication> -#include <QDebug> -#include <QFile> -#include <QDir> -#include <QFileInfo> -#include <QLocale> -#include <QHash> -#include <QMultiHash> -#include <QRegExp> -#include <QSharedData> -#include <QSharedPointer> -#include <QStringList> -#include <QTextStream> -#include <QXmlStreamReader> -#include <QXmlStreamWriter> - -#include <functional> - -enum { debugMimeDB = 0 }; - -// XML tags in mime files -static const char mimeInfoTagC[] = "mime-info"; -static const char mimeTypeTagC[] = "mime-type"; -static const char mimeTypeAttributeC[] = "type"; -static const char subClassTagC[] = "sub-class-of"; -static const char commentTagC[] = "comment"; -static const char globTagC[] = "glob"; -static const char aliasTagC[] = "alias"; -static const char patternAttributeC[] = "pattern"; -static const char weightAttributeC[] = "weight"; -static const char localeAttributeC[] = "xml:lang"; - -static const char magicTagC[] = "magic"; -static const char priorityAttributeC[] = "priority"; -static const char matchTagC[] = "match"; -static const char matchValueAttributeC[] = "value"; -static const char matchTypeAttributeC[] = "type"; -static const char matchStringTypeValueC[] = "string"; -static const char matchByteTypeValueC[] = "byte"; -static const char matchOffsetAttributeC[] = "offset"; - -// Types -static const char textTypeC[] = "text/plain"; -static const char binaryTypeC[] = "application/octet-stream"; - -// UTF16 byte order marks -static const char bigEndianByteOrderMarkC[] = "\xFE\xFF"; -static const char littleEndianByteOrderMarkC[] = "\xFF\xFE"; - -// Fallback priorities, must be low. -enum { - BinaryMatchPriority = Core::MimeGlobPattern::MinWeight + 1, - TextMatchPriority -}; - -/*! - \class Core::IMagicMatcher - - \brief The IMagicMatcher class is an interface for a MIME type magic - matcher that examines file contents to determine the MIME type of a file. - - \sa Core::MimeType, Core::MimeDatabase, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -namespace Core { - -typedef QSharedPointer<MagicRuleMatcher> MagicRuleMatcherPtr; - -namespace Internal { - -/*! - \class Core::Internal::FileMatchContext - - \brief The FileMatchContext class is the context passed on to the MIME - types when looking for a file match. - - This class exists to enable reading the file contents \e {on demand}, - as opposed to each mime type trying to open and read while checking. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -class FileMatchContext -{ - Q_DISABLE_COPY(FileMatchContext) - -public: - // Max data to be read from a file - enum { MaxData = 2048 }; - - explicit FileMatchContext(const QFileInfo &fi); - - inline QString fileName() const { return m_fileName; } - // Return (cached) first MaxData bytes of file - QByteArray data(); - -private: - enum State { - // File cannot be read/does not exist - NoDataAvailable, - // Not read yet - DataNotRead, - // Available - DataRead }; - const QFileInfo m_fileInfo; - const QString m_fileName; - State m_state; - QByteArray m_data; -}; - -FileMatchContext::FileMatchContext(const QFileInfo &fi) : - m_fileInfo(fi), - m_fileName(fi.fileName()), - m_state(fi.isFile() && fi.isReadable() && fi.size() > 0 ? DataNotRead : NoDataAvailable) -{ -} - -QByteArray FileMatchContext::data() -{ - // Do we need to read? - if (m_state == DataNotRead) { - const QString fullName = m_fileInfo.absoluteFilePath(); - QFile file(fullName); - if (file.open(QIODevice::ReadOnly)) { - m_data = file.read(MaxData); - m_state = DataRead; - } else { - qWarning("%s failed to open %s: %s\n", Q_FUNC_INFO, fullName.toUtf8().constData(), file.errorString().toUtf8().constData()); - m_state = NoDataAvailable; - } - } - return m_data; -} - -/*! - \class Core::Internal::BinaryMatcher - \brief The BinaryMatcher class is the binary fallback matcher for the MIME - type \c{application/octet-stream}. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -class BinaryMatcher : public IMagicMatcher -{ -public: - BinaryMatcher() {} - virtual bool matches(const QByteArray & /*data*/) const { return true; } - virtual int priority() const { return BinaryMatchPriority; } -}; - -/*! - \class Core::Internal::HeuristicTextMagicMatcher - \brief The HeuristicTextMagicMatcher class implements a heuristic text file - matcher for MIME types. - - If the data does not contain any character below tab (9), it is detected as - text. Additionally, UTF16 byte order markers are checked. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -class HeuristicTextMagicMatcher : public IMagicMatcher -{ -public: - HeuristicTextMagicMatcher() {} - virtual bool matches(const QByteArray &data) const; - virtual int priority() const { return TextMatchPriority; } - - static bool isTextFile(const QByteArray &data); -}; - -bool HeuristicTextMagicMatcher::isTextFile(const QByteArray &data) -{ - const int size = data.size(); - for (int i = 0; i < size; i++) { - const char c = data.at(i); - if (c >= 0x01 && c < 0x09) // Sure-fire binary - return false; - if (c == 0) // Check for UTF16 - return data.startsWith(bigEndianByteOrderMarkC) || data.startsWith(littleEndianByteOrderMarkC); - } - return true; -} - -bool HeuristicTextMagicMatcher::matches(const QByteArray &data) const -{ - const bool rc = isTextFile(data); - if (debugMimeDB) - qDebug() << Q_FUNC_INFO << " on " << data.size() << " returns " << rc; - return rc; -} - -} // namespace Internal - -/*! - \class Core::MagicRule - \brief The MagicRule class is a base class for standard Magic matching rules - based on contents - and offset specification. - - Stores the offset and provides conversion helpers. - Base class for implementations for \c string and \c byte. - Others, such as \c little16 and \c big16, can be created when needed. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser - */ - -const QChar MagicRule::kColon(QLatin1Char(':')); - -MagicRule::MagicRule(int startPos, int endPos) : m_startPos(startPos), m_endPos(endPos) -{ -} - -MagicRule::~MagicRule() -{ -} - -int MagicRule::startPos() const -{ - return m_startPos; -} - -int MagicRule::endPos() const -{ - return m_endPos; -} - -QString MagicRule::toOffset(const QPair<int, int> &startEnd) -{ - return QString::fromLatin1("%1:%2").arg(startEnd.first).arg(startEnd.second); -} - -QPair<int, int> MagicRule::fromOffset(const QString &offset) -{ - const QStringList &startEnd = offset.split(kColon); - Q_ASSERT(startEnd.size() == 2); - return qMakePair(startEnd.at(0).toInt(), startEnd.at(1).toInt()); -} - -/*! - \class Core::MagicStringRule - \brief The MagicStringRule class provides rules for matching strings. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser - */ - -const QString MagicStringRule::kMatchType(QLatin1String("string")); - -MagicStringRule::MagicStringRule(const QString &s, int startPos, int endPos) : - MagicRule(startPos, endPos), m_pattern(s.toUtf8()) -{ -} - -MagicStringRule::~MagicStringRule() -{ -} - -QString MagicStringRule::matchType() const -{ - return kMatchType; -} - -QString MagicStringRule::matchValue() const -{ - return QLatin1String(m_pattern); -} - -bool MagicStringRule::matches(const QByteArray &data) const -{ - // Quick check - if ((startPos() + m_pattern.size()) > data.size()) - return false; - // Most common: some string at position 0: - if (startPos() == 0 && startPos() == endPos()) - return data.startsWith(m_pattern); - // Range - const int index = data.indexOf(m_pattern, startPos()); - const bool rc = index != -1 && index <= endPos(); - if (debugMimeDB) - qDebug() << "Checking " << m_pattern << startPos() << endPos() << " returns " << rc; - return rc; -} - -/*! - \class Core::MagicByteRule - \brief The MagicByteRule class provides rules for matching a sequence of - binary data. - - Format: - \code - \0x7f\0x45\0x4c\0x46 - \endcode - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser - */ - -const QString MagicByteRule::kMatchType(QLatin1String("byte")); - -MagicByteRule::MagicByteRule(const QString &s, int startPos, int endPos) : - MagicRule(startPos, endPos), m_bytesSize(0) -{ - if (validateByteSequence(s, &m_bytes)) - m_bytesSize = m_bytes.size(); - else - m_bytes.clear(); -} - -MagicByteRule::~MagicByteRule() -{ -} - -bool MagicByteRule::validateByteSequence(const QString &sequence, QList<int> *bytes) -{ - // Expect an hex format value like this: \0x7f\0x45\0x4c\0x46 - const QStringList &byteSequence = sequence.split(QLatin1Char('\\'), QString::SkipEmptyParts); - foreach (const QString &byte, byteSequence) { - bool ok; - const int hex = byte.toInt(&ok, 16); - if (ok) { - if (bytes) - bytes->push_back(hex); - } else { - return false; - } - } - return true; -} - -QString MagicByteRule::matchType() const -{ - return kMatchType; -} - -QString MagicByteRule::matchValue() const -{ - QString value; - foreach (int byte, m_bytes) - value.append(QString::fromLatin1("\\0x%1").arg(byte, 0, 16)); - return value; -} - -bool MagicByteRule::matches(const QByteArray &data) const -{ - if (m_bytesSize == 0) - return false; - - const int dataSize = data.size(); - for (int start = startPos(); start <= endPos(); ++start) { - if ((start + m_bytesSize) > dataSize) - return false; - - int matchAt = 0; - while (matchAt < m_bytesSize) { - if (data.at(start + matchAt) != m_bytes.at(matchAt)) - break; - ++matchAt; - } - if (matchAt == m_bytesSize) - return true; - } - - return false; -} - -/*! - \class Core::MagicRuleMatcher - - \brief The MagicRuleMatcher class implements a Magic matcher that checks the - number of rules based on the boolean operator OR. - - This class is used for rules parsed from XML files. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -MagicRuleMatcher::MagicRuleMatcher() : - m_priority(65535) -{ -} - -void MagicRuleMatcher::add(const MagicRuleSharedPointer &rule) -{ - m_list.append(rule); -} - -void MagicRuleMatcher::add(const MagicRuleList &ruleList) -{ - m_list.append(ruleList); -} - -MagicRuleMatcher::MagicRuleList MagicRuleMatcher::magicRules() const -{ - return m_list; -} - -bool MagicRuleMatcher::matches(const QByteArray &data) const -{ - const MagicRuleList::const_iterator cend = m_list.constEnd(); - for (MagicRuleList::const_iterator it = m_list.constBegin(); it != cend; ++it) - if ( (*it)->matches(data)) - return true; - return false; -} - -int MagicRuleMatcher::priority() const -{ - return m_priority; -} - -void MagicRuleMatcher::setPriority(int p) -{ - m_priority = p; -} - -IMagicMatcher::IMagicMatcherList MagicRuleMatcher::createMatchers( - const QHash<int, MagicRuleList> &rulesByPriority) -{ - IMagicMatcher::IMagicMatcherList matchers; - QHash<int, MagicRuleList>::const_iterator ruleIt = rulesByPriority.begin(); - for (; ruleIt != rulesByPriority.end(); ++ruleIt) { - MagicRuleMatcher *magicRuleMatcher = new MagicRuleMatcher(); - magicRuleMatcher->setPriority(ruleIt.key()); - magicRuleMatcher->add(ruleIt.value()); - matchers.append(IMagicMatcher::IMagicMatcherSharedPointer(magicRuleMatcher)); - } - return matchers; -} - -/*! - \class Core::GlobPattern - \brief The GlobPattern class provides a glob pattern for file names for - MIME type matching. - - \sa Core::MimeType, Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -MimeGlobPattern::MimeGlobPattern(const QString &pattern, unsigned weight) : - m_pattern(pattern), m_weight(weight) -{ - bool hasQuestionMark = pattern.contains(QLatin1Char('?')); - bool hasStar = pattern.contains(QLatin1Char('*')); - - if (!hasQuestionMark && hasStar && pattern.lastIndexOf(QLatin1Char('*')) == 0) { - m_type = Suffix; - } else if (!hasQuestionMark && !hasStar) { - m_type = Exact; - } else { - // This hopefully never happens as it is expensive. - m_type = Glob; - m_regexp.setPattern(pattern); - m_regexp.setPatternSyntax(QRegExp::Wildcard); - if (!m_regexp.isValid()) - qWarning("%s: Invalid wildcard '%s'.", Q_FUNC_INFO, pattern.toUtf8().constData()); - } -} - -MimeGlobPattern::~MimeGlobPattern() -{ -} - -bool MimeGlobPattern::matches(const QString &fileName) const -{ - if (m_type == Exact) - return fileName == m_pattern; - if (m_type == Suffix) - return fileName.endsWith(m_pattern.midRef(1)); - return m_regexp.exactMatch(fileName); -} - - -/*! - \class Core::MimeType - - \brief The MimeType class contains MIME type data used in \QC. - - Contains most information from standard MIME type XML database files. - - Currently, magic of types \c string anc \c bytes is supported. In addition, - C++ classes, derived from \c Core::IMagicMatcher can be added to check - on contents. - - The class provides a list of suffixes and a concept of a - \e {preferred suffix} (derived from glob patterns). This is used for example - to be able to configure the suffix used for C++ files in \QC. - - MIME type XML files look like follows: - \code - <?xml version="1.0" encoding="UTF-8"?> - <mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info"> - <!-- Mime types must match the desktop file associations --> - <mime-type type="application/vnd.qt.qmakeprofile"> - <comment xml:lang="en">Qt qmake Profile</comment> - <glob pattern="*.pro" weight="50"/> - </mime-type> - </mime-info> - \endcode - - \sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -class MimeTypeData : public QSharedData { -public: - typedef QHash<QString,QString> LocaleHash; - - MimeTypeData(); - - void clear(); - void assignSuffix(const QString &pattern); - void assignSuffixes(const QStringList &patterns); - void debug(QTextStream &str, int indent = 0) const; - - QRegExp suffixPattern; - - QString type; - QString comment; - - LocaleHash localeComments; - QStringList aliases; - QList<MimeGlobPattern> globPatterns; - QStringList subClassesOf; - QString preferredSuffix; - QStringList suffixes; - IMagicMatcher::IMagicMatcherList magicMatchers; -}; - -MimeTypeData::MimeTypeData() - // RE to match a suffix glob pattern: "*.ext" (and not sth like "Makefile" or - // "*.log[1-9]" - : suffixPattern(QLatin1String("^\\*(?:\\.[\\w+]+)+$")) -{ - QTC_CHECK(suffixPattern.isValid()); -} - -void MimeTypeData::clear() -{ - type.clear(); - comment.clear(); - aliases.clear(); - globPatterns.clear(); - subClassesOf.clear(); - preferredSuffix.clear(); - suffixes.clear(); - magicMatchers.clear(); -} - -void MimeTypeData::assignSuffix(const QString &pattern) -{ - if (suffixPattern.exactMatch(pattern)) { - const QString suffix = pattern.right(pattern.size() - 2); - suffixes.push_back(suffix); - if (preferredSuffix.isEmpty()) - preferredSuffix = suffix; - } -} - -void MimeTypeData::assignSuffixes(const QStringList &patterns) -{ - foreach (const QString &pattern, patterns) - assignSuffix(pattern); -} - -void MimeTypeData::debug(QTextStream &str, int indent) const -{ - const QString indentS = QString(indent, QLatin1Char(' ')); - const QLatin1Char comma(','); - str << indentS << "Type: " << type; - if (!aliases.empty()) - str << " Aliases: " << aliases.join(comma); - str << ", magic: " << magicMatchers.size() << '\n'; - str << indentS << "Comment: " << comment << '\n'; - if (!subClassesOf.empty()) - str << indentS << "SubClassesOf: " << subClassesOf.join(comma) << '\n'; - if (!globPatterns.empty()) { - str << indentS << "Glob: "; - foreach (const MimeGlobPattern &gp, globPatterns) - str << gp.pattern() << '(' << gp.weight() << ')'; - str << '\n'; - if (!suffixes.empty()) { - str << indentS << "Suffixes: " << suffixes.join(comma) - << " preferred: " << preferredSuffix << '\n'; - } - } - str << '\n'; -} - -// ---------------- MimeType -MimeType::MimeType() : - m_d(new MimeTypeData) -{ -} - -MimeType::MimeType(const MimeType &rhs) : - m_d(rhs.m_d) -{ -} - -MimeType &MimeType::operator=(const MimeType &rhs) -{ - if (this != &rhs) - m_d = rhs.m_d; - return *this; -} - -MimeType::MimeType(const MimeTypeData &d) : - m_d(new MimeTypeData(d)) -{ -} - -MimeType::~MimeType() -{ -} - -void MimeType::clear() -{ - m_d->clear(); -} - -bool MimeType::isNull() const -{ - return m_d->type.isEmpty(); -} - -MimeType::operator bool() const -{ - return !isNull(); -} - -bool MimeType::isTopLevel() const -{ - return m_d->subClassesOf.empty(); -} - -QString MimeType::type() const -{ - return m_d->type; -} - -void MimeType::setType(const QString &type) -{ - m_d->type = type; -} - -QString MimeType::comment() const -{ - return m_d->comment; -} - -void MimeType::setComment(const QString &comment) -{ - m_d->comment = comment; -} - -// Return "en", "de", etc. derived from "en_US", de_DE". -static inline QString systemLanguage() -{ - QString name = QLocale::system().name(); - const int underScorePos = name.indexOf(QLatin1Char('_')); - if (underScorePos != -1) - name.truncate(underScorePos); - return name; -} - -QString MimeType::localeComment(const QString &localeArg) const -{ - const QString locale = localeArg.isEmpty() ? systemLanguage() : localeArg; - const MimeTypeData::LocaleHash::const_iterator it = m_d->localeComments.constFind(locale); - if (it == m_d->localeComments.constEnd()) - return m_d->comment; - return it.value(); -} - -void MimeType::setLocaleComment(const QString &locale, const QString &comment) -{ - m_d->localeComments[locale] = comment; -} - -QStringList MimeType::aliases() const -{ - return m_d->aliases; -} - -void MimeType::setAliases(const QStringList &a) -{ - m_d->aliases = a; -} - -QList<MimeGlobPattern> MimeType::globPatterns() const -{ - return m_d->globPatterns; -} - -void MimeType::setGlobPatterns(const QList<MimeGlobPattern> &g) -{ - m_d->globPatterns = g; - - QString oldPrefferedSuffix = m_d->preferredSuffix; - m_d->suffixes.clear(); - m_d->preferredSuffix.clear(); - m_d->assignSuffixes(MimeDatabase::fromGlobPatterns(g)); - if (m_d->preferredSuffix != oldPrefferedSuffix && m_d->suffixes.contains(oldPrefferedSuffix)) - m_d->preferredSuffix = oldPrefferedSuffix; -} - -QStringList MimeType::subClassesOf() const -{ - return m_d->subClassesOf; -} - -void MimeType::setSubClassesOf(const QStringList &s) -{ - m_d->subClassesOf = s; -} - -QString MimeType::preferredSuffix() const -{ - return m_d->preferredSuffix; -} - -bool MimeType::setPreferredSuffix(const QString &s) -{ - if (!m_d->suffixes.contains(s)) { - qWarning("%s: Attempt to set preferred suffix to '%s', which is not in the list of suffixes: %s.", - m_d->type.toUtf8().constData(), - s.toUtf8().constData(), - m_d->suffixes.join(QLatin1Char(',')).toUtf8().constData()); - return false; - } - m_d->preferredSuffix = s; - return true; -} - -QString MimeType::formatFilterString(const QString &description, const QList<MimeGlobPattern> &globs) -{ - QString rc; - if (globs.empty()) // Binary files - return rc; - { - QTextStream str(&rc); - str << description; - if (!globs.empty()) { - str << " ("; - const int size = globs.size(); - for (int i = 0; i < size; i++) { - if (i) - str << ' '; - str << globs.at(i).pattern(); - } - str << ')'; - } - } - return rc; -} - -QString MimeType::filterString() const -{ - // @todo: Use localeComment() once creator is shipped with translations - return formatFilterString(comment(), m_d->globPatterns); -} - -bool MimeType::matchesType(const QString &type) const -{ - return m_d->type == type || m_d->aliases.contains(type); -} - -unsigned MimeType::matchesFile(const QFileInfo &file) const -{ - Internal::FileMatchContext context(file); - const unsigned suffixPriority = matchesFileBySuffix(context); - if (suffixPriority >= MimeGlobPattern::MaxWeight) - return suffixPriority; - return qMax(suffixPriority, matchesFileByContent(context)); -} - -unsigned MimeType::matchesFileBySuffix(Internal::FileMatchContext &c) const -{ - // check globs - foreach (const MimeGlobPattern &gp, m_d->globPatterns) { - if (gp.matches(c.fileName())) - return gp.weight(); - } - return 0; -} - -unsigned MimeType::matchesFileByContent(Internal::FileMatchContext &c) const -{ - // Nope, try magic matchers on context data - if (m_d->magicMatchers.isEmpty()) - return 0; - - return matchesData(c.data()); -} - -unsigned MimeType::matchesData(const QByteArray &data) const -{ - unsigned priority = 0; - if (!data.isEmpty()) { - foreach (const IMagicMatcher::IMagicMatcherSharedPointer &matcher, m_d->magicMatchers) { - const unsigned magicPriority = matcher->priority(); - if (magicPriority > priority && matcher->matches(data)) - priority = magicPriority; - } - } - return priority; -} - -QStringList MimeType::suffixes() const -{ - return m_d->suffixes; -} - -void MimeType::addMagicMatcher(const IMagicMatcherSharedPointer &matcher) -{ - m_d->magicMatchers.push_back(matcher); -} - -const MimeType::IMagicMatcherList &MimeType::magicMatchers() const -{ - return m_d->magicMatchers; -} - -void MimeType::setMagicMatchers(const IMagicMatcherList &matchers) -{ - m_d->magicMatchers = matchers; -} - -namespace { -struct RemovePred : std::unary_function<MimeType::IMagicMatcherSharedPointer, bool> -{ - RemovePred(bool keepRuleBased) : m_keepRuleBase(keepRuleBased) {} - bool m_keepRuleBase; - - bool operator()(const MimeType::IMagicMatcherSharedPointer &matcher) { - if ((m_keepRuleBase && !dynamic_cast<MagicRuleMatcher *>(matcher.data())) - || (!m_keepRuleBase && dynamic_cast<MagicRuleMatcher *>(matcher.data()))) - return true; - return false; - } -}; -} // Anonymous - -MimeType::IMagicMatcherList MimeType::magicRuleMatchers() const -{ - IMagicMatcherList ruleMatchers = m_d->magicMatchers; - Utils::erase(ruleMatchers, RemovePred(true)); - return ruleMatchers; -} - -void MimeType::setMagicRuleMatchers(const IMagicMatcherList &matchers) -{ - Utils::erase(m_d->magicMatchers, RemovePred(false)); - - m_d->magicMatchers.append(matchers); -} - -QDebug operator<<(QDebug d, const MimeType &mt) -{ - QString s; - { - QTextStream str(&s); - mt.m_d->debug(str); - } - d << s; - return d; -} - -namespace Internal { - -/*! - \class Core::Internal::BaseMimeTypeParser - \brief The BaseMimeTypeParser class provides a generic parser for a - sequence of <mime-type>. - - This class calls the abstract handler function process for the MIME types - it finds. - - \sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::MimeTypeParser -*/ - -class BaseMimeTypeParser -{ - Q_DISABLE_COPY(BaseMimeTypeParser) - -public: - BaseMimeTypeParser() {} - virtual ~BaseMimeTypeParser() {} - - bool parse(QIODevice *dev, const QString &fileName, QString *errorMessage); - -private: - // Overwrite to process the sequence of parsed data - virtual bool process(const MimeType &t, QString *errorMessage) = 0; - - void addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const; - - enum ParseStage { ParseBeginning, - ParseMimeInfo, - ParseMimeType, - ParseComment, - ParseGlobPattern, - ParseSubClass, - ParseAlias, - ParseMagic, - ParseMagicMatchRule, - ParseOtherMimeTypeSubTag, - ParseError }; - - static ParseStage nextStage(ParseStage currentStage, const QStringRef &startElement); -}; - -void BaseMimeTypeParser::addGlobPattern(const QString &pattern, const QString &weight, MimeTypeData *d) const -{ - if (pattern.isEmpty()) - return; - // Collect patterns as a QRegExp list and filter out the plain - // suffix ones for our suffix list. Use first one as preferred - if (weight.isEmpty()) - d->globPatterns.push_back(MimeGlobPattern(pattern)); - else - d->globPatterns.push_back(MimeGlobPattern(pattern, weight.toInt())); - - d->assignSuffix(pattern); -} - -BaseMimeTypeParser::ParseStage BaseMimeTypeParser::nextStage(ParseStage currentStage, const QStringRef &startElement) -{ - switch (currentStage) { - case ParseBeginning: - if (startElement == QLatin1String(mimeInfoTagC)) - return ParseMimeInfo; - if (startElement == QLatin1String(mimeTypeTagC)) - return ParseMimeType; - return ParseError; - case ParseMimeInfo: - return startElement == QLatin1String(mimeTypeTagC) ? ParseMimeType : ParseError; - case ParseMimeType: - case ParseComment: - case ParseGlobPattern: - case ParseSubClass: - case ParseAlias: - case ParseOtherMimeTypeSubTag: - case ParseMagicMatchRule: - if (startElement == QLatin1String(mimeTypeTagC)) // Sequence of <mime-type> - return ParseMimeType; - if (startElement == QLatin1String(commentTagC )) - return ParseComment; - if (startElement == QLatin1String(globTagC)) - return ParseGlobPattern; - if (startElement == QLatin1String(subClassTagC)) - return ParseSubClass; - if (startElement == QLatin1String(aliasTagC)) - return ParseAlias; - if (startElement == QLatin1String(magicTagC)) - return ParseMagic; - if (startElement == QLatin1String(matchTagC)) - return ParseMagicMatchRule; - return ParseOtherMimeTypeSubTag; - case ParseMagic: - if (startElement == QLatin1String(matchTagC)) - return ParseMagicMatchRule; - break; - case ParseError: - break; - } - return ParseError; -} - -// Parse int number from an (attribute) string) -static bool parseNumber(const QString &n, int *target, QString *errorMessage) -{ - bool ok; - *target = n.toInt(&ok); - if (!ok) { - *errorMessage = QString::fromLatin1("Not a number \"%1\".").arg(n); - return false; - } - return true; -} - -// Evaluate a magic match rule like -// <match value="must be converted with BinHex" type="string" offset="11"/> -// <match value="0x9501" type="big16" offset="0:64"/> -static bool addMagicMatchRule(const QXmlStreamAttributes &atts, - const MagicRuleMatcherPtr &ruleMatcher, - QString *errorMessage) -{ - const QStringRef type = atts.value(QLatin1String(matchTypeAttributeC)); - if (type != QLatin1String(matchStringTypeValueC) && - type != QLatin1String(matchByteTypeValueC)) { - qWarning("%s: match type %s is not supported.", Q_FUNC_INFO, type.toUtf8().constData()); - return true; - } - const QString value = atts.value(QLatin1String(matchValueAttributeC)).toString(); - if (value.isEmpty()) { - *errorMessage = QString::fromLatin1("Empty match value detected."); - return false; - } - // Parse for offset as "1" or "1:10" - int startPos, endPos; - const QString offsetS = atts.value(QLatin1String(matchOffsetAttributeC)).toString(); - const int colonIndex = offsetS.indexOf(QLatin1Char(':')); - const QString startPosS = colonIndex == -1 ? offsetS : offsetS.mid(0, colonIndex); - const QString endPosS = colonIndex == -1 ? offsetS : offsetS.mid(colonIndex + 1); - if (!parseNumber(startPosS, &startPos, errorMessage) || !parseNumber(endPosS, &endPos, errorMessage)) - return false; - if (debugMimeDB) - qDebug() << Q_FUNC_INFO << value << startPos << endPos; - - if (type == QLatin1String(matchStringTypeValueC)) - ruleMatcher->add(QSharedPointer<MagicRule>(new MagicStringRule(value, startPos, endPos))); - else - ruleMatcher->add(QSharedPointer<MagicRule>(new MagicByteRule(value, startPos, endPos))); - return true; -} - -bool BaseMimeTypeParser::parse(QIODevice *dev, const QString &fileName, QString *errorMessage) -{ - MimeTypeData data; - MagicRuleMatcherPtr ruleMatcher; - QXmlStreamReader reader(dev); - ParseStage ps = ParseBeginning; - QXmlStreamAttributes atts; - while (!reader.atEnd()) { - switch (reader.readNext()) { - case QXmlStreamReader::StartElement: - ps = nextStage(ps, reader.name()); - atts = reader.attributes(); - switch (ps) { - case ParseMimeType: { // start parsing a type - const QString type = atts.value(QLatin1String(mimeTypeAttributeC)).toString(); - if (type.isEmpty()) - reader.raiseError(QString::fromLatin1("Missing 'type'-attribute")); - else - data.type = type; - } - break; - case ParseGlobPattern: - addGlobPattern(atts.value(QLatin1String(patternAttributeC)).toString(), - atts.value(QLatin1String(weightAttributeC)).toString(), &data); - break; - case ParseSubClass: { - const QString inheritsFrom = atts.value(QLatin1String(mimeTypeAttributeC)).toString(); - if (!inheritsFrom.isEmpty()) - data.subClassesOf.push_back(inheritsFrom); - } - break; - case ParseComment: { - // comments have locale attributes. We want the default, English one - const QStringRef locale = atts.value(QLatin1String(localeAttributeC)); - const QString comment = QCoreApplication::translate("MimeType", reader.readElementText().toLatin1()); - if (locale.isEmpty()) - data.comment = comment; - else - data.localeComments.insert(locale.toString(), comment); - } - break; - case ParseAlias: { - const QStringRef alias = atts.value(QLatin1String(mimeTypeAttributeC)); - if (!alias.isEmpty()) - data.aliases.push_back(alias.toString()); - } - break; - case ParseMagic: { - int priority = 0; - const QStringRef priorityS = atts.value(QLatin1String(priorityAttributeC)); - if (!priorityS.isEmpty()) { - if (!parseNumber(priorityS.toString(), &priority, errorMessage)) - return false; - - } - ruleMatcher = MagicRuleMatcherPtr(new MagicRuleMatcher); - ruleMatcher->setPriority(priority); - } - break; - case ParseMagicMatchRule: - QTC_ASSERT(!ruleMatcher.isNull(), return false); - if (!addMagicMatchRule(atts, ruleMatcher, errorMessage)) - return false; - break; - case ParseError: - reader.raiseError(QString::fromLatin1("Unexpected element <%1>").arg(reader.name().toString())); - break; - default: - break; - } // switch nextStage - break; - // continue switch QXmlStreamReader::Token... - case QXmlStreamReader::EndElement: // Finished element - if (reader.name() == QLatin1String(mimeTypeTagC)) { - if (!process(MimeType(data), errorMessage)) - return false; - data.clear(); - } else { - // Finished a match sequence - if (reader.name() == QLatin1String(magicTagC)) { - QTC_ASSERT(!ruleMatcher.isNull(), return false); - data.magicMatchers.push_back(ruleMatcher); - ruleMatcher = MagicRuleMatcherPtr(); - } - } - break; - - default: - break; - } // switch reader.readNext() - } - - if (reader.hasError()) { - *errorMessage = QString::fromLatin1("An error has been encountered at line %1 of %2: %3:").arg(reader.lineNumber()).arg(fileName, reader.errorString()); - return false; - } - return true; -} - -} // namespace Internal - -// MimeMapEntry: Entry of a type map, consisting of type and level. - -enum { Dangling = 32767 }; - -struct MimeMapEntry -{ - explicit MimeMapEntry(const MimeType &t = MimeType(), int aLevel = Dangling); - MimeType type; - int level; // hierachy level -}; - -MimeMapEntry::MimeMapEntry(const MimeType &t, int aLevel) : - type(t), - level(aLevel) -{ -} - -/*! - \class Core::MimeDatabase - \brief The MimeDatabase class is a MIME type database to which the plugins - can add the MIME types they handle. - - The class is protected by a QMutex and can therefore be accessed by threads. - - A good testcase is to run it over \c {/usr/share/mime/<*>/<*>.xml} on Linux. - - When adding a \c{text/plain} to it, the MIME type will receive a magic matcher - that checks for text files that do not match the globs by heuristics. - - \section1 Design Considerations - - Storage requirements: - \list - \li Must be robust in case of incomplete hierarchies and dangling entries. - \li Plugins will not load and register their MIME types in order of - inheritance. - \li Multiple inheritance (several subClassesOf) can occur. - \li Provide quick lookup by name. - \li Provide quick lookup by file type. - \endlist - - This basically rules out a pointer-based tree, so the structure chosen is: - \list - \li An alias map \c {QString->QString} for mapping aliases to types. - \li A map \c {QString->MimeMapEntry} for the types (MimeMapEntry being a pair of - MimeType and (hierarchy) level. - \li A map \c {QString->QString} representing parent to child relations (enabling - recursing over children). - \li Using strings avoids dangling pointers. - \endlist - - The hierarchy level is used for mapping by file types. When \c findByFile() - is first called after \c addMimeType(), it recurses over the hierarchy and sets - the hierarchy level of the entries accordingly (0 toplevel, 1 first - order...). It then does several passes over the type map, checking the - globs for maxLevel, maxLevel-1....until it finds a match (the idea being - to check the most specific types first). Starting a recursion from the - leaves is not suitable since it will hit parent nodes several times. - - \sa Core::MimeType, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::BaseMimeTypeParser, Core::Internal::MimeTypeParser -*/ - -class MimeDatabasePrivate -{ - Q_DISABLE_COPY(MimeDatabasePrivate) - -public: - MimeDatabasePrivate(); - - bool addMimeTypes(const QString &fileName, QString *errorMessage); - bool addMimeTypes(QIODevice *device, QString *errorMessage); - bool addMimeType(MimeType mt); - - MimeType findByType(const QString &type) const; - MimeType findByFile(const QFileInfo &f) const; - MimeType findByData(const QByteArray &data) const; - - QStringList filterStrings() const; - - QStringList suffixes() const; - bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix); - - QList<MimeGlobPattern> globPatterns() const; - void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns); - - QList<QSharedPointer<IMagicMatcher> > magicMatchers() const; - void setMagicMatchers(const QString &typeOrAlias, - const QList<QSharedPointer<IMagicMatcher> > &matchers); - - QList<MimeType> mimeTypes() const; - - void syncUserModifiedMimeTypes(); - static QList<MimeType> readUserModifiedMimeTypes(); - static void writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes); - void clearUserModifiedMimeTypes(); - - static QList<MimeGlobPattern> toGlobPatterns(const QStringList &patterns, - int weight = MimeGlobPattern::MaxWeight); - static QStringList fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns); - - void debug(QTextStream &str) const; - - typedef QHash<QString, MimeMapEntry> TypeMimeTypeMap; - typedef QHash<QString, QString> AliasMap; - typedef QMultiHash<QString, QString> ParentChildrenMap; - - static const QString kModifiedMimeTypesFile; - static QString kModifiedMimeTypesPath; - - - bool addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage); - inline const QString &resolveAlias(const QString &name) const; - MimeType findByFile(const QFileInfo &f, unsigned *priority) const; - MimeType findByData(const QByteArray &data, unsigned *priority) const; - void determineLevels(); - void raiseLevelRecursion(MimeMapEntry &e, int level); - - TypeMimeTypeMap m_typeMimeTypeMap; - AliasMap m_aliasMap; - ParentChildrenMap m_parentChildrenMap; - int m_maxLevel; - QMutex m_mutex; -}; - -const QString MimeDatabasePrivate::kModifiedMimeTypesFile(QLatin1String("modifiedmimetypes.xml")); -QString MimeDatabasePrivate::kModifiedMimeTypesPath; - -MimeDatabasePrivate::MimeDatabasePrivate() : - m_maxLevel(-1) -{ - // Assign here to avoid non-local static data initialization issues. - kModifiedMimeTypesPath = ICore::userResourcePath() + QLatin1String("/mimetypes/"); -} - -/*! - \class Core::Internal::MimeTypeParser - \brief The MimeTypeParser class provides a MIME type parser. - - Populates Core::MimeDataBase - - \sa Core::MimeDatabase, Core::IMagicMatcher, Core::MagicRuleMatcher, Core::MagicRule, Core::MagicStringRule, Core::MagicByteRule, Core::GlobPattern - \sa Core::Internal::FileMatchContext, Core::Internal::BinaryMatcher, Core::Internal::HeuristicTextMagicMatcher - \sa Core::Internal::MimeTypeParser -*/ - -namespace Internal { - // Parser that builds MimeDB hierarchy by adding to MimeDatabasePrivate - class MimeTypeParser : public BaseMimeTypeParser { - public: - explicit MimeTypeParser(MimeDatabasePrivate &db) : m_db(db) {} - private: - virtual bool process(const MimeType &t, QString *) { m_db.addMimeType(t); return true; } - - MimeDatabasePrivate &m_db; - }; -} // namespace Internal - -bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, const QString &fileName, QString *errorMessage) -{ - Internal::MimeTypeParser parser(*this); - return parser.parse(device, fileName, errorMessage); -} - -bool MimeDatabasePrivate::addMimeTypes(const QString &fileName, QString *errorMessage) -{ - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly|QIODevice::Text)) { - *errorMessage = QString::fromLatin1("Cannot open %1: %2").arg(fileName, file.errorString()); - return false; - } - return addMimeTypes(&file, fileName, errorMessage); -} - -bool MimeDatabasePrivate::addMimeTypes(QIODevice *device, QString *errorMessage) -{ - return addMimeTypes(device, QLatin1String("<stream>"), errorMessage); -} - -bool MimeDatabasePrivate::addMimeType(MimeType mt) -{ - if (!mt) - return false; - - const QString type = mt.type(); - // Hack: Add a magic text matcher to "text/plain" and the fallback matcher to - // binary types "application/octet-stream" - if (type == QLatin1String(textTypeC)) { - mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::HeuristicTextMagicMatcher)); - } else { - if (type == QLatin1String(binaryTypeC)) - mt.addMagicMatcher(QSharedPointer<IMagicMatcher>(new Internal::BinaryMatcher)); - } - // insert the type. - m_typeMimeTypeMap.insert(type, MimeMapEntry(mt)); - // Register the children - // Aliases will be resolved later once all mime types are known. - const QStringList subClassesOf = mt.subClassesOf(); - if (!subClassesOf.empty()) { - const QStringList::const_iterator socend = subClassesOf.constEnd(); - for (QStringList::const_iterator soit = subClassesOf.constBegin(); soit != socend; ++soit) - m_parentChildrenMap.insert(*soit, type); - } - // register aliasses - const QStringList aliases = mt.aliases(); - if (!aliases.empty()) { - const QStringList::const_iterator cend = aliases.constEnd(); - for (QStringList::const_iterator it = aliases.constBegin(); it != cend; ++it) - m_aliasMap.insert(*it, type); - } - m_maxLevel = -1; // Mark as dirty - return true; -} - -const QString &MimeDatabasePrivate::resolveAlias(const QString &name) const -{ - const AliasMap::const_iterator aliasIt = m_aliasMap.constFind(name); - return aliasIt == m_aliasMap.constEnd() ? name : aliasIt.value(); -} - -void MimeDatabasePrivate::raiseLevelRecursion(MimeMapEntry &e, int level) -{ - if (e.level == Dangling || e.level < level) - e.level = level; - if (m_maxLevel < level) - m_maxLevel = level; - // At all events recurse over children since nodes might have been - // added. - QStringList childTypes = m_parentChildrenMap.values(e.type.type()); - foreach (const QString &alias, e.type.aliases()) - childTypes.append(m_parentChildrenMap.values(alias)); - if (childTypes.empty()) - return; - // look them up in the type->mime type map - const int nextLevel = level + 1; - const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end(); - const QStringList::const_iterator cend = childTypes.constEnd(); - for (QStringList::const_iterator it = childTypes.constBegin(); it != cend; ++it) { - const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*it)); - if (tm_it == tm_end) { - qWarning("%s: Inconsistent mime hierarchy detected, child %s of %s cannot be found.", - Q_FUNC_INFO, it->toUtf8().constData(), e.type.type().toUtf8().constData()); - } else { - raiseLevelRecursion(*tm_it, nextLevel); - } - } -} - -void MimeDatabasePrivate::determineLevels() -{ - // Loop over toplevels and recurse down their hierarchies. - // Determine top levels by subtracting the children from the parent - // set. Note that a toplevel at this point might have 'subclassesOf' - // set to some class that is not in the DB, so, checking for an empty - // 'subclassesOf' set is not sufficient to find the toplevels. - // First, take the parent->child entries whose parent exists and build - // sets of parents/children - QSet<QString> parentSet, childrenSet; - const ParentChildrenMap::const_iterator pcend = m_parentChildrenMap.constEnd(); - for (ParentChildrenMap::const_iterator it = m_parentChildrenMap.constBegin(); it != pcend; ++it) - if (m_typeMimeTypeMap.contains(it.key())) { - parentSet.insert(it.key()); - childrenSet.insert(it.value()); - } - const QSet<QString> topLevels = parentSet.subtract(childrenSet); - if (debugMimeDB) - qDebug() << Q_FUNC_INFO << "top levels" << topLevels; - const TypeMimeTypeMap::iterator tm_end = m_typeMimeTypeMap.end(); - const QSet<QString>::const_iterator tl_cend = topLevels.constEnd(); - for (QSet<QString>::const_iterator tl_it = topLevels.constBegin(); tl_it != tl_cend; ++tl_it) { - const TypeMimeTypeMap::iterator tm_it = m_typeMimeTypeMap.find(resolveAlias(*tl_it)); - if (tm_it == tm_end) { - qWarning("%s: Inconsistent mime hierarchy detected, top level element %s cannot be found.", - Q_FUNC_INFO, tl_it->toUtf8().constData()); - } else { - raiseLevelRecursion(tm_it.value(), 0); - } - } -} - -bool MimeDatabasePrivate::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix) -{ - TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias)); - if (tit != m_typeMimeTypeMap.end()) - return tit.value().type.setPreferredSuffix(suffix); - return false; -} - -// Returns a mime type or Null one if none found -MimeType MimeDatabasePrivate::findByType(const QString &typeOrAlias) const -{ - const TypeMimeTypeMap::const_iterator tit = m_typeMimeTypeMap.constFind(resolveAlias(typeOrAlias)); - if (tit != m_typeMimeTypeMap.constEnd()) - return tit.value().type; - return MimeType(); -} - -// Debugging wrapper around findByFile() -MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f) const -{ - unsigned priority = 0; - if (debugMimeDB) - qDebug() << '>' << Q_FUNC_INFO << f.absoluteFilePath(); - const MimeType rc = findByFile(f, &priority); - if (debugMimeDB) { - if (rc) - qDebug() << "<MimeDatabase::findByFile: match prio=" << priority << rc.type(); - else - qDebug() << "<MimeDatabase::findByFile: no match"; - } - return rc; -} - -// Returns a mime type or Null one if none found -MimeType MimeDatabasePrivate::findByFile(const QFileInfo &f, unsigned *priorityPtr) const -{ - // Is the hierarchy set up in case we find several matches? - if (m_maxLevel < 0) { - MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this); - db->determineLevels(); - } - - // First, glob patterns are evaluated. If there is a match with max weight, - // this one is selected and we are done. Otherwise, the file contents are - // evaluated and the match with the highest value (either a magic priority or - // a glob pattern weight) is selected. Matching starts from max level (most - // specific) in both cases, even when there is already a suffix matching candidate. - *priorityPtr = 0; - MimeType candidate; - Internal::FileMatchContext context(f); - - // Pass 1) Try to match on suffix - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (int level = m_maxLevel; level >= 0; level--) { - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) { - if (it.value().level == level) { - const unsigned suffixPriority = it.value().type.matchesFileBySuffix(context); - if (suffixPriority && suffixPriority > *priorityPtr) { - *priorityPtr = suffixPriority; - candidate = it.value().type; - if (suffixPriority >= MimeGlobPattern::MaxWeight) - return candidate; - } - } - } - } - - // Pass 2) Match on content - if (!f.isReadable()) - return candidate; - for (int level = m_maxLevel; level >= 0; level--) { - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) { - if (it.value().level == level) { - const unsigned contentPriority = it.value().type.matchesFileByContent(context); - if (contentPriority && contentPriority > *priorityPtr) { - *priorityPtr = contentPriority; - candidate = it.value().type; - } - } - } - } - - return candidate; -} - -// Debugging wrapper around findByData() -MimeType MimeDatabasePrivate::findByData(const QByteArray &data) const -{ - unsigned priority = 0; - if (debugMimeDB) - qDebug() << '>' << Q_FUNC_INFO << data.left(20).toHex(); - const MimeType rc = findByData(data, &priority); - if (debugMimeDB) { - if (rc) - qDebug() << "<MimeDatabase::findByData: match prio=" << priority << rc.type(); - else - qDebug() << "<MimeDatabase::findByData: no match"; - } - return rc; -} - -// Returns a mime type or Null one if none found -MimeType MimeDatabasePrivate::findByData(const QByteArray &data, unsigned *priorityPtr) const -{ - // Is the hierarchy set up in case we find several matches? - if (m_maxLevel < 0) { - MimeDatabasePrivate *db = const_cast<MimeDatabasePrivate *>(this); - db->determineLevels(); - } - - *priorityPtr = 0; - MimeType candidate; - - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (int level = m_maxLevel; level >= 0; level--) - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) - if (it.value().level == level) { - const unsigned contentPriority = it.value().type.matchesData(data); - if (contentPriority && contentPriority > *priorityPtr) { - *priorityPtr = contentPriority; - candidate = it.value().type; - } - } - - return candidate; -} - -// Return all known suffixes -QStringList MimeDatabasePrivate::suffixes() const -{ - QStringList rc; - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) - rc += it.value().type.suffixes(); - return rc; -} - -QStringList MimeDatabasePrivate::filterStrings() const -{ - QStringList rc; - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) { - const QString filterString = it.value().type.filterString(); - if (!filterString.isEmpty()) - rc += filterString; - } - return rc; -} - -QList<MimeGlobPattern> MimeDatabasePrivate::globPatterns() const -{ - QList<MimeGlobPattern> globPatterns; - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) - globPatterns.append(it.value().type.globPatterns()); - return globPatterns; -} - -void MimeDatabasePrivate::setGlobPatterns(const QString &typeOrAlias, - const QList<MimeGlobPattern> &globPatterns) -{ - TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias)); - if (tit != m_typeMimeTypeMap.end()) - tit.value().type.setGlobPatterns(globPatterns); -} - -QList<QSharedPointer<IMagicMatcher> > MimeDatabasePrivate::magicMatchers() const -{ - QList<QSharedPointer<IMagicMatcher> > magicMatchers; - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) - magicMatchers.append(it.value().type.magicMatchers()); - return magicMatchers; -} - -void MimeDatabasePrivate::setMagicMatchers(const QString &typeOrAlias, - const QList<QSharedPointer<IMagicMatcher> > &matchers) -{ - TypeMimeTypeMap::iterator tit = m_typeMimeTypeMap.find(resolveAlias(typeOrAlias)); - if (tit != m_typeMimeTypeMap.end()) - tit.value().type.setMagicMatchers(matchers); -} - -QList<MimeType> MimeDatabasePrivate::mimeTypes() const -{ - QList<MimeType> mimeTypes; - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) - mimeTypes.append(it.value().type); - return mimeTypes; -} - -void MimeDatabasePrivate::syncUserModifiedMimeTypes() -{ - QHash<QString, MimeType> userModified; - const QList<MimeType> &userMimeTypes = readUserModifiedMimeTypes(); - foreach (const MimeType &userMimeType, userMimeTypes) - userModified.insert(userMimeType.type(), userMimeType); - - TypeMimeTypeMap::iterator end = m_typeMimeTypeMap.end(); - QHash<QString, MimeType>::const_iterator userMimeEnd = userModified.end(); - for (TypeMimeTypeMap::iterator it = m_typeMimeTypeMap.begin(); it != end; ++it) { - QHash<QString, MimeType>::const_iterator userMimeIt = - userModified.find(it.value().type.type()); - if (userMimeIt != userMimeEnd) { - it.value().type.setGlobPatterns(userMimeIt.value().globPatterns()); - it.value().type.setMagicRuleMatchers(userMimeIt.value().magicRuleMatchers()); - } - } -} - -QList<MimeType> MimeDatabasePrivate::readUserModifiedMimeTypes() -{ - typedef MagicRuleMatcher::MagicRuleList MagicRuleList; - typedef MagicRuleMatcher::MagicRuleSharedPointer MagicRuleSharedPointer; - - QList<MimeType> mimeTypes; - QFile file(kModifiedMimeTypesPath + kModifiedMimeTypesFile); - if (file.open(QFile::ReadOnly)) { - MimeType mimeType; - QHash<int, MagicRuleList> rules; - QXmlStreamReader reader(&file); - QXmlStreamAttributes atts; - const QString mimeTypeAttribute = QLatin1String(mimeTypeAttributeC); - const QString patternAttribute = QLatin1String(patternAttributeC); - const QString matchValueAttribute = QLatin1String(matchValueAttributeC); - const QString matchTypeAttribute = QLatin1String(matchTypeAttributeC); - const QString matchOffsetAttribute = QLatin1String(matchOffsetAttributeC); - const QString priorityAttribute = QLatin1String(priorityAttributeC); - while (!reader.atEnd()) { - switch (reader.readNext()) { - case QXmlStreamReader::StartElement: - atts = reader.attributes(); - if (reader.name() == QLatin1String(mimeTypeTagC)) { - mimeType.setType(atts.value(mimeTypeAttribute).toString()); - const QString &patterns = atts.value(patternAttribute).toString(); - mimeType.setGlobPatterns(toGlobPatterns(patterns.split(QLatin1Char(';')))); - } else if (reader.name() == QLatin1String(matchTagC)) { - const QString &value = atts.value(matchValueAttribute).toString(); - const QStringRef type = atts.value(matchTypeAttribute); - const QString &offset = atts.value(matchOffsetAttribute).toString(); - QPair<int, int> range = MagicRule::fromOffset(offset); - const int priority = atts.value(priorityAttribute).toString().toInt(); - - MagicRule *magicRule; - if (type == MagicStringRule::kMatchType) - magicRule = new MagicStringRule(value, range.first, range.second); - else - magicRule = new MagicByteRule(value, range.first, range.second); - rules[priority].append(MagicRuleSharedPointer(magicRule)); - } - break; - case QXmlStreamReader::EndElement: - if (reader.name() == QLatin1String(mimeTypeTagC)) { - mimeType.setMagicRuleMatchers(MagicRuleMatcher::createMatchers(rules)); - mimeTypes.append(mimeType); - mimeType.clear(); - rules.clear(); - } - break; - default: - break; - } - } - if (reader.hasError()) - qWarning() << kModifiedMimeTypesFile << reader.errorString() << reader.lineNumber() - << reader.columnNumber(); - file.close(); - } - return mimeTypes; -} - -void MimeDatabasePrivate::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes) -{ - // Keep mime types modified which are already on file, unless they are part of the current set. - QSet<QString> currentMimeTypes; - foreach (const MimeType &mimeType, mimeTypes) - currentMimeTypes.insert(mimeType.type()); - const QList<MimeType> &inFileMimeTypes = readUserModifiedMimeTypes(); - QList<MimeType> allModifiedMimeTypes = mimeTypes; - foreach (const MimeType &mimeType, inFileMimeTypes) - if (!currentMimeTypes.contains(mimeType.type())) - allModifiedMimeTypes.append(mimeType); - - if (QFile::exists(kModifiedMimeTypesPath) || QDir().mkpath(kModifiedMimeTypesPath)) { - QFile file(kModifiedMimeTypesPath + kModifiedMimeTypesFile); - if (file.open(QFile::WriteOnly | QFile::Truncate)) { - // Notice this file only represents user modifications. It is writen in a - // convienient way for synchronization, which is similar to but not exactly the - // same format we use for the embedded mime type files. - QXmlStreamWriter writer(&file); - writer.setAutoFormatting(true); - writer.writeStartDocument(); - writer.writeStartElement(QLatin1String(mimeInfoTagC)); - const QString mimeTypeTag = QLatin1String(mimeTypeTagC); - const QString matchTag = QLatin1String(matchTagC); - const QString mimeTypeAttribute = QLatin1String(mimeTypeAttributeC); - const QString patternAttribute = QLatin1String(patternAttributeC); - const QString matchValueAttribute = QLatin1String(matchValueAttributeC); - const QString matchTypeAttribute = QLatin1String(matchTypeAttributeC); - const QString matchOffsetAttribute = QLatin1String(matchOffsetAttributeC); - const QString priorityAttribute = QLatin1String(priorityAttributeC); - - foreach (const MimeType &mimeType, allModifiedMimeTypes) { - writer.writeStartElement(mimeTypeTag); - writer.writeAttribute(mimeTypeAttribute, mimeType.type()); - writer.writeAttribute(patternAttribute, - fromGlobPatterns(mimeType.globPatterns()).join(QLatin1Char(';'))); - const QList<QSharedPointer<IMagicMatcher> > &matchers = mimeType.magicMatchers(); - foreach (const QSharedPointer<IMagicMatcher> &matcher, matchers) { - // Only care about rule-based matchers. - if (MagicRuleMatcher *ruleMatcher = - dynamic_cast<MagicRuleMatcher *>(matcher.data())) { - const MagicRuleMatcher::MagicRuleList &rules = ruleMatcher->magicRules(); - foreach (const MagicRuleMatcher::MagicRuleSharedPointer &rule, rules) { - writer.writeStartElement(matchTag); - writer.writeAttribute(matchValueAttribute, rule->matchValue()); - writer.writeAttribute(matchTypeAttribute, rule->matchType()); - writer.writeAttribute(matchOffsetAttribute, - MagicRule::toOffset( - qMakePair(rule->startPos(), rule->endPos()))); - writer.writeAttribute(priorityAttribute, - QString::number(ruleMatcher->priority())); - writer.writeEndElement(); - } - } - } - writer.writeEndElement(); - } - writer.writeEndElement(); - writer.writeEndDocument(); - file.close(); - } - } -} - -void MimeDatabasePrivate::clearUserModifiedMimeTypes() -{ - // This removes the user's file. However, the operation will actually take place the next time - // Creator starts, since we currently don't support removing stuff from the mime database. - QFile::remove(kModifiedMimeTypesPath + kModifiedMimeTypesFile); -} - -QList<MimeGlobPattern> MimeDatabasePrivate::toGlobPatterns(const QStringList &patterns, int weight) -{ - QList<MimeGlobPattern> globPatterns; - foreach (const QString &pattern, patterns) - globPatterns.append(MimeGlobPattern(pattern, weight)); - return globPatterns; -} - -QStringList MimeDatabasePrivate::fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns) -{ - QStringList patterns; - foreach (const MimeGlobPattern &globPattern, globPatterns) - patterns.append(globPattern.pattern()); - return patterns; -} - -void MimeDatabasePrivate::debug(QTextStream &str) const -{ - str << ">MimeDatabase\n"; - const TypeMimeTypeMap::const_iterator cend = m_typeMimeTypeMap.constEnd(); - for (TypeMimeTypeMap::const_iterator it = m_typeMimeTypeMap.constBegin(); it != cend; ++it) { - str << "Entry level " << it.value().level << '\n'; - it.value().type.m_d->debug(str); - } - str << "<MimeDatabase\n"; -} - -static MimeDatabasePrivate *d; - -MimeDatabase::MimeDatabase() -{ - d = new MimeDatabasePrivate; -} - -MimeDatabase::~MimeDatabase() -{ - delete d; -} - -MimeType MimeDatabase::findByType(const QString &typeOrAlias) -{ - d->m_mutex.lock(); - const MimeType rc = d->findByType(typeOrAlias); - d->m_mutex.unlock(); - return rc; -} - -MimeType MimeDatabase::findByFileUnlocked(const QFileInfo &f) -{ - return d->findByFile(f); -} - -MimeType MimeDatabase::findByFile(const QFileInfo &f) -{ - d->m_mutex.lock(); - const MimeType rc = findByFileUnlocked(f); - d->m_mutex.unlock(); - return rc; -} - -MimeType MimeDatabase::findByData(const QByteArray &data) -{ - d->m_mutex.lock(); - const MimeType rc = d->findByData(data); - d->m_mutex.unlock(); - return rc; -} - -bool MimeDatabase::addMimeType(const MimeType &mt) -{ - d->m_mutex.lock(); - const bool rc = d->addMimeType(mt); - d->m_mutex.unlock(); - return rc; -} - -bool MimeDatabase::addMimeTypes(const QString &fileName, QString *errorMessage) -{ - d->m_mutex.lock(); - const bool rc = d->addMimeTypes(fileName, errorMessage); - d->m_mutex.unlock(); - return rc; -} - -bool MimeDatabase::addMimeTypes(QIODevice *device, QString *errorMessage) -{ - d->m_mutex.lock(); - const bool rc = d->addMimeTypes(device, errorMessage); - d->m_mutex.unlock(); - return rc; -} - -QStringList MimeDatabase::suffixes() -{ - d->m_mutex.lock(); - const QStringList rc = d->suffixes(); - d->m_mutex.unlock(); - return rc; -} - -QStringList MimeDatabase::filterStrings() -{ - d->m_mutex.lock(); - const QStringList rc = d->filterStrings(); - d->m_mutex.unlock(); - return rc; -} -QString MimeDatabase::allFiltersString(QString *allFilesFilter) -{ - if (allFilesFilter) - allFilesFilter->clear(); - - // Compile list of filter strings, sort, and remove duplicates (different mime types might - // generate the same filter). - QStringList filters = filterStrings(); - if (filters.empty()) - return QString(); - filters.sort(); - filters.erase(std::unique(filters.begin(), filters.end()), filters.end()); - - static const QString allFiles = - QCoreApplication::translate("Core", Constants::ALL_FILES_FILTER); - if (allFilesFilter) - *allFilesFilter = allFiles; - - // Prepend all files filter (instead of appending to work around a bug in Qt/Mac). - filters.prepend(allFiles); - - return filters.join(QLatin1String(";;")); -} - -QList<MimeGlobPattern> MimeDatabase::globPatterns() -{ - d->m_mutex.lock(); - const QList<MimeGlobPattern> rc = d->globPatterns(); - d->m_mutex.unlock(); - return rc; -} - -void MimeDatabase::setGlobPatterns(const QString &typeOrAlias, - const QList<MimeGlobPattern> &globPatterns) -{ - d->m_mutex.lock(); - d->setGlobPatterns(typeOrAlias, globPatterns); - d->m_mutex.unlock(); -} - -MimeDatabase::IMagicMatcherList MimeDatabase::magicMatchers() -{ - d->m_mutex.lock(); - const IMagicMatcherList rc = d->magicMatchers(); - d->m_mutex.unlock(); - return rc; -} - -void MimeDatabase::setMagicMatchers(const QString &typeOrAlias, - const IMagicMatcherList &matchers) -{ - d->m_mutex.lock(); - d->setMagicMatchers(typeOrAlias, matchers); - d->m_mutex.unlock(); -} - -QList<MimeType> MimeDatabase::mimeTypes() -{ - d->m_mutex.lock(); - const QList<MimeType> &mimeTypes = d->mimeTypes(); - d->m_mutex.unlock(); - return mimeTypes; -} - -void MimeDatabase::syncUserModifiedMimeTypes() -{ - d->m_mutex.lock(); - d->syncUserModifiedMimeTypes(); - d->m_mutex.unlock(); -} - -void MimeDatabase::clearUserModifiedMimeTypes() -{ - d->m_mutex.lock(); - d->clearUserModifiedMimeTypes(); - d->m_mutex.unlock(); -} - -QList<MimeType> MimeDatabase::readUserModifiedMimeTypes() -{ - return MimeDatabasePrivate::readUserModifiedMimeTypes(); -} - -void MimeDatabase::writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes) -{ - MimeDatabasePrivate::writeUserModifiedMimeTypes(mimeTypes); -} - -QString MimeDatabase::preferredSuffixByType(const QString &type) -{ - if (const MimeType mt = findByType(type)) - return mt.preferredSuffix(); // already does Mutex locking - return QString(); -} - -QString MimeDatabase::preferredSuffixByFile(const QFileInfo &f) -{ - if (const MimeType mt = findByFile(f)) - return mt.preferredSuffix(); // already does Mutex locking - return QString(); -} - -bool MimeDatabase::setPreferredSuffix(const QString &typeOrAlias, const QString &suffix) -{ - d->m_mutex.lock(); - const bool rc = d->setPreferredSuffix(typeOrAlias, suffix); - d->m_mutex.unlock(); - return rc; -} - -QList<MimeGlobPattern> MimeDatabase::toGlobPatterns(const QStringList &patterns, int weight) -{ - return MimeDatabasePrivate::toGlobPatterns(patterns, weight); -} - -QStringList MimeDatabase::fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns) -{ - return MimeDatabasePrivate::fromGlobPatterns(globPatterns); -} - -//QDebug operator<<(QDebug d, const MimeDatabase &mt) -//{ -// QString s; -// { -// QTextStream str(&s); -// d->debug(str); -// } -// db << s; -// return db; -//} - -} // namespace Core diff --git a/src/plugins/coreplugin/mimedatabase.h b/src/plugins/coreplugin/mimedatabase.h deleted file mode 100644 index 263f5507cc..0000000000 --- a/src/plugins/coreplugin/mimedatabase.h +++ /dev/null @@ -1,318 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2015 The Qt Company Ltd. -** Contact: http://www.qt.io/licensing -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms and -** conditions see http://www.qt.io/terms-conditions. For further information -** use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -****************************************************************************/ - -#ifndef MIMEDATABASE_H -#define MIMEDATABASE_H - -#include <coreplugin/core_global.h> -#include <QStringList> -#include <QSharedDataPointer> -#include <QSharedPointer> -#include <QByteArray> -#include <QMutex> -#include <QFileInfo> -#include <QPair> - -QT_BEGIN_NAMESPACE -class QIODevice; -class QDebug; -QT_END_NAMESPACE - -namespace Core { - -class MimeTypeData; -class MimeDatabasePrivate; - -namespace Internal { - class BaseMimeTypeParser; - class FileMatchContext; - class MainWindow; -} - -class CORE_EXPORT IMagicMatcher -{ - Q_DISABLE_COPY(IMagicMatcher) - -protected: - IMagicMatcher() {} - -public: - typedef QSharedPointer<IMagicMatcher> IMagicMatcherSharedPointer; - typedef QList<IMagicMatcherSharedPointer> IMagicMatcherList; - - // Check for a match on contents of a file - virtual bool matches(const QByteArray &data) const = 0; - // Return a priority value from 1..100 - virtual int priority() const = 0; - virtual ~IMagicMatcher() {} -}; - -class CORE_EXPORT MagicRule -{ - Q_DISABLE_COPY(MagicRule) -public: - MagicRule(int startPos, int endPos); - virtual ~MagicRule(); - - virtual QString matchType() const = 0; - virtual QString matchValue() const = 0; - virtual bool matches(const QByteArray &data) const = 0; - - int startPos() const; - int endPos() const; - - static QString toOffset(const QPair<int, int> &startEnd); - static QPair<int, int> fromOffset(const QString &offset); - -private: - static const QChar kColon; - - const int m_startPos; - const int m_endPos; -}; - -class CORE_EXPORT MagicStringRule : public MagicRule -{ -public: - MagicStringRule(const QString &s, int startPos, int endPos); - virtual ~MagicStringRule(); - - virtual QString matchType() const; - virtual QString matchValue() const; - virtual bool matches(const QByteArray &data) const; - - static const QString kMatchType; - -private: - const QByteArray m_pattern; -}; - -class CORE_EXPORT MagicByteRule : public MagicRule -{ -public: - MagicByteRule(const QString &s, int startPos, int endPos); - virtual ~MagicByteRule(); - - virtual QString matchType() const; - virtual QString matchValue() const; - virtual bool matches(const QByteArray &data) const; - - static bool validateByteSequence(const QString &sequence, QList<int> *bytes = 0); - - static const QString kMatchType; - -private: - int m_bytesSize; - QList<int> m_bytes; -}; - -class CORE_EXPORT MagicRuleMatcher : public IMagicMatcher -{ - Q_DISABLE_COPY(MagicRuleMatcher) -public: - typedef QSharedPointer<MagicRule> MagicRuleSharedPointer; - typedef QList<MagicRuleSharedPointer> MagicRuleList; - - MagicRuleMatcher(); - - void add(const MagicRuleSharedPointer &rule); - void add(const MagicRuleList &ruleList); - MagicRuleList magicRules() const; - - virtual bool matches(const QByteArray &data) const; - - virtual int priority() const; - void setPriority(int p); - - // Create a list of MagicRuleMatchers from a hash of rules indexed by priorities. - static IMagicMatcher::IMagicMatcherList createMatchers(const QHash<int, MagicRuleList> &); - -private: - MagicRuleList m_list; - int m_priority; -}; - -class CORE_EXPORT MimeGlobPattern -{ -public: - static const unsigned MaxWeight = 100; - static const unsigned MinWeight = 1; - - explicit MimeGlobPattern(const QString &pattern, unsigned weight = MaxWeight); - ~MimeGlobPattern(); - - bool matches(const QString &fileName) const; - unsigned weight() const { return m_weight; } - QString pattern() const { return m_pattern; } - -private: - enum { Suffix, Exact, Glob } m_type; - QString m_pattern; - QRegExp m_regexp; // Will be used in \c Glob case only. - unsigned m_weight; -}; - - -class CORE_EXPORT MimeType -{ -public: - typedef IMagicMatcher::IMagicMatcherList IMagicMatcherList; - typedef IMagicMatcher::IMagicMatcherSharedPointer IMagicMatcherSharedPointer; - - MimeType(); - MimeType(const MimeType&); - MimeType &operator=(const MimeType&); - ~MimeType(); - - void clear(); - bool isNull() const; - operator bool() const; - - bool isTopLevel() const; - - QString type() const; - void setType(const QString &type); - - QStringList aliases() const; - void setAliases(const QStringList &); - - QString comment() const; - void setComment(const QString &comment); - - QString localeComment(const QString &locale = QString() /* en, de...*/) const; - void setLocaleComment(const QString &locale, const QString &comment); - - QList<MimeGlobPattern> globPatterns() const; - void setGlobPatterns(const QList<MimeGlobPattern> &); - - QStringList subClassesOf() const; - void setSubClassesOf(const QStringList &); - - // Extension over standard mime data - QStringList suffixes() const; - QString preferredSuffix() const; - bool setPreferredSuffix(const QString&); - - // Check for type or one of the aliases - bool matchesType(const QString &type) const; - - // Check glob patterns weights and magic priorities so the highest - // value is returned. A 0 (zero) indicates no match. - unsigned matchesFile(const QFileInfo &file) const; - - // Return a filter string usable for a file dialog - QString filterString() const; - - void addMagicMatcher(const IMagicMatcherSharedPointer &matcher); - - const IMagicMatcherList &magicMatchers() const; - void setMagicMatchers(const IMagicMatcherList &matchers); - - // Convenience for rule-base matchers. - IMagicMatcherList magicRuleMatchers() const; - void setMagicRuleMatchers(const IMagicMatcherList &matchers); - - friend QDebug operator<<(QDebug d, const MimeType &mt); - - static QString formatFilterString(const QString &description, - const QList<MimeGlobPattern> &globs); - -private: - explicit MimeType(const MimeTypeData &d); - unsigned matchesFileBySuffix(Internal::FileMatchContext &c) const; - unsigned matchesFileByContent(Internal::FileMatchContext &c) const; - unsigned matchesData(const QByteArray &data) const; - - friend class Internal::BaseMimeTypeParser; - friend class MimeDatabasePrivate; - QSharedDataPointer<MimeTypeData> m_d; -}; - -class CORE_EXPORT MimeDatabase -{ - Q_DISABLE_COPY(MimeDatabase) -public: - typedef IMagicMatcher::IMagicMatcherList IMagicMatcherList; - typedef IMagicMatcher::IMagicMatcherSharedPointer IMagicMatcherSharedPointer; - - static bool addMimeTypes(const QString &fileName, QString *errorMessage); - static bool addMimeTypes(QIODevice *device, QString *errorMessage); - static bool addMimeType(const MimeType &mt); - - // Returns a mime type or Null one if none found - static MimeType findByType(const QString &type); - - // Returns a mime type or Null one if none found - static MimeType findByFile(const QFileInfo &f); - - // Returns a mime type or Null one if none found - static MimeType findByData(const QByteArray &data); - - // Return all known suffixes - static QStringList suffixes(); - static bool setPreferredSuffix(const QString &typeOrAlias, const QString &suffix); - static QString preferredSuffixByType(const QString &type); - static QString preferredSuffixByFile(const QFileInfo &f); - - static QStringList filterStrings(); - // Return a string with all the possible file filters, for use with file dialogs - static QString allFiltersString(QString *allFilesFilter = 0); - - static QList<MimeGlobPattern> globPatterns(); - static void setGlobPatterns(const QString &typeOrAlias, const QList<MimeGlobPattern> &globPatterns); - - static IMagicMatcherList magicMatchers(); - static void setMagicMatchers(const QString &typeOrAlias, const IMagicMatcherList &matchers); - - static QList<MimeType> mimeTypes(); - - // The mime types from the functions bellow are considered only in regard to - // their glob patterns and rule-based magic matchers. - static void syncUserModifiedMimeTypes(); - static QList<MimeType> readUserModifiedMimeTypes(); - static void writeUserModifiedMimeTypes(const QList<MimeType> &mimeTypes); - static void clearUserModifiedMimeTypes(); - - static QList<MimeGlobPattern> toGlobPatterns(const QStringList &patterns, - int weight = MimeGlobPattern::MaxWeight); - static QStringList fromGlobPatterns(const QList<MimeGlobPattern> &globPatterns); - -private: - MimeDatabase(); - ~MimeDatabase(); - - static MimeType findByFileUnlocked(const QFileInfo &f); - - friend class Core::Internal::MainWindow; -}; - -} // namespace Core - -#endif // MIMEDATABASE_H diff --git a/src/plugins/coreplugin/mimetypemagicdialog.cpp b/src/plugins/coreplugin/mimetypemagicdialog.cpp index a265fe5495..ead53b0164 100644 --- a/src/plugins/coreplugin/mimetypemagicdialog.cpp +++ b/src/plugins/coreplugin/mimetypemagicdialog.cpp @@ -29,7 +29,6 @@ ****************************************************************************/ #include "mimetypemagicdialog.h" -#include "mimedatabase.h" #include <utils/headerviewstretcher.h> @@ -59,37 +58,37 @@ void MimeTypeMagicDialog::applyRecommended(bool checked) void MimeTypeMagicDialog::validateAccept() { - if (ui.valueLineEdit->text().isEmpty() - || (ui.byteRadioButton->isChecked() - && !MagicByteRule::validateByteSequence(ui.valueLineEdit->text()))) { - QMessageBox::critical(0, tr("Error"), tr("Not a valid byte pattern.")); - return; - } +// if (ui.valueLineEdit->text().isEmpty() +// || (ui.byteRadioButton->isChecked() +// && !MagicByteRule::validateByteSequence(ui.valueLineEdit->text()))) { +// QMessageBox::critical(0, tr("Error"), tr("Not a valid byte pattern.")); +// return; +// } accept(); } void MimeTypeMagicDialog::setMagicData(const MagicData &data) { - ui.valueLineEdit->setText(data.m_value); - if (data.m_type == MagicStringRule::kMatchType) - ui.stringRadioButton->setChecked(true); - else - ui.byteRadioButton->setChecked(true); - ui.startRangeSpinBox->setValue(data.m_start); - ui.endRangeSpinBox->setValue(data.m_end); - ui.prioritySpinBox->setValue(data.m_priority); +// ui.valueLineEdit->setText(data.m_value); +// if (data.m_type == MagicStringRule::kMatchType) +// ui.stringRadioButton->setChecked(true); +// else +// ui.byteRadioButton->setChecked(true); +// ui.startRangeSpinBox->setValue(data.m_start); +// ui.endRangeSpinBox->setValue(data.m_end); +// ui.prioritySpinBox->setValue(data.m_priority); } MagicData MimeTypeMagicDialog::magicData() const { MagicData data; - data.m_value = ui.valueLineEdit->text(); - if (ui.stringRadioButton->isChecked()) - data.m_type = MagicStringRule::kMatchType; - else - data.m_type = MagicByteRule::kMatchType; - data.m_start = ui.startRangeSpinBox->value(); - data.m_end = ui.endRangeSpinBox->value(); - data.m_priority = ui.prioritySpinBox->value(); +// data.m_value = ui.valueLineEdit->text(); +// if (ui.stringRadioButton->isChecked()) +// data.m_type = MagicStringRule::kMatchType; +// else +// data.m_type = MagicByteRule::kMatchType; +// data.m_start = ui.startRangeSpinBox->value(); +// data.m_end = ui.endRangeSpinBox->value(); +// data.m_priority = ui.prioritySpinBox->value(); return data; } diff --git a/src/plugins/coreplugin/mimetypesettings.cpp b/src/plugins/coreplugin/mimetypesettings.cpp index df6b0871fc..e49a372b52 100644 --- a/src/plugins/coreplugin/mimetypesettings.cpp +++ b/src/plugins/coreplugin/mimetypesettings.cpp @@ -30,7 +30,6 @@ #include "coreconstants.h" #include "icore.h" -#include "mimedatabase.h" #include "mimetypemagicdialog.h" #include "mimetypesettings.h" #include "ui_mimetypesettingspage.h" @@ -39,6 +38,7 @@ #include <coreplugin/editormanager/iexternaleditor.h> #include <utils/algorithm.h> #include <utils/headerviewstretcher.h> +#include <utils/mimetypes/mimedatabase.h> #include <QAbstractTableModel> #include <QCoreApplication> @@ -70,10 +70,10 @@ public: virtual QVariant data(const QModelIndex &modelIndex, int role = Qt::DisplayRole) const; void load(); - void validatePatterns(QStringList *candidates, const MimeType &mimeType) const; + void validatePatterns(QStringList *candidates) const; void updateKnownPatterns(const QStringList &oldPatterns, const QStringList &newPatterns); - QList<MimeType> m_mimeTypes; + QList<Utils::MimeType> m_mimeTypes; QSet<QString> m_knownPatterns; QHash<QString, QString> m_handlersByMimeType; }; @@ -106,7 +106,7 @@ QVariant MimeTypeSettingsModel::data(const QModelIndex &modelIndex, int role) co const int column = modelIndex.column(); if (role == Qt::DisplayRole) { - const QString &type = m_mimeTypes.at(modelIndex.row()).type(); + const QString &type = m_mimeTypes.at(modelIndex.row()).name(); if (column == 0) return type; else @@ -117,14 +117,14 @@ QVariant MimeTypeSettingsModel::data(const QModelIndex &modelIndex, int role) co void MimeTypeSettingsModel::load() { - m_mimeTypes = MimeDatabase::mimeTypes(); - Utils::sort(m_mimeTypes, [](const MimeType &a, const MimeType &b) { - return a.type().compare(b.type(), Qt::CaseInsensitive) < 0; + Utils::MimeDatabase mdb; + m_mimeTypes = mdb.allMimeTypes(); + Utils::sort(m_mimeTypes, [](const Utils::MimeType &a, const Utils::MimeType &b) { + return a.name().compare(b.name(), Qt::CaseInsensitive) < 0; }); - m_knownPatterns = QSet<QString>::fromList( - MimeDatabase::fromGlobPatterns(MimeDatabase::globPatterns())); + m_knownPatterns = QSet<QString>::fromList(Utils::MimeDatabase::allGlobPatterns()); - foreach (const MimeType &mimeType, m_mimeTypes) { + foreach (const Utils::MimeType &mimeType, m_mimeTypes) { QString value; const QList<IEditorFactory *> factories = EditorManager::editorFactories(mimeType); @@ -138,15 +138,14 @@ void MimeTypeSettingsModel::load() else value = tr("Undefined"); } - m_handlersByMimeType.insert(mimeType.type(), value); + m_handlersByMimeType.insert(mimeType.name(), value); } } -void MimeTypeSettingsModel::validatePatterns(QStringList *candidates, - const MimeType &mimeType) const +void MimeTypeSettingsModel::validatePatterns(QStringList *candidates) const { QSet<QString> oldPatterns = - QSet<QString>::fromList(MimeDatabase::fromGlobPatterns(mimeType.globPatterns())); + QSet<QString>::fromList(Utils::MimeDatabase::allGlobPatterns()); QStringList duplicates; QStringList::iterator it = candidates->begin(); @@ -209,9 +208,10 @@ public: void clearSyncData(); void markAsModified(int index); - void addMagicHeaderRow(const MagicData &data); - MagicData getMagicHeaderRowData(const int row) const; - void editMagicHeaderRowData(const int row, const MagicData &data); + // TODO +// void addMagicHeaderRow(const MagicData &data); +// MagicData getMagicHeaderRowData(const int row) const; +// void editMagicHeaderRowData(const int row, const MagicData &data); void updateMimeDatabase(); void resetState(); @@ -219,9 +219,10 @@ public: public slots: void syncData(const QModelIndex ¤t, const QModelIndex &previous); void handlePatternEdited(); - void addMagicHeader(); - void removeMagicHeader(); - void editMagicHeader(); + // TODO +// void addMagicHeader(); +// void removeMagicHeader(); +// void editMagicHeader(); void resetMimeTypes(); void updateMagicHeaderButtons(); @@ -278,9 +279,10 @@ void MimeTypeSettingsPrivate::configureUi(QWidget *w) SLOT(syncData(QModelIndex,QModelIndex))); connect(m_ui.patternsLineEdit, SIGNAL(textEdited(QString)), this, SLOT(handlePatternEdited())); - connect(m_ui.addMagicButton, SIGNAL(clicked()), this, SLOT(addMagicHeader())); - connect(m_ui.removeMagicButton, SIGNAL(clicked()), this, SLOT(removeMagicHeader())); - connect(m_ui.editMagicButton, SIGNAL(clicked()), this, SLOT(editMagicHeader())); + // TODO +// connect(m_ui.addMagicButton, SIGNAL(clicked()), this, SLOT(addMagicHeader())); +// connect(m_ui.removeMagicButton, SIGNAL(clicked()), this, SLOT(removeMagicHeader())); +// connect(m_ui.editMagicButton, SIGNAL(clicked()), this, SLOT(editMagicHeader())); connect(m_ui.resetButton, SIGNAL(clicked()), this, SLOT(resetMimeTypes())); connect(m_ui.magicHeadersTreeWidget, SIGNAL(itemSelectionChanged()), @@ -332,35 +334,37 @@ void MimeTypeSettingsPrivate::markAsModified(int index) void MimeTypeSettingsPrivate::syncMimePattern() { - MimeType &mimeType = m_model->m_mimeTypes[m_mimeForPatternSync]; - QStringList patterns = m_ui.patternsLineEdit->text().split(kSemiColon); - patterns.removeDuplicates(); - m_model->validatePatterns(&patterns, mimeType); - m_model->updateKnownPatterns(MimeDatabase::fromGlobPatterns(mimeType.globPatterns()), patterns); - mimeType.setGlobPatterns(MimeDatabase::toGlobPatterns(patterns)); + // TODO +// MimeType &mimeType = m_model->m_mimeTypes[m_mimeForPatternSync]; +// QStringList patterns = m_ui.patternsLineEdit->text().split(kSemiColon); +// patterns.removeDuplicates(); +// m_model->validatePatterns(&patterns); +// m_model->updateKnownPatterns(MimeDatabase::fromGlobPatterns(mimeType.globPatterns()), patterns); +// mimeType.setGlobPatterns(MimeDatabase::toGlobPatterns(patterns)); } void MimeTypeSettingsPrivate::syncMimeMagic() { - typedef MagicRuleMatcher::MagicRuleList MagicRuleList; - typedef MagicRuleMatcher::MagicRuleSharedPointer MagicRuleSharedPointer; - - // Gather the magic rules. - QHash<int, MagicRuleList> rulesByPriority; - for (int row = 0; row < m_ui.magicHeadersTreeWidget->topLevelItemCount(); ++row) { - const MagicData &data = getMagicHeaderRowData(row); - // @TODO: Validate magic rule? - MagicRule *magicRule; - if (data.m_type == MagicStringRule::kMatchType) - magicRule = new MagicStringRule(data.m_value, data.m_start, data.m_end); - else - magicRule = new MagicByteRule(data.m_value, data.m_start, data.m_end); - rulesByPriority[data.m_priority].append(MagicRuleSharedPointer(magicRule)); - } + // TODO +// typedef MagicRuleMatcher::MagicRuleList MagicRuleList; +// typedef MagicRuleMatcher::MagicRuleSharedPointer MagicRuleSharedPointer; - const QList<QSharedPointer<IMagicMatcher> > &matchers = - MagicRuleMatcher::createMatchers(rulesByPriority); - m_model->m_mimeTypes[m_mimeForMagicSync].setMagicRuleMatchers(matchers); +// // Gather the magic rules. +// QHash<int, MagicRuleList> rulesByPriority; +// for (int row = 0; row < m_ui.magicHeadersTreeWidget->topLevelItemCount(); ++row) { +// const MagicData &data = getMagicHeaderRowData(row); +// // @TODO: Validate magic rule? +// MagicRule *magicRule; +// if (data.m_type == MagicStringRule::kMatchType) +// magicRule = new MagicStringRule(data.m_value, data.m_start, data.m_end); +// else +// magicRule = new MagicByteRule(data.m_value, data.m_start, data.m_end); +// rulesByPriority[data.m_priority].append(MagicRuleSharedPointer(magicRule)); +// } + +// const QList<QSharedPointer<IMagicMatcher> > &matchers = +// MagicRuleMatcher::createMatchers(rulesByPriority); +// m_model->m_mimeTypes[m_mimeForMagicSync].setMagicRuleMatchers(matchers); } void MimeTypeSettingsPrivate::clearSyncData() @@ -384,27 +388,25 @@ void MimeTypeSettingsPrivate::syncData(const QModelIndex ¤t, } if (current.isValid()) { - const MimeType ¤tMimeType = + const Utils::MimeType ¤tMimeType = m_model->m_mimeTypes.at(m_filterModel->mapToSource(current).row()); - QStringList formatedPatterns; - foreach (const MimeGlobPattern &pattern, currentMimeType.globPatterns()) - formatedPatterns.append(pattern.pattern()); - m_ui.patternsLineEdit->setText(formatedPatterns.join(kSemiColon)); - - // Consider only rule-based matchers. - const QList<QSharedPointer<IMagicMatcher> > &matchers = currentMimeType.magicRuleMatchers(); - foreach (const QSharedPointer<IMagicMatcher> &matcher, matchers) { - MagicRuleMatcher *ruleMatcher = static_cast<MagicRuleMatcher *>(matcher.data()); - const int priority = ruleMatcher->priority(); - const MagicRuleMatcher::MagicRuleList &rules = ruleMatcher->magicRules(); - foreach (const MagicRuleMatcher::MagicRuleSharedPointer &rule, rules) - addMagicHeaderRow(MagicData(rule->matchValue(), - rule->matchType(), - rule->startPos(), - rule->endPos(), - priority)); - } + m_ui.patternsLineEdit->setText(currentMimeType.globPatterns().join(kSemiColon)); + + // TODO +// // Consider only rule-based matchers. +// const QList<QSharedPointer<IMagicMatcher> > &matchers = currentMimeType.magicRuleMatchers(); +// foreach (const QSharedPointer<IMagicMatcher> &matcher, matchers) { +// MagicRuleMatcher *ruleMatcher = static_cast<MagicRuleMatcher *>(matcher.data()); +// const int priority = ruleMatcher->priority(); +// const MagicRuleMatcher::MagicRuleList &rules = ruleMatcher->magicRules(); +// foreach (const MagicRuleMatcher::MagicRuleSharedPointer &rule, rules) +// addMagicHeaderRow(MagicData(rule->matchValue(), +// rule->matchType(), +// rule->startPos(), +// rule->endPos(), +// priority)); +// } } } @@ -417,94 +419,96 @@ void MimeTypeSettingsPrivate::handlePatternEdited() } } -void MimeTypeSettingsPrivate::addMagicHeaderRow(const MagicData &data) -{ - const int row = m_ui.magicHeadersTreeWidget->topLevelItemCount(); - editMagicHeaderRowData(row, data); -} - -MagicData MimeTypeSettingsPrivate::getMagicHeaderRowData(const int row) const -{ - MagicData data; - data.m_value = m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(0); - data.m_type = m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(1); - QPair<int, int> startEnd = - MagicRule::fromOffset(m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(2)); - data.m_start = startEnd.first; - data.m_end = startEnd.second; - data.m_priority = m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(3).toInt(); - - return data; -} +// TODO +//void MimeTypeSettingsPrivate::addMagicHeaderRow(const MagicData &data) +//{ +// const int row = m_ui.magicHeadersTreeWidget->topLevelItemCount(); +// editMagicHeaderRowData(row, data); +//} + +//MagicData MimeTypeSettingsPrivate::getMagicHeaderRowData(const int row) const +//{ +// MagicData data; +// data.m_value = m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(0); +// data.m_type = m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(1); +// QPair<int, int> startEnd = +// MagicRule::fromOffset(m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(2)); +// data.m_start = startEnd.first; +// data.m_end = startEnd.second; +// data.m_priority = m_ui.magicHeadersTreeWidget->topLevelItem(row)->text(3).toInt(); + +// return data; +//} + +//void MimeTypeSettingsPrivate::editMagicHeaderRowData(const int row, const MagicData &data) +//{ +// QTreeWidgetItem *item = new QTreeWidgetItem; +// item->setText(0, data.m_value); +// item->setText(1, data.m_type); +// item->setText(2, MagicRule::toOffset(qMakePair(data.m_start, data.m_end))); +// item->setText(3, QString::number(data.m_priority)); +// m_ui.magicHeadersTreeWidget->takeTopLevelItem(row); +// m_ui.magicHeadersTreeWidget->insertTopLevelItem(row, item); +// m_ui.magicHeadersTreeWidget->setCurrentItem(item); +//} + +//void MimeTypeSettingsPrivate::addMagicHeader() +//{ +// if (!checkSelectedMimeType()) +// return; + +// MimeTypeMagicDialog dlg; +// if (dlg.exec()) { +// addMagicHeaderRow(dlg.magicData()); +// markMimeForMagicSync(m_filterModel->mapToSource( +// m_ui.mimeTypesTreeView->currentIndex()).row()); +// } +//} + +//void MimeTypeSettingsPrivate::removeMagicHeader() +//{ +// if (!checkSelectedMagicHeader()) +// return; + +// m_ui.magicHeadersTreeWidget->takeTopLevelItem(m_ui.magicHeadersTreeWidget->indexOfTopLevelItem(m_ui.magicHeadersTreeWidget->currentItem())); +// markMimeForMagicSync(m_filterModel->mapToSource( +// m_ui.mimeTypesTreeView->currentIndex()).row()); +//} + +//void MimeTypeSettingsPrivate::editMagicHeader() +//{ +// if (!checkSelectedMagicHeader()) +// return; + +// MimeTypeMagicDialog dlg; +// dlg.setMagicData(getMagicHeaderRowData(m_ui.magicHeadersTreeWidget->indexOfTopLevelItem(m_ui.magicHeadersTreeWidget->currentItem()))); +// if (dlg.exec()) { +// editMagicHeaderRowData(m_ui.magicHeadersTreeWidget->indexOfTopLevelItem(m_ui.magicHeadersTreeWidget->currentItem()), dlg.magicData()); +// markMimeForMagicSync(m_filterModel->mapToSource( +// m_ui.mimeTypesTreeView->currentIndex()).row()); +// } +//} -void MimeTypeSettingsPrivate::editMagicHeaderRowData(const int row, const MagicData &data) -{ - QTreeWidgetItem *item = new QTreeWidgetItem; - item->setText(0, data.m_value); - item->setText(1, data.m_type); - item->setText(2, MagicRule::toOffset(qMakePair(data.m_start, data.m_end))); - item->setText(3, QString::number(data.m_priority)); - m_ui.magicHeadersTreeWidget->takeTopLevelItem(row); - m_ui.magicHeadersTreeWidget->insertTopLevelItem(row, item); - m_ui.magicHeadersTreeWidget->setCurrentItem(item); -} - -void MimeTypeSettingsPrivate::addMagicHeader() -{ - if (!checkSelectedMimeType()) - return; - - MimeTypeMagicDialog dlg; - if (dlg.exec()) { - addMagicHeaderRow(dlg.magicData()); - markMimeForMagicSync(m_filterModel->mapToSource( - m_ui.mimeTypesTreeView->currentIndex()).row()); - } -} - -void MimeTypeSettingsPrivate::removeMagicHeader() +void MimeTypeSettingsPrivate::updateMimeDatabase() { - if (!checkSelectedMagicHeader()) - return; + // TODO +// if (m_modifiedMimeTypes.isEmpty()) +// return; - m_ui.magicHeadersTreeWidget->takeTopLevelItem(m_ui.magicHeadersTreeWidget->indexOfTopLevelItem(m_ui.magicHeadersTreeWidget->currentItem())); - markMimeForMagicSync(m_filterModel->mapToSource( - m_ui.mimeTypesTreeView->currentIndex()).row()); -} +// // For this case it is a better approach to simply use a list and to remove duplicates +// // afterwards than to keep a more complex data structure like a hash table. +// Utils::sort(m_modifiedMimeTypes); +// m_modifiedMimeTypes.erase(std::unique(m_modifiedMimeTypes.begin(), m_modifiedMimeTypes.end()), +// m_modifiedMimeTypes.end()); -void MimeTypeSettingsPrivate::editMagicHeader() -{ - if (!checkSelectedMagicHeader()) - return; - - MimeTypeMagicDialog dlg; - dlg.setMagicData(getMagicHeaderRowData(m_ui.magicHeadersTreeWidget->indexOfTopLevelItem(m_ui.magicHeadersTreeWidget->currentItem()))); - if (dlg.exec()) { - editMagicHeaderRowData(m_ui.magicHeadersTreeWidget->indexOfTopLevelItem(m_ui.magicHeadersTreeWidget->currentItem()), dlg.magicData()); - markMimeForMagicSync(m_filterModel->mapToSource( - m_ui.mimeTypesTreeView->currentIndex()).row()); - } -} - -void MimeTypeSettingsPrivate::updateMimeDatabase() -{ - if (m_modifiedMimeTypes.isEmpty()) - return; - - // For this case it is a better approach to simply use a list and to remove duplicates - // afterwards than to keep a more complex data structure like a hash table. - Utils::sort(m_modifiedMimeTypes); - m_modifiedMimeTypes.erase(std::unique(m_modifiedMimeTypes.begin(), m_modifiedMimeTypes.end()), - m_modifiedMimeTypes.end()); - - QList<MimeType> allModified; - foreach (int index, m_modifiedMimeTypes) { - const MimeType &mimeType = m_model->m_mimeTypes.at(index); - MimeDatabase::setGlobPatterns(mimeType.type(), mimeType.globPatterns()); - MimeDatabase::setMagicMatchers(mimeType.type(), mimeType.magicMatchers()); - allModified.append(mimeType); - } - MimeDatabase::writeUserModifiedMimeTypes(allModified); +// QList<MimeType> allModified; +// foreach (int index, m_modifiedMimeTypes) { +// const MimeType &mimeType = m_model->m_mimeTypes.at(index); +// MimeDatabase::setGlobPatterns(mimeType.type(), mimeType.globPatterns()); +// MimeDatabase::setMagicMatchers(mimeType.type(), mimeType.magicMatchers()); +// allModified.append(mimeType); +// } +// MimeDatabase::writeUserModifiedMimeTypes(allModified); } void MimeTypeSettingsPrivate::resetState() @@ -561,6 +565,11 @@ QWidget *MimeTypeSettings::widget() if (!d->m_widget) { d->m_widget = new QWidget; d->configureUi(d->m_widget); + // TODO temporarily disabled + d->m_ui.addMagicButton->setEnabled(false); + d->m_ui.editMagicButton->setEnabled(false); + d->m_ui.removeMagicButton->setEnabled(false); + d->m_ui.patternsLineEdit->setEnabled(false); } return d->m_widget; } @@ -585,12 +594,13 @@ void MimeTypeSettings::apply() void MimeTypeSettings::finish() { - if (d->m_persist) { - if (d->m_reset) - MimeDatabase::clearUserModifiedMimeTypes(); - else - d->updateMimeDatabase(); - } + // TODO +// if (d->m_persist) { +// if (d->m_reset) +// MimeDatabase::clearUserModifiedMimeTypes(); +// else +// d->updateMimeDatabase(); +// } d->resetState(); delete d->m_widget; } diff --git a/src/plugins/cpaster/cpasterplugin.cpp b/src/plugins/cpaster/cpasterplugin.cpp index 570d3b8012..5e3caad193 100644 --- a/src/plugins/cpaster/cpasterplugin.cpp +++ b/src/plugins/cpaster/cpasterplugin.cpp @@ -46,11 +46,11 @@ #include <coreplugin/id.h> #include <coreplugin/coreconstants.h> #include <coreplugin/editormanager/editormanager.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> -#include <utils/qtcassert.h> #include <utils/fileutils.h> +#include <utils/mimetypes/mimedatabase.h> +#include <utils/qtcassert.h> #include <texteditor/texteditor.h> #include <QtPlugin> @@ -377,7 +377,9 @@ void CodepasterPlugin::finishFetch(const QString &titleDescription, // Default to "txt". QByteArray byteContent = content.toUtf8(); QString suffix; - if (const MimeType mimeType = MimeDatabase::findByData(byteContent)) + Utils::MimeDatabase mdb; + const Utils::MimeType mimeType = mdb.mimeTypeForData(byteContent); + if (mimeType.isValid()) suffix = mimeType.preferredSuffix(); if (suffix.isEmpty()) suffix = QLatin1String("txt"); diff --git a/src/plugins/cppeditor/CppEditor.mimetypes.xml b/src/plugins/cppeditor/CppEditor.mimetypes.xml index 37eeb170a5..cf31f0e315 100644 --- a/src/plugins/cppeditor/CppEditor.mimetypes.xml +++ b/src/plugins/cppeditor/CppEditor.mimetypes.xml @@ -1,33 +1,24 @@ <?xml version="1.0" encoding="UTF-8"?> <mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="text/x-csrc"> - <sub-class-of type="text/plain"/> - <comment>C Source file</comment> - <glob pattern="*.c"/> - <!-- NVIDIA CUDA files are like C --> - <glob pattern="*.cu"/> - </mime-type> - - <!-- A C Header file is virtually undistinguishable from the C++ header --> - <mime-type type="text/x-chdr"> + <mime-type type="text/vnd.nvidia.cuda.csrc"> <sub-class-of type="text/x-csrc"/> - <comment>C Header file</comment> - <glob pattern="*.h"/> + <comment>NVIDIA CUDA C source code</comment> + <glob pattern="*.cu"/> </mime-type> <!-- Those are used to find matching headers by the CppTools plugin, so, they should match --> <mime-type type="text/x-c++hdr"> <sub-class-of type="text/x-chdr"/> - <comment>C++ Header file</comment> <comment>C++ header</comment> - <glob pattern="*.h"/> <glob pattern="*.hh"/> <glob pattern="*.hxx"/> <glob pattern="*.h++"/> - <glob pattern="*.H"/> <glob pattern="*.hpp"/> <glob pattern="*.hp"/> + <!-- Additions to freedesktop: --> + <glob pattern="*.h"/> + <glob pattern="*.H"/> <!-- Find include guards of header files without extension, for example, STL ones like <string>. Those can have a big initial comment exceeding 1000 chars, though. --> @@ -39,17 +30,17 @@ </mime-type> <mime-type type="text/x-c++src"> - <comment>C++ Source file</comment> + <comment>C++ source code</comment> <sub-class-of type="text/x-csrc"/> <comment>C++ source code</comment> <glob pattern="*.cpp"/> - <glob pattern="*.cp"/> - <glob pattern="*.cc"/> <glob pattern="*.cxx"/> + <glob pattern="*.cc"/> + <glob pattern="*.C" case-sensitive="true"/> <glob pattern="*.c++"/> - <glob pattern="*.C"/> + <!-- Additions to freedesktop: --> + <glob pattern="*.cp"/> <glob pattern="*.inl"/> - <glob pattern="*.moc"/> <glob pattern="*.qdoc"/> <glob pattern="*.tcc"/> <glob pattern="*.tpp"/> @@ -60,11 +51,14 @@ </magic> </mime-type> - <mime-type type="text/x-objcsrc"> - <comment>Objective-C source code</comment> - <sub-class-of type="text/x-csrc"/> - <glob pattern="*.m"/> - </mime-type> + <mime-type type="text/x-moc"> + <comment>Qt MOC file</comment> + <acronym>Qt MOC</acronym> + <expanded-acronym>Qt Meta Object Compiler</expanded-acronym> + <!-- Fix to freedesktop: moc is C++ source --> + <sub-class-of type="text/x-c++src"/> + <glob pattern="*.moc"/> + </mime-type> <mime-type type="text/x-objc++src"> <comment>Objective-C++ source code</comment> diff --git a/src/plugins/cppeditor/cppeditordocument.cpp b/src/plugins/cppeditor/cppeditordocument.cpp index 40abd27f44..d29b680fd8 100644 --- a/src/plugins/cppeditor/cppeditordocument.cpp +++ b/src/plugins/cppeditor/cppeditordocument.cpp @@ -44,6 +44,7 @@ #include <projectexplorer/session.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/runextensions.h> @@ -202,7 +203,8 @@ void CppEditorDocument::onFilePathChanged(const Utils::FileName &oldPath, Q_UNUSED(oldPath); if (!newPath.isEmpty()) { - setMimeType(Core::MimeDatabase::findByFile(newPath.toFileInfo()).type()); + Utils::MimeDatabase mdb; + setMimeType(mdb.mimeTypeForFile(newPath.toFileInfo()).name()); disconnect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument())); connect(this, SIGNAL(contentsChanged()), this, SLOT(scheduleProcessDocument())); diff --git a/src/plugins/cppeditor/cppeditorplugin.cpp b/src/plugins/cppeditor/cppeditorplugin.cpp index 918b6ba76f..f8874787cf 100644 --- a/src/plugins/cppeditor/cppeditorplugin.cpp +++ b/src/plugins/cppeditor/cppeditorplugin.cpp @@ -60,7 +60,7 @@ #include <texteditor/texteditorconstants.h> #include <utils/hostosinfo.h> - +#include <utils/mimetypes/mimedatabase.h> #include <utils/theme/theme.h> #include <QCoreApplication> @@ -153,8 +153,8 @@ CppQuickFixAssistProvider *CppEditorPlugin::quickFixProvider() const bool CppEditorPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage) { - if (!MimeDatabase::addMimeTypes(QLatin1String(":/cppeditor/CppEditor.mimetypes.xml"), errorMessage)) - return false; + Q_UNUSED(errorMessage) + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/cppeditor/CppEditor.mimetypes.xml")); addAutoReleasedObject(new CppEditorFactory); addAutoReleasedObject(new CppOutlineWidgetFactory); diff --git a/src/plugins/cpptools/cppcompletionassist.cpp b/src/plugins/cpptools/cppcompletionassist.cpp index d11ac69f0b..8057bd1a98 100644 --- a/src/plugins/cpptools/cppcompletionassist.cpp +++ b/src/plugins/cpptools/cppcompletionassist.cpp @@ -49,6 +49,7 @@ #include <texteditor/texteditorsettings.h> #include <texteditor/completionsettings.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <cplusplus/BackwardsScanner.h> @@ -1120,9 +1121,8 @@ bool InternalCppCompletionAssistProcessor::completeInclude(const QTextCursor &cu if (!headerPaths.contains(currentFilePath)) headerPaths.append(currentFilePath); - const Core::MimeType mimeType = - Core::MimeDatabase::findByType(QLatin1String("text/x-c++hdr")); - const QStringList suffixes = mimeType.suffixes(); + Utils::MimeDatabase mdb; + const QStringList suffixes = mdb.mimeTypeForName(QLatin1String("text/x-c++hdr")).suffixes(); foreach (const ProjectPart::HeaderPath &headerPath, headerPaths) { QString realPath = headerPath.path; @@ -1171,9 +1171,10 @@ bool InternalCppCompletionAssistProcessor::objcKeywordsWanted() const const QString fileName = m_interface->fileName(); - const QString mt = Core::MimeDatabase::findByFile(fileName).type(); - return mt == QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE) - || mt == QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE); + Utils::MimeDatabase mdb; + const Utils::MimeType mt = mdb.mimeTypeForFile(fileName); + return mt.matchesName(QLatin1String(CppTools::Constants::OBJECTIVE_C_SOURCE_MIMETYPE)) + || mt.matchesName(QLatin1String(CppTools::Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)); } int InternalCppCompletionAssistProcessor::startCompletionInternal(const QString &fileName, diff --git a/src/plugins/cpptools/cppfilesettingspage.cpp b/src/plugins/cpptools/cppfilesettingspage.cpp index 449095664e..af5680b42d 100644 --- a/src/plugins/cpptools/cppfilesettingspage.cpp +++ b/src/plugins/cpptools/cppfilesettingspage.cpp @@ -36,11 +36,11 @@ #include <coreplugin/icore.h> #include <coreplugin/editormanager/editormanager.h> -#include <coreplugin/mimedatabase.h> #include <cppeditor/cppeditorconstants.h> #include <utils/environment.h> #include <utils/fileutils.h> +#include <utils/mimetypes/mimedatabase.h> #include <QSettings> #include <QDebug> @@ -118,8 +118,17 @@ void CppFileSettings::fromSettings(QSettings *s) bool CppFileSettings::applySuffixesToMimeDB() { - return Core::MimeDatabase::setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE), sourceSuffix) - && Core::MimeDatabase::setPreferredSuffix(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE), headerSuffix); + Utils::MimeDatabase mdb; + Utils::MimeType mt; + mt = mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)); + if (!mt.isValid()) + return false; + mt.setPreferredSuffix(sourceSuffix); + mt = mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)); + if (!mt.isValid()) + return false; + mt.setPreferredSuffix(headerSuffix); + return true; } bool CppFileSettings::equals(const CppFileSettings &rhs) const @@ -255,13 +264,18 @@ CppFileSettingsWidget::CppFileSettingsWidget(QWidget *parent) : { m_ui->setupUi(this); // populate suffix combos - if (const Core::MimeType sourceMt = Core::MimeDatabase::findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE))) + Utils::MimeDatabase mdb; + const Utils::MimeType sourceMt = mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)); + if (sourceMt.isValid()) { foreach (const QString &suffix, sourceMt.suffixes()) m_ui->sourceSuffixComboBox->addItem(suffix); + } - if (const Core::MimeType headerMt = Core::MimeDatabase::findByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))) + const Utils::MimeType headerMt = mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)); + if (headerMt.isValid()) { foreach (const QString &suffix, headerMt.suffixes()) m_ui->headerSuffixComboBox->addItem(suffix); + } m_ui->licenseTemplatePathChooser->setExpectedKind(Utils::PathChooser::File); m_ui->licenseTemplatePathChooser->setHistoryCompleter(QLatin1String("Cpp.LicenseTemplate.History")); m_ui->licenseTemplatePathChooser->addButton(tr("Edit..."), this, SLOT(slotEdit())); diff --git a/src/plugins/cpptools/cppprojectfile.cpp b/src/plugins/cpptools/cppprojectfile.cpp index 8936b2e240..56a035adc7 100644 --- a/src/plugins/cpptools/cppprojectfile.cpp +++ b/src/plugins/cpptools/cppprojectfile.cpp @@ -33,7 +33,8 @@ #include "cpptoolsconstants.h" #include <coreplugin/icore.h> - +#include <utils/mimetypes/mimedatabase.h> +# #include <QDebug> namespace CppTools { @@ -51,11 +52,11 @@ ProjectFile::ProjectFile(const QString &file, Kind kind) ProjectFile::Kind ProjectFile::classify(const QString &file) { - const QFileInfo fi(file); - const Core::MimeType mimeType = Core::MimeDatabase::findByFile(fi); - if (!mimeType) + Utils::MimeDatabase mdb; + const Utils::MimeType mimeType = mdb.mimeTypeForFile(file); + if (!mimeType.isValid()) return Unclassified; - const QString mt = mimeType.type(); + const QString mt = mimeType.name(); if (mt == QLatin1String(CppTools::Constants::C_SOURCE_MIMETYPE)) return CSource; if (mt == QLatin1String(CppTools::Constants::C_HEADER_MIMETYPE)) @@ -141,20 +142,22 @@ ProjectFileAdder::~ProjectFileAdder() bool ProjectFileAdder::maybeAdd(const QString &path) { - m_fileInfo.setFile(path); - foreach (const Pair &pair, m_mapping) - if (pair.first.matchesFile(path)) { - m_files << ProjectFile(path, pair.second); - return true; - } + const Utils::MimeType mt = Utils::MimeDatabase::bestMatch(path, m_mimeTypes); + if (mt.isValid()) { + m_files << ProjectFile(path, m_mimeNameMapping.value(mt.name())); + return true; + } return false; } void ProjectFileAdder::addMapping(const char *mimeName, ProjectFile::Kind kind) { - Core::MimeType mimeType = Core::MimeDatabase::findByType(QLatin1String(mimeName)); - if (!mimeType.isNull()) - m_mapping.append(Pair(mimeType, kind)); + Utils::MimeDatabase mdb; + Utils::MimeType mimeType = mdb.mimeTypeForName(QLatin1String(mimeName)); + if (mimeType.isValid()) { + m_mimeNameMapping.insert(mimeType.name(), kind); + m_mimeTypes.append(mimeType); + } } } // namespace Internal diff --git a/src/plugins/cpptools/cppprojectfile.h b/src/plugins/cpptools/cppprojectfile.h index 8202820dc9..c656b70e8b 100644 --- a/src/plugins/cpptools/cppprojectfile.h +++ b/src/plugins/cpptools/cppprojectfile.h @@ -33,8 +33,10 @@ #include "cpptools_global.h" -#include <coreplugin/mimedatabase.h> +#include <utils/mimetypes/mimetype.h> +#include <QHash> +#include <QList> #include <QString> namespace CppTools { @@ -81,13 +83,12 @@ public: bool maybeAdd(const QString &path); private: - typedef QPair<Core::MimeType, ProjectFile::Kind> Pair; void addMapping(const char *mimeName, ProjectFile::Kind kind); QList<ProjectFile> &m_files; - QList<Pair> m_mapping; - QFileInfo m_fileInfo; + QHash<QString, ProjectFile::Kind> m_mimeNameMapping; + QList<Utils::MimeType> m_mimeTypes; }; } // namespace Internal diff --git a/src/plugins/cpptools/cpptoolsplugin.cpp b/src/plugins/cpptools/cpptoolsplugin.cpp index 36c9552260..628a0e122b 100644 --- a/src/plugins/cpptools/cpptoolsplugin.cpp +++ b/src/plugins/cpptools/cpptoolsplugin.cpp @@ -59,6 +59,7 @@ #include <utils/fileutils.h> #include <utils/hostosinfo.h> #include <utils/macroexpander.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QtPlugin> @@ -270,24 +271,25 @@ static QStringList findFilesInProject(const QString &name, // source belonging to a header and vice versa static QStringList matchingCandidateSuffixes(ProjectFile::Kind kind) { + Utils::MimeDatabase mdb; switch (kind) { // Note that C/C++ headers are undistinguishable case ProjectFile::CHeader: case ProjectFile::CXXHeader: case ProjectFile::ObjCHeader: case ProjectFile::ObjCXXHeader: - return MimeDatabase::findByType(QLatin1String(Constants::C_SOURCE_MIMETYPE)).suffixes() - + MimeDatabase::findByType(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)).suffixes() - + MimeDatabase::findByType(QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE)).suffixes() - + MimeDatabase::findByType(QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes(); + return mdb.mimeTypeForName(QLatin1String(Constants::C_SOURCE_MIMETYPE)).suffixes() + + mdb.mimeTypeForName(QLatin1String(Constants::CPP_SOURCE_MIMETYPE)).suffixes() + + mdb.mimeTypeForName(QLatin1String(Constants::OBJECTIVE_C_SOURCE_MIMETYPE)).suffixes() + + mdb.mimeTypeForName(QLatin1String(Constants::OBJECTIVE_CPP_SOURCE_MIMETYPE)).suffixes(); case ProjectFile::CSource: case ProjectFile::ObjCSource: - return MimeDatabase::findByType(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes(); + return mdb.mimeTypeForName(QLatin1String(Constants::C_HEADER_MIMETYPE)).suffixes(); case ProjectFile::CXXSource: case ProjectFile::ObjCXXSource: case ProjectFile::CudaSource: case ProjectFile::OpenCLSource: - return MimeDatabase::findByType(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes(); + return mdb.mimeTypeForName(QLatin1String(Constants::CPP_HEADER_MIMETYPE)).suffixes(); default: return QStringList(); } diff --git a/src/plugins/cvs/cvsplugin.cpp b/src/plugins/cvs/cvsplugin.cpp index 09bf9f55c8..fd5d777f81 100644 --- a/src/plugins/cvs/cvsplugin.cpp +++ b/src/plugins/cvs/cvsplugin.cpp @@ -52,7 +52,6 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/messagebox.h> #include <coreplugin/messagemanager.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/actionmanager/command.h> @@ -60,8 +59,9 @@ #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/locator/commandlocator.h> #include <coreplugin/vcsmanager.h> -#include <utils/stringutils.h> #include <utils/fileutils.h> +#include <utils/mimetypes/mimedatabase.h> +#include <utils/stringutils.h> #include <QDebug> #include <QDate> @@ -230,7 +230,8 @@ static const VcsBaseSubmitEditorParameters submitParameters = { bool CvsPlugin::initialize(const QStringList &arguments, QString *errorMessage) { - Q_UNUSED(arguments); + Q_UNUSED(arguments) + Q_UNUSED(errorMessage) using namespace Constants; using namespace Core::Constants; @@ -240,8 +241,7 @@ bool CvsPlugin::initialize(const QStringList &arguments, QString *errorMessage) m_cvsPluginInstance = this; - if (!MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.cvs/CVS.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.cvs/CVS.mimetypes.xml")); m_settings.readSettings(ICore::settings()); m_client = new CvsClient(&m_settings); diff --git a/src/plugins/debugger/Debugger.mimetypes.xml b/src/plugins/debugger/Debugger.mimetypes.xml new file mode 100644 index 0000000000..c59d5ea56a --- /dev/null +++ b/src/plugins/debugger/Debugger.mimetypes.xml @@ -0,0 +1,14 @@ +<?xml version="1.0"?> +<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> + <mime-type type="text/x-asm"> + <sub-class-of type="text/plain"/> + <comment>Assembler</comment> + <glob pattern="*.asm"/> + </mime-type> + <!-- Catch-all for assemblers --> + <mime-type type="text/x-qtcreator-generic-asm"> + <sub-class-of type="text/x-asm"/> + <comment>Qt Creator Generic Assembler</comment> + <glob pattern="*.asm"/> + </mime-type> +</mime-info> diff --git a/src/plugins/debugger/debugger.qrc b/src/plugins/debugger/debugger.qrc index 5fe047141b..4e930511e0 100644 --- a/src/plugins/debugger/debugger.qrc +++ b/src/plugins/debugger/debugger.qrc @@ -38,5 +38,6 @@ <file>images/qml/apply-on-save.png</file> <file>images/debugger_restart.png</file> <file>images/debugger_restart_small.png</file> + <file>Debugger.mimetypes.xml</file> </qresource> </RCC> diff --git a/src/plugins/debugger/debuggerplugin.cpp b/src/plugins/debugger/debuggerplugin.cpp index 6ab869034c..581a27626d 100644 --- a/src/plugins/debugger/debuggerplugin.cpp +++ b/src/plugins/debugger/debuggerplugin.cpp @@ -106,6 +106,7 @@ #include <utils/basetreeview.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/proxyaction.h> #include <utils/qtcassert.h> #include <utils/savedaction.h> @@ -1269,6 +1270,8 @@ bool DebuggerPluginPrivate::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(errorMessage); + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/debugger/Debugger.mimetypes.xml")); + m_arguments = arguments; if (!m_arguments.isEmpty()) connect(KitManager::instance(), &KitManager::kitsLoaded, diff --git a/src/plugins/debugger/disassembleragent.cpp b/src/plugins/debugger/disassembleragent.cpp index 90f5b8dde3..30c884a1fe 100644 --- a/src/plugins/debugger/disassembleragent.cpp +++ b/src/plugins/debugger/disassembleragent.cpp @@ -41,11 +41,11 @@ #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <texteditor/textdocument.h> #include <texteditor/texteditor.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QTextBlock> @@ -237,8 +237,9 @@ void DisassemblerAgentPrivate::configureMimeType() document->setMimeType(mimeType); - MimeType mtype = MimeDatabase::findByType(mimeType); - if (mtype) { + Utils::MimeDatabase mdb; + Utils::MimeType mtype = mdb.mimeTypeForName(mimeType); + if (mtype.isValid()) { foreach (IEditor *editor, DocumentModel::editorsForDocument(document)) if (TextEditorWidget *widget = qobject_cast<TextEditorWidget *>(editor->widget())) widget->configureGenericHighlighter(); diff --git a/src/plugins/designer/Designer.mimetypes.xml b/src/plugins/designer/Designer.mimetypes.xml deleted file mode 100644 index a593f240d1..0000000000 --- a/src/plugins/designer/Designer.mimetypes.xml +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="application/x-designer"> - <sub-class-of type="application/xml"/> - <comment>Qt Designer file</comment> - <glob pattern="*.ui"/> - </mime-type> -</mime-info> diff --git a/src/plugins/designer/cpp/formclasswizardpage.cpp b/src/plugins/designer/cpp/formclasswizardpage.cpp index 767b283849..bf26dedfd2 100644 --- a/src/plugins/designer/cpp/formclasswizardpage.cpp +++ b/src/plugins/designer/cpp/formclasswizardpage.cpp @@ -35,9 +35,9 @@ #include <utils/wizard.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <cpptools/cpptoolsconstants.h> - +#include <utils/mimetypes/mimedatabase.h> +# #include <QDebug> #include <QMessageBox> @@ -84,8 +84,13 @@ bool FormClassWizardPage::lowercaseHeaderFiles() // Set up new class widget from settings void FormClassWizardPage::initFileGenerationSettings() { - m_ui->newClassWidget->setHeaderExtension(Core::MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))); - m_ui->newClassWidget->setSourceExtension(Core::MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE))); + Utils::MimeDatabase mdb; + m_ui->newClassWidget->setHeaderExtension( + mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)) + .preferredSuffix()); + m_ui->newClassWidget->setSourceExtension( + mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)) + .preferredSuffix()); m_ui->newClassWidget->setLowerCaseFiles(lowercaseHeaderFiles()); } diff --git a/src/plugins/designer/designer.qrc b/src/plugins/designer/designer.qrc index 7565ed0032..3f1fd4ebe0 100644 --- a/src/plugins/designer/designer.qrc +++ b/src/plugins/designer/designer.qrc @@ -1,6 +1,5 @@ <RCC> - <qresource prefix="/formeditor" > + <qresource prefix="/formeditor"> <file>images/qt_ui.png</file> - <file>Designer.mimetypes.xml</file> </qresource> </RCC> diff --git a/src/plugins/designer/formeditorplugin.cpp b/src/plugins/designer/formeditorplugin.cpp index 4d95d3d67a..36322b33f6 100644 --- a/src/plugins/designer/formeditorplugin.cpp +++ b/src/plugins/designer/formeditorplugin.cpp @@ -45,14 +45,15 @@ #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/coreconstants.h> #include <coreplugin/designmode.h> #include <cpptools/cpptoolsconstants.h> #include <projectexplorer/jsonwizard/jsonwizardfactory.h> - +#include <utils/mimetypes/mimedatabase.h> +# #include <QApplication> #include <QDebug> +#include <QFileInfo> #include <QLibraryInfo> #include <QTranslator> #include <QtPlugin> @@ -80,9 +81,6 @@ bool FormEditorPlugin::initialize(const QStringList &arguments, QString *error) { Q_UNUSED(arguments) - if (!MimeDatabase::addMimeTypes(QLatin1String(":/formeditor/Designer.mimetypes.xml"), error)) - return false; - initializeTemplates(); ProjectExplorer::JsonWizardFactory::registerPageFactory(new Internal::FormPageFactory); @@ -162,17 +160,19 @@ static QString otherFile() const QString current = currentFile(); if (current.isEmpty()) return QString(); - const MimeType currentMimeType = MimeDatabase::findByFile(current); - if (!currentMimeType) + Utils::MimeDatabase mdb; + const Utils::MimeType currentMimeType = mdb.mimeTypeForFile(current); + if (!currentMimeType.isValid()) return QString(); // Determine potential suffixes of candidate files // 'ui' -> 'cpp', 'cpp/h' -> 'ui'. QStringList candidateSuffixes; - if (currentMimeType.type() == QLatin1String(FORM_MIMETYPE)) { - candidateSuffixes += MimeDatabase::findByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes(); - } else if (currentMimeType.type() == QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE) - || currentMimeType.type() == QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)) { - candidateSuffixes += MimeDatabase::findByType(QLatin1String(FORM_MIMETYPE)).suffixes(); + if (currentMimeType.matchesName(QLatin1String(FORM_MIMETYPE))) { + candidateSuffixes += mdb.mimeTypeForName( + QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)).suffixes(); + } else if (currentMimeType.matchesName(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)) + || currentMimeType.matchesName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))) { + candidateSuffixes += mdb.mimeTypeForName(QLatin1String(FORM_MIMETYPE)).suffixes(); } else { return QString(); } diff --git a/src/plugins/designer/formeditorw.cpp b/src/plugins/designer/formeditorw.cpp index af42604c14..42d1e3c308 100644 --- a/src/plugins/designer/formeditorw.cpp +++ b/src/plugins/designer/formeditorw.cpp @@ -49,7 +49,6 @@ #include <coreplugin/actionmanager/actioncontainer.h> #include <coreplugin/modemanager.h> #include <coreplugin/minisplitter.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/outputpane.h> #include <utils/qtcassert.h> diff --git a/src/plugins/designer/qtcreatorintegration.cpp b/src/plugins/designer/qtcreatorintegration.cpp index fbfad6ca16..1376648fd6 100644 --- a/src/plugins/designer/qtcreatorintegration.cpp +++ b/src/plugins/designer/qtcreatorintegration.cpp @@ -45,6 +45,7 @@ #include <texteditor/texteditor.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/session.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QDesignerFormWindowInterface> @@ -641,6 +642,7 @@ bool QtCreatorIntegration::navigateToSlot(const QString &objectName, void QtCreatorIntegration::slotSyncSettingsToDesigner() { // Set promotion-relevant parameters on integration. - setHeaderSuffix(Core::MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))); + Utils::MimeDatabase mdb; + setHeaderSuffix(mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)).preferredSuffix()); setHeaderLowercase(FormClassWizardPage::lowercaseHeaderFiles()); } diff --git a/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp b/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp index c90982db6e..b91c4b81e5 100644 --- a/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp +++ b/src/plugins/diffeditor/sidebysidediffeditorwidget.cpp @@ -56,7 +56,6 @@ #include <coreplugin/icore.h> #include <coreplugin/minisplitter.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/patchtool.h> #include <extensionsystem/pluginmanager.h> diff --git a/src/plugins/diffeditor/unifieddiffeditorwidget.cpp b/src/plugins/diffeditor/unifieddiffeditorwidget.cpp index eb2ab3cdad..17c1bd8c43 100644 --- a/src/plugins/diffeditor/unifieddiffeditorwidget.cpp +++ b/src/plugins/diffeditor/unifieddiffeditorwidget.cpp @@ -55,7 +55,6 @@ #include <coreplugin/icore.h> #include <coreplugin/minisplitter.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/patchtool.h> #include <extensionsystem/pluginmanager.h> diff --git a/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp b/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp index 5e4bc5446b..da5b17e19d 100644 --- a/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp +++ b/src/plugins/genericprojectmanager/filesselectionwizardpage.cpp @@ -33,7 +33,6 @@ #include "genericprojectwizard.h" #include "genericprojectconstants.h" -#include <coreplugin/mimedatabase.h> #include <coreplugin/icore.h> #include <projectexplorer/selectablefilesmodel.h> diff --git a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp index 8c0b6686ca..dd74961bba 100644 --- a/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp +++ b/src/plugins/genericprojectmanager/genericbuildconfiguration.cpp @@ -35,12 +35,12 @@ #include "genericprojectconstants.h" #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/buildinfo.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/toolchain.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/pathchooser.h> #include <utils/qtcassert.h> @@ -103,8 +103,10 @@ QList<BuildInfo *> GenericBuildConfigurationFactory::availableBuilds(const Targe int GenericBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const { - return (k && Core::MimeDatabase::findByFile(QFileInfo(projectPath)) - .matchesType(QLatin1String(Constants::GENERICMIMETYPE))) ? 0 : -1; + Utils::MimeDatabase mdb; + if (k && mdb.mimeTypeForFile(projectPath).matchesName(QLatin1String(Constants::GENERICMIMETYPE))) + return 0; + return -1; } QList<BuildInfo *> GenericBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const diff --git a/src/plugins/genericprojectmanager/genericproject.cpp b/src/plugins/genericprojectmanager/genericproject.cpp index df91ad0b2e..ce33b8a889 100644 --- a/src/plugins/genericprojectmanager/genericproject.cpp +++ b/src/plugins/genericprojectmanager/genericproject.cpp @@ -37,7 +37,6 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/icontext.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <cpptools/cpptoolsconstants.h> #include <cpptools/cppmodelmanager.h> #include <extensionsystem/pluginmanager.h> diff --git a/src/plugins/genericprojectmanager/genericprojectplugin.cpp b/src/plugins/genericprojectmanager/genericprojectplugin.cpp index 32f5466671..79aa8abcd2 100644 --- a/src/plugins/genericprojectmanager/genericprojectplugin.cpp +++ b/src/plugins/genericprojectmanager/genericprojectplugin.cpp @@ -39,7 +39,6 @@ #include "genericproject.h" #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> @@ -47,6 +46,8 @@ #include <projectexplorer/projecttree.h> #include <projectexplorer/selectablefilesmodel.h> +#include <utils/mimetypes/mimedatabase.h> + #include <QtPlugin> #include <QDebug> @@ -62,10 +63,8 @@ GenericProjectPlugin::GenericProjectPlugin() bool GenericProjectPlugin::initialize(const QStringList &, QString *errorMessage) { - const QLatin1String mimetypesXml(":genericproject/GenericProjectManager.mimetypes.xml"); - - if (!MimeDatabase::addMimeTypes(mimetypesXml, errorMessage)) - return false; + Q_UNUSED(errorMessage) + Utils::MimeDatabase::addMimeTypes(QLatin1String(":genericproject/GenericProjectManager.mimetypes.xml")); addAutoReleasedObject(new Manager); addAutoReleasedObject(new ProjectFilesFactory); diff --git a/src/plugins/genericprojectmanager/genericprojectwizard.cpp b/src/plugins/genericprojectmanager/genericprojectwizard.cpp index c43dc22b28..f7b9e757b8 100644 --- a/src/plugins/genericprojectmanager/genericprojectwizard.cpp +++ b/src/plugins/genericprojectmanager/genericprojectwizard.cpp @@ -32,11 +32,11 @@ #include "filesselectionwizardpage.h" #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/customwizard/customwizard.h> #include <utils/filewizardpage.h> +#include <utils/mimetypes/mimedatabase.h> #include <QApplication> #include <QDebug> @@ -156,11 +156,10 @@ Core::GeneratedFiles GenericProjectWizard::generateFiles(const QWizard *w, const QString configFileName = QFileInfo(dir, projectName + QLatin1String(".config")).absoluteFilePath(); const QStringList paths = wizard->selectedPaths(); - Core::MimeType headerTy = Core::MimeDatabase::findByType(QLatin1String("text/x-chdr")); + Utils::MimeDatabase mdb; + Utils::MimeType headerTy = mdb.mimeTypeForName(QLatin1String("text/x-chdr")); - QStringList nameFilters; - foreach (const Core::MimeGlobPattern &gp, headerTy.globPatterns()) - nameFilters.append(gp.pattern()); + QStringList nameFilters = headerTy.globPatterns(); QStringList includePaths; foreach (const QString &path, paths) { diff --git a/src/plugins/git/gitplugin.cpp b/src/plugins/git/gitplugin.cpp index 552d16232b..222d76bd72 100644 --- a/src/plugins/git/gitplugin.cpp +++ b/src/plugins/git/gitplugin.cpp @@ -59,11 +59,11 @@ #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/locator/commandlocator.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/vcsmanager.h> #include <coreplugin/coreconstants.h> #include <coreplugin/messagebox.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/parameteraction.h> @@ -269,6 +269,7 @@ QAction *GitPlugin::createRepositoryAction(ActionContainer *ac, bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) + Q_UNUSED(errorMessage) Context context(Constants::GIT_CONTEXT); @@ -655,8 +656,7 @@ bool GitPlugin::initialize(const QStringList &arguments, QString *errorMessage) connect(VcsManager::instance(), SIGNAL(repositoryChanged(QString)), this, SLOT(updateBranches(QString)), Qt::QueuedConnection); - if (!MimeDatabase::addMimeTypes(QLatin1String(RC_GIT_MIME_XML), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(RC_GIT_MIME_XML)); /* "Gerrit" */ m_gerritPlugin = new Gerrit::Internal::GerritPlugin(this); diff --git a/src/plugins/glsleditor/glsleditorplugin.cpp b/src/plugins/glsleditor/glsleditorplugin.cpp index 35bd943dd8..bd6c2fde17 100644 --- a/src/plugins/glsleditor/glsleditorplugin.cpp +++ b/src/plugins/glsleditor/glsleditorplugin.cpp @@ -46,12 +46,12 @@ #include <coreplugin/fileiconprovider.h> #include <coreplugin/icore.h> #include <coreplugin/id.h> -#include <coreplugin/mimedatabase.h> #include <extensionsystem/pluginmanager.h> #include <texteditor/texteditorconstants.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QAction> @@ -122,8 +122,7 @@ GlslEditorPlugin::~GlslEditorPlugin() bool GlslEditorPlugin::initialize(const QStringList & /*arguments*/, QString *errorMessage) { - if (!MimeDatabase::addMimeTypes(QLatin1String(":/glsleditor/GLSLEditor.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/glsleditor/GLSLEditor.mimetypes.xml")); addAutoReleasedObject(new GlslEditorFactory); addAutoReleasedObject(new GlslCompletionAssistProvider); diff --git a/src/plugins/imageviewer/ImageViewer.mimetypes.xml b/src/plugins/imageviewer/ImageViewer.mimetypes.xml deleted file mode 100644 index f4f99a7a1c..0000000000 --- a/src/plugins/imageviewer/ImageViewer.mimetypes.xml +++ /dev/null @@ -1,70 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="image/bmp"> - <sub-class-of type="application/octet-stream"/> - <comment>BMP image</comment> - <glob pattern="*.bmp"/> - </mime-type> - <mime-type type="image/gif"> - <sub-class-of type="application/octet-stream"/> - <comment>GIF image</comment> - <glob pattern="*.gif"/> - </mime-type> - <mime-type type="image/x-icon"> - <sub-class-of type="application/octet-stream"/> - <comment>ICO image</comment> - <glob pattern="*.ico"/> - </mime-type> - <mime-type type="image/jpeg"> - <sub-class-of type="application/octet-stream"/> - <comment>JPEG image</comment> - <glob pattern="*.jpg"/> - <glob pattern="*.jpeg"/> - </mime-type> - <mime-type type="video/x-mng"> - <sub-class-of type="application/octet-stream"/> - <comment>MNG video</comment> - <glob pattern="*.mng"/> - </mime-type> - <mime-type type="image/x-portable-bitmap"> - <sub-class-of type="application/octet-stream"/> - <comment>PBM image</comment> - <glob pattern="*.pbm"/> - </mime-type> - <mime-type type="image/x-portable-graymap"> - <sub-class-of type="application/octet-stream"/> - <comment>PGM image</comment> - <glob pattern="*.pgm"/> - </mime-type> - <mime-type type="image/png"> - <sub-class-of type="application/octet-stream"/> - <comment>PNG image</comment> - <glob pattern="*.png"/> - </mime-type> - <mime-type type="image/x-portable-pixmap"> - <sub-class-of type="application/octet-stream"/> - <comment>PPM image</comment> - <glob pattern="*.ppm"/> - </mime-type> - <mime-type type="image/svg+xml"> - <sub-class-of type="application/octet-stream"/> - <comment>SVG image</comment> - <glob pattern="*.svg"/> - </mime-type> - <mime-type type="image/tiff"> - <sub-class-of type="application/octet-stream"/> - <comment>TIFF image</comment> - <glob pattern="*.tif"/> - <glob pattern="*.tiff"/> - </mime-type> - <mime-type type="image/xbm"> - <sub-class-of type="application/octet-stream"/> - <comment>XBM image</comment> - <glob pattern="*.xbm"/> - </mime-type> - <mime-type type="image/xpm"> - <sub-class-of type="application/octet-stream"/> - <comment>XPM image</comment> - <glob pattern="*.xpm"/> - </mime-type> -</mime-info> diff --git a/src/plugins/imageviewer/imageviewer.qrc b/src/plugins/imageviewer/imageviewer.qrc index d48561a89e..94f8b07631 100644 --- a/src/plugins/imageviewer/imageviewer.qrc +++ b/src/plugins/imageviewer/imageviewer.qrc @@ -1,6 +1,5 @@ <RCC> <qresource prefix="/imageviewer"> - <file>ImageViewer.mimetypes.xml</file> <file>images/outline.png</file> <file>images/zoomin.png</file> <file>images/zoomout.png</file> diff --git a/src/plugins/imageviewer/imageviewerplugin.cpp b/src/plugins/imageviewer/imageviewerplugin.cpp index 865e3aaede..20a1cfcf43 100644 --- a/src/plugins/imageviewer/imageviewerplugin.cpp +++ b/src/plugins/imageviewer/imageviewerplugin.cpp @@ -36,7 +36,6 @@ #include <QDebug> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/id.h> #include <extensionsystem/pluginmanager.h> @@ -48,9 +47,7 @@ namespace Internal { bool ImageViewerPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) - - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/imageviewer/ImageViewer.mimetypes.xml"), errorMessage)) - return false; + Q_UNUSED(errorMessage) m_factory = new ImageViewerFactory(this); addAutoReleasedObject(m_factory); diff --git a/src/plugins/perforce/perforceplugin.cpp b/src/plugins/perforce/perforceplugin.cpp index a5e00a2299..fb2bba4041 100644 --- a/src/plugins/perforce/perforceplugin.cpp +++ b/src/plugins/perforce/perforceplugin.cpp @@ -48,12 +48,12 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/icore.h> #include <coreplugin/messagemanager.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/locator/commandlocator.h> +#include <utils/fileutils.h> +#include <utils/mimetypes/mimedatabase.h> +#include <utils/parameteraction.h> #include <utils/qtcassert.h> #include <utils/synchronousprocess.h> -#include <utils/parameteraction.h> -#include <utils/fileutils.h> #include <vcsbase/basevcseditorfactory.h> #include <vcsbase/basevcssubmiteditorfactory.h> #include <vcsbase/vcsbaseeditor.h> @@ -221,12 +221,13 @@ static const VcsBaseSubmitEditorParameters submitParameters = { bool PerforcePlugin::initialize(const QStringList & /* arguments */, QString *errorMessage) { + Q_UNUSED(errorMessage) Context context(PERFORCE_CONTEXT); initializeVcs(new PerforceVersionControl(this), context); - if (!MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.perforce/Perforce.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.perforce/Perforce.mimetypes.xml")); + m_instance = this; m_settings.fromSettings(ICore::settings()); diff --git a/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp b/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp index 773dcfd685..80ce3a40ba 100644 --- a/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp +++ b/src/plugins/projectexplorer/customwizard/customwizardparameters.cpp @@ -32,10 +32,10 @@ #include "customwizardpreprocessor.h" #include "customwizardscriptgenerator.h" -#include <coreplugin/mimedatabase.h> #include <coreplugin/icore.h> #include <cpptools/cpptoolsconstants.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <QCoreApplication> @@ -917,10 +917,13 @@ void CustomWizardContext::reset() const QDate currentDate = QDate::currentDate(); const QTime currentTime = QTime::currentTime(); baseReplacements.clear(); + Utils::MimeDatabase mdb; baseReplacements.insert(QLatin1String("CppSourceSuffix"), - MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE))); + mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_SOURCE_MIMETYPE)) + .preferredSuffix()); baseReplacements.insert(QLatin1String("CppHeaderSuffix"), - MimeDatabase::preferredSuffixByType(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE))); + mdb.mimeTypeForName(QLatin1String(CppTools::Constants::CPP_HEADER_MIMETYPE)) + .preferredSuffix()); baseReplacements.insert(QLatin1String("CurrentDate"), currentDate.toString(Qt::ISODate)); baseReplacements.insert(QLatin1String("CurrentTime"), diff --git a/src/plugins/projectexplorer/jsonwizard/jsonkitspage.cpp b/src/plugins/projectexplorer/jsonwizard/jsonkitspage.cpp index 502119daaf..ed6985ecc5 100644 --- a/src/plugins/projectexplorer/jsonwizard/jsonkitspage.cpp +++ b/src/plugins/projectexplorer/jsonwizard/jsonkitspage.cpp @@ -37,12 +37,12 @@ #include "../projectexplorer.h" #include <coreplugin/featureprovider.h> -#include <coreplugin/mimedatabase.h> #include <extensionsystem/pluginmanager.h> #include <utils/algorithm.h> #include <utils/macroexpander.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> namespace ProjectExplorer { @@ -102,11 +102,12 @@ void JsonKitsPage::setupProjectFiles(const JsonWizard::GeneratorFiles &files) if (fi.exists()) path = fi.canonicalFilePath(); - Core::MimeType mt = Core::MimeDatabase::findByFile(fi); - if (mt.isNull()) + Utils::MimeDatabase mdb; + Utils::MimeType mt = mdb.mimeTypeForFile(fi); + if (!mt.isValid()) continue; - auto manager = Utils::findOrDefault(managerList, Utils::equal(&IProjectManager::mimeType, mt.type())); + auto manager = Utils::findOrDefault(managerList, Utils::equal(&IProjectManager::mimeType, mt.name())); project = manager ? manager->openProject(path, &errorMessage) : 0; if (project) { if (setupProject(project)) diff --git a/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp b/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp index 2ca6972e96..ec643baf79 100644 --- a/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp +++ b/src/plugins/projectexplorer/jsonwizard/jsonwizardgeneratorfactory.cpp @@ -38,7 +38,6 @@ #include "../projectexplorerconstants.h" #include <coreplugin/dialogs/promptoverwritedialog.h> -#include <coreplugin/mimedatabase.h> #include <texteditor/icodestylepreferences.h> #include <texteditor/icodestylepreferencesfactory.h> #include <texteditor/indenter.h> @@ -48,6 +47,7 @@ #include <texteditor/texteditorsettings.h> #include <utils/algorithm.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/stringutils.h> #include <utils/qtcassert.h> @@ -90,8 +90,8 @@ bool JsonWizardGenerator::formatFile(const JsonWizard *wizard, GeneratedFile *fi if (file->isBinary() || file->contents().isEmpty()) return true; // nothing to do - MimeType mt = MimeDatabase::findByFile(QFileInfo(file->path())); - Id languageId = TextEditorSettings::languageId(mt.type()); + Utils::MimeDatabase mdb; + Id languageId = TextEditorSettings::languageId(mdb.mimeTypeForFile(file->path()).name()); if (!languageId.isValid()) return true; // don't modify files like *.ui, *.pro diff --git a/src/plugins/projectexplorer/projectexplorer.cpp b/src/plugins/projectexplorer/projectexplorer.cpp index c842c49f7e..2d928926d8 100644 --- a/src/plugins/projectexplorer/projectexplorer.cpp +++ b/src/plugins/projectexplorer/projectexplorer.cpp @@ -111,7 +111,6 @@ #include <coreplugin/coreconstants.h> #include <coreplugin/documentmanager.h> #include <coreplugin/imode.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/modemanager.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> @@ -128,6 +127,7 @@ #include <utils/algorithm.h> #include <utils/fileutils.h> #include <utils/macroexpander.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/parameteraction.h> #include <utils/qtcassert.h> #include <utils/stringutils.h> @@ -1337,7 +1337,7 @@ void ProjectExplorerPlugin::extensionsInitialized() QList<IProjectManager*> projectManagers = ExtensionSystem::PluginManager::getObjects<IProjectManager>(); - QList<MimeGlobPattern> allGlobPatterns; + QStringList allGlobPatterns; const QString filterSeparator = QLatin1String(";;"); QStringList filterStrings; @@ -1352,10 +1352,11 @@ void ProjectExplorerPlugin::extensionsInitialized() return 0; }); + Utils::MimeDatabase mdb; foreach (IProjectManager *manager, projectManagers) { const QString mimeType = manager->mimeType(); factory->addMimeType(mimeType); - MimeType mime = MimeDatabase::findByType(mimeType); + Utils::MimeType mime = mdb.mimeTypeForName(mimeType); allGlobPatterns.append(mime.globPatterns()); filterStrings.append(mime.filterString()); @@ -1364,8 +1365,10 @@ void ProjectExplorerPlugin::extensionsInitialized() addAutoReleasedObject(factory); - filterStrings.prepend(MimeType::formatFilterString( - tr("All Projects"), allGlobPatterns)); + QString allProjectsFilter = tr("All Projects"); + allProjectsFilter += QLatin1String(" (") + allGlobPatterns.join(QLatin1Char(' ')) + + QLatin1Char(')'); + filterStrings.prepend(allProjectsFilter); dd->m_projectFilterString = filterStrings.join(filterSeparator); BuildManager::extensionsInitialized(); @@ -1573,10 +1576,12 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName continue; } - if (const MimeType mt = MimeDatabase::findByFile(QFileInfo(fileName))) { + Utils::MimeDatabase mdb; + Utils::MimeType mt = mdb.mimeTypeForFile(fileName); + if (mt.isValid()) { bool foundProjectManager = false; foreach (IProjectManager *manager, projectManagers) { - if (manager->mimeType() == mt.type()) { + if (mt.matchesName(manager->mimeType())) { foundProjectManager = true; QString tmp; if (Project *pro = manager->openProject(filePath, &tmp)) { @@ -1598,7 +1603,7 @@ QList<Project *> ProjectExplorerPlugin::openProjects(const QStringList &fileName if (!foundProjectManager) { appendError(errorString, tr("Failed opening project \"%1\": No plugin can open project type \"%2\".") .arg(QDir::toNativeSeparators(fileName)) - .arg((mt.type()))); + .arg(mt.name())); } } else { appendError(errorString, tr("Failed opening project \"%1\": Unknown project type.") @@ -1666,11 +1671,13 @@ void ProjectExplorerPlugin::determineSessionToRestoreAtStartup() QStringList ProjectExplorerPlugin::projectFileGlobs() { QStringList result; + Utils::MimeDatabase mdb; foreach (const IProjectManager *ipm, ExtensionSystem::PluginManager::getObjects<IProjectManager>()) { - if (const MimeType mimeType = MimeDatabase::findByType(ipm->mimeType())) { - const QList<MimeGlobPattern> patterns = mimeType.globPatterns(); + Utils::MimeType mimeType = mdb.mimeTypeForName(ipm->mimeType()); + if (mimeType.isValid()) { + const QStringList patterns = mimeType.globPatterns(); if (!patterns.isEmpty()) - result.push_back(patterns.front().pattern()); + result.append(patterns.front()); } } return result; @@ -3122,10 +3129,12 @@ ProjectExplorerSettings ProjectExplorerPlugin::projectExplorerSettings() QStringList ProjectExplorerPlugin::projectFilePatterns() { QStringList patterns; - foreach (const IProjectManager *pm, allProjectManagers()) - if (const MimeType mt = MimeDatabase::findByType(pm->mimeType())) - foreach (const MimeGlobPattern &gp, mt.globPatterns()) - patterns.append(gp.pattern()); + Utils::MimeDatabase mdb; + foreach (const IProjectManager *pm, allProjectManagers()) { + Utils::MimeType mt = mdb.mimeTypeForName(pm->mimeType()); + if (mt.isValid()) + patterns.append(mt.globPatterns()); + } return patterns; } diff --git a/src/plugins/projectexplorer/projectexplorerconstants.h b/src/plugins/projectexplorer/projectexplorerconstants.h index 72235e7640..37818e8fb6 100644 --- a/src/plugins/projectexplorer/projectexplorerconstants.h +++ b/src/plugins/projectexplorer/projectexplorerconstants.h @@ -171,7 +171,7 @@ const char C_SOURCE_MIMETYPE[] = "text/x-csrc"; const char C_HEADER_MIMETYPE[] = "text/x-chdr"; const char CPP_SOURCE_MIMETYPE[] = "text/x-c++src"; const char CPP_HEADER_MIMETYPE[] = "text/x-c++hdr"; -const char LINGUIST_MIMETYPE[] = "application/x-linguist"; +const char LINGUIST_MIMETYPE[] = "text/vnd.trolltech.linguist"; const char FORM_MIMETYPE[] = "application/x-designer"; const char QML_MIMETYPE[] = "application/x-qml"; // separate def also in qmljstoolsconstants.h const char RESOURCE_MIMETYPE[] = "application/vnd.qt.xml.resource"; diff --git a/src/plugins/projectexplorer/projectfilewizardextension.cpp b/src/plugins/projectexplorer/projectfilewizardextension.cpp index dd8ec516ce..2b6a253d49 100644 --- a/src/plugins/projectexplorer/projectfilewizardextension.cpp +++ b/src/plugins/projectexplorer/projectfilewizardextension.cpp @@ -39,7 +39,6 @@ #include <utils/stringutils.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <texteditor/texteditorsettings.h> #include <texteditor/icodestylepreferences.h> #include <texteditor/icodestylepreferencesfactory.h> @@ -48,7 +47,8 @@ #include <texteditor/storagesettings.h> #include <projectexplorer/project.h> #include <projectexplorer/editorconfiguration.h> - +#include <utils/mimetypes/mimedatabase.h> +# #include <QPointer> #include <QDebug> #include <QFileInfo> @@ -230,8 +230,8 @@ void ProjectFileWizardExtension::applyCodeStyle(GeneratedFile *file) const if (file->isBinary() || file->contents().isEmpty()) return; // nothing to do - MimeType mt = MimeDatabase::findByFile(QFileInfo(file->path())); - Id languageId = TextEditorSettings::languageId(mt.type()); + Utils::MimeDatabase mdb; + Id languageId = TextEditorSettings::languageId(mdb.mimeTypeForFile(file->path()).name()); if (!languageId.isValid()) return; // don't modify files like *.ui *.pro diff --git a/src/plugins/projectexplorer/projectnodes.cpp b/src/plugins/projectexplorer/projectnodes.cpp index 51591dd8bd..b6dcb505f9 100644 --- a/src/plugins/projectexplorer/projectnodes.cpp +++ b/src/plugins/projectexplorer/projectnodes.cpp @@ -34,7 +34,6 @@ #include "projectexplorerconstants.h" #include "projecttree.h" -#include <coreplugin/mimedatabase.h> #include <coreplugin/fileiconprovider.h> #include <coreplugin/icore.h> #include <coreplugin/iversioncontrol.h> diff --git a/src/plugins/projectexplorer/projectnodes.h b/src/plugins/projectexplorer/projectnodes.h index 47082ca92f..553fe805b8 100644 --- a/src/plugins/projectexplorer/projectnodes.h +++ b/src/plugins/projectexplorer/projectnodes.h @@ -45,8 +45,6 @@ QT_BEGIN_NAMESPACE class QFileInfo; QT_END_NAMESPACE -namespace Core { class MimeDatabase; } - namespace ProjectExplorer { class RunConfiguration; diff --git a/src/plugins/pythoneditor/PythonEditor.mimetypes.xml b/src/plugins/pythoneditor/PythonEditor.mimetypes.xml index 61009c0d0e..23d192286e 100644 --- a/src/plugins/pythoneditor/PythonEditor.mimetypes.xml +++ b/src/plugins/pythoneditor/PythonEditor.mimetypes.xml @@ -1,10 +1,8 @@ <?xml version="1.0"?> <mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="text/x-python"> - <sub-class-of type="text/plain"/> - <comment>Python Source File</comment> - <glob pattern="*.py"/> + <mime-type type="text/x-python-gui"> + <sub-class-of type="text/x-python"/> + <comment>Python source file without console</comment> <glob pattern="*.pyw"/> - <glob pattern="*.wsgi"/> </mime-type> </mime-info> diff --git a/src/plugins/pythoneditor/pythoneditorconstants.h b/src/plugins/pythoneditor/pythoneditorconstants.h index 217ae3bdfc..54505bd4b5 100644 --- a/src/plugins/pythoneditor/pythoneditorconstants.h +++ b/src/plugins/pythoneditor/pythoneditorconstants.h @@ -44,7 +44,6 @@ const char C_EDITOR_DISPLAY_NAME[] = * MIME type ******************************************************************************/ const char C_PY_MIMETYPE[] = "text/x-python"; -const char RC_PY_MIME_XML[] = ":/pythoneditor/PythonEditor.mimetypes.xml"; const char C_PY_MIME_ICON[] = "text-x-python"; } // namespace Constants diff --git a/src/plugins/pythoneditor/pythoneditorplugin.cpp b/src/plugins/pythoneditor/pythoneditorplugin.cpp index ff92ed0380..881e2a6911 100644 --- a/src/plugins/pythoneditor/pythoneditorplugin.cpp +++ b/src/plugins/pythoneditor/pythoneditorplugin.cpp @@ -35,12 +35,12 @@ #include <coreplugin/icore.h> #include <coreplugin/coreconstants.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/fileiconprovider.h> #include <coreplugin/id.h> #include <coreplugin/editormanager/editormanager.h> #include <extensionsystem/pluginmanager.h> #include <texteditor/texteditorconstants.h> +#include <utils/mimetypes/mimedatabase.h> #include <QtPlugin> #include <QCoreApplication> @@ -209,9 +209,9 @@ PythonEditorPlugin::~PythonEditorPlugin() bool PythonEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) + Q_UNUSED(errorMessage) - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(RC_PY_MIME_XML), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/pythoneditor/PythonEditor.mimetypes.xml")); addAutoReleasedObject(new PythonEditorFactory); diff --git a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp index 713b9bf813..f01eb4b09b 100644 --- a/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp +++ b/src/plugins/qbsprojectmanager/qbsbuildconfiguration.cpp @@ -40,7 +40,6 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <utils/qtcassert.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/kit.h> @@ -49,6 +48,7 @@ #include <projectexplorer/projectmacroexpander.h> #include <projectexplorer/target.h> #include <projectexplorer/toolchain.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcprocess.h> #include <QCoreApplication> @@ -397,8 +397,10 @@ QList<BuildInfo *> QbsBuildConfigurationFactory::availableBuilds(const Target *p int QbsBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const { - return (k && Core::MimeDatabase::findByFile(QFileInfo(projectPath)) - .matchesType(QLatin1String(Constants::MIME_TYPE))) ? 0 : -1; + Utils::MimeDatabase mdb; + if (k && mdb.mimeTypeForFile(projectPath).matchesName(QLatin1String(Constants::MIME_TYPE))) + return 0; + return -1; } static Utils::FileName defaultBuildDirectory(const QString &projectFilePath, const Kit *k, diff --git a/src/plugins/qbsprojectmanager/qbsproject.cpp b/src/plugins/qbsprojectmanager/qbsproject.cpp index 980a7c8a59..6dc7a181e0 100644 --- a/src/plugins/qbsprojectmanager/qbsproject.cpp +++ b/src/plugins/qbsprojectmanager/qbsproject.cpp @@ -46,7 +46,6 @@ #include <coreplugin/vcsmanager.h> #include <coreplugin/messagemanager.h> #include <coreplugin/progressmanager/progressmanager.h> -#include <coreplugin/mimedatabase.h> #include <cpptools/cppmodelmanager.h> #include <projectexplorer/buildenvironmentwidget.h> #include <projectexplorer/buildmanager.h> diff --git a/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp b/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp index 2241309fda..4923f2b444 100644 --- a/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp +++ b/src/plugins/qmakeprojectmanager/qmakebuildconfiguration.cpp @@ -41,7 +41,6 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/buildsteplist.h> #include <projectexplorer/kit.h> @@ -52,6 +51,7 @@ #include <projectexplorer/toolchainmanager.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtversionmanager.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/qtcprocess.h> #include <utils/qtcassert.h> @@ -687,8 +687,10 @@ QList<BuildInfo *> QmakeBuildConfigurationFactory::availableBuilds(const Target int QmakeBuildConfigurationFactory::priority(const Kit *k, const QString &projectPath) const { - return (k && Core::MimeDatabase::findByFile(QFileInfo(projectPath)) - .matchesType(QLatin1String(Constants::PROFILE_MIMETYPE))) ? 0 : -1; + Utils::MimeDatabase mdb; + if (k && mdb.mimeTypeForFile(projectPath).matchesName(QLatin1String(Constants::PROFILE_MIMETYPE))) + return 0; + return -1; } QList<BuildInfo *> QmakeBuildConfigurationFactory::availableSetups(const Kit *k, const QString &projectPath) const diff --git a/src/plugins/qmakeprojectmanager/qmakenodes.cpp b/src/plugins/qmakeprojectmanager/qmakenodes.cpp index f6d0e07ae0..d8b90a04c0 100644 --- a/src/plugins/qmakeprojectmanager/qmakenodes.cpp +++ b/src/plugins/qmakeprojectmanager/qmakenodes.cpp @@ -63,6 +63,7 @@ #include <utils/fileutils.h> #include <utils/hostosinfo.h> #include <utils/qtcprocess.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/stringutils.h> #include <utils/theme/theme.h> #include <proparser/prowriter.h> @@ -1033,9 +1034,10 @@ bool QmakePriFileNode::addFiles(const QStringList &filePaths, QStringList *notAd typedef QMap<QString, QStringList> TypeFileMap; // Split into lists by file type and bulk-add them. TypeFileMap typeFileMap; + Utils::MimeDatabase mdb; foreach (const QString &file, filePaths) { - const Core::MimeType mt = Core::MimeDatabase::findByFile(file); - typeFileMap[mt.type()] << file; + const Utils::MimeType mt = mdb.mimeTypeForFile(file); + typeFileMap[mt.name()] << file; } QStringList failedFiles; @@ -1080,9 +1082,10 @@ bool QmakePriFileNode::removeFiles(const QStringList &filePaths, typedef QMap<QString, QStringList> TypeFileMap; // Split into lists by file type and bulk-add them. TypeFileMap typeFileMap; + Utils::MimeDatabase mdb; foreach (const QString &file, filePaths) { - const Core::MimeType mt = Core::MimeDatabase::findByFile(file); - typeFileMap[mt.type()] << file; + const Utils::MimeType mt = mdb.mimeTypeForFile(file); + typeFileMap[mt.name()] << file; } foreach (const QString &type, typeFileMap.keys()) { const QStringList typeFiles = typeFileMap.value(type); @@ -1105,13 +1108,14 @@ bool QmakePriFileNode::renameFile(const QString &filePath, const QString &newFil return false; bool changeProFileOptional = deploysFolder(QFileInfo(filePath).absolutePath()); - const Core::MimeType mt = Core::MimeDatabase::findByFile(newFilePath); + Utils::MimeDatabase mdb; + const Utils::MimeType mt = mdb.mimeTypeForFile(newFilePath); QStringList dummy; - changeFiles(mt.type(), QStringList() << filePath, &dummy, RemoveFromProFile); + changeFiles(mt.name(), QStringList() << filePath, &dummy, RemoveFromProFile); if (!dummy.isEmpty() && !changeProFileOptional) return false; - changeFiles(mt.type(), QStringList() << newFilePath, &dummy, AddToProFile); + changeFiles(mt.name(), QStringList() << newFilePath, &dummy, AddToProFile); if (!dummy.isEmpty() && !changeProFileOptional) return false; return true; diff --git a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp index 78332c73e1..cac76533eb 100644 --- a/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp +++ b/src/plugins/qmakeprojectmanager/qmakeprojectmanagerplugin.cpp @@ -55,7 +55,6 @@ #include <projectexplorer/session.h> #include <projectexplorer/projecttree.h> #include <projectexplorer/target.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/coreconstants.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> @@ -64,6 +63,7 @@ #include <texteditor/texteditoractionhandler.h> #include <texteditor/texteditorconstants.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/parameteraction.h> #ifdef WITH_TESTS @@ -94,11 +94,11 @@ QmakeProjectManagerPlugin::~QmakeProjectManagerPlugin() bool QmakeProjectManagerPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) + Q_UNUSED(errorMessage) const Core::Context projectContext(QmakeProjectManager::Constants::PROJECT_ID); Core::Context projecTreeContext(ProjectExplorer::Constants::C_PROJECT_TREE); - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":qmakeprojectmanager/QmakeProjectManager.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":qmakeprojectmanager/QmakeProjectManager.mimetypes.xml")); //create and register objects m_qmakeProjectManager = new QmakeManager; diff --git a/src/plugins/qmljstools/QmlJSTools.mimetypes.xml b/src/plugins/qmljstools/QmlJSTools.mimetypes.xml index 048a192e9d..e92b773542 100644 --- a/src/plugins/qmljstools/QmlJSTools.mimetypes.xml +++ b/src/plugins/qmljstools/QmlJSTools.mimetypes.xml @@ -4,7 +4,7 @@ <alias type="text/x-qml"/> <sub-class-of type="text/plain"/> <comment>QML file</comment> - <glob weight="50" pattern="*.qml"/> + <glob pattern="*.qml"/> </mime-type> <mime-type type="application/x-qt.qbs+qml"> <alias type="text/x-qt.qbs+qml"/> @@ -16,7 +16,7 @@ <alias type="text/x-qt.ui+qml"/> <sub-class-of type="application/x-qml"/> <comment>QtQuick Designer ui file</comment> - <glob weight="100" pattern="*.ui.qml"/> + <glob pattern="*.ui.qml"/> </mime-type> <mime-type type="application/x-qmlproject"> <alias type="text/x-qmlproject"/> @@ -30,16 +30,6 @@ <comment>QML file</comment> <glob pattern="*.qmltypes"/> </mime-type> - <mime-type type="application/javascript"> - <alias type="application/x-javascript"/> - <alias type="text/javascript"/> - <alias type="text/x-javascript"/> - <sub-class-of type="text/plain"/> - <comment>Qt Script file</comment> - <glob pattern="*.js"/> - <glob pattern="*.qs"/> - <glob pattern="*.qtt"/> - </mime-type> <mime-type type="application/json"> <sub-class-of type="text/plain"/> <comment>JSON file</comment> diff --git a/src/plugins/qmljstools/qmljsmodelmanager.cpp b/src/plugins/qmljstools/qmljsmodelmanager.cpp index 3c37317fb1..83698a91d3 100644 --- a/src/plugins/qmljstools/qmljsmodelmanager.cpp +++ b/src/plugins/qmljstools/qmljsmodelmanager.cpp @@ -52,6 +52,7 @@ #include <qtsupport/qtsupportconstants.h> #include <texteditor/textdocument.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <QDir> #include <QFile> @@ -76,22 +77,18 @@ ModelManagerInterface::ProjectInfo QmlJSTools::Internal::ModelManager::defaultPr ModelManagerInterface::ProjectInfo projectInfo(project); ProjectExplorer::Target *activeTarget = 0; if (project) { - QList<MimeGlobPattern> globs; - foreach (const MimeType &mimeType, MimeDatabase::mimeTypes()) - if (mimeType.type() == QLatin1String(Constants::QML_MIMETYPE) - || mimeType.subClassesOf().contains(QLatin1String(Constants::QML_MIMETYPE))) - globs << mimeType.globPatterns(); - if (globs.isEmpty()) { - globs.append(MimeGlobPattern(QLatin1String("*.qbs"))); - globs.append(MimeGlobPattern(QLatin1String("*.qml"))); - globs.append(MimeGlobPattern(QLatin1String("*.qmltypes"))); - globs.append(MimeGlobPattern(QLatin1String("*.qmlproject"))); + Utils::MimeDatabase mdb; + QList<Utils::MimeType> qmlTypes; + foreach (const Utils::MimeType &mimeType, mdb.allMimeTypes()) { + if (mimeType.matchesName(QLatin1String(Constants::QML_MIMETYPE)) + || mimeType.allAncestors().contains(QLatin1String(Constants::QML_MIMETYPE))) + qmlTypes.append(mimeType); } foreach (const QString &filePath, - project->files(ProjectExplorer::Project::ExcludeGeneratedFiles)) - foreach (const MimeGlobPattern &glob, globs) - if (glob.matches(filePath)) - projectInfo.sourceFiles << filePath; + project->files(ProjectExplorer::Project::ExcludeGeneratedFiles)) { + if (mdb.bestMatch(filePath, qmlTypes).isValid()) + projectInfo.sourceFiles << filePath; + } activeTarget = project->activeTarget(); } ProjectExplorer::Kit *activeKit = activeTarget ? activeTarget->kit() : @@ -179,22 +176,23 @@ QHash<QString,QmlJS::Dialect> ModelManager::languageForSuffix() const QHash<QString,QmlJS::Dialect> res = ModelManagerInterface::languageForSuffix(); if (ICore::instance()) { - MimeType jsSourceTy = MimeDatabase::findByType(QLatin1String(Constants::JS_MIMETYPE)); + Utils::MimeDatabase mdb; + Utils::MimeType jsSourceTy = mdb.mimeTypeForName(QLatin1String(Constants::JS_MIMETYPE)); foreach (const QString &suffix, jsSourceTy.suffixes()) res[suffix] = Dialect::JavaScript; - MimeType qmlSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QML_MIMETYPE)); + Utils::MimeType qmlSourceTy = mdb.mimeTypeForName(QLatin1String(Constants::QML_MIMETYPE)); foreach (const QString &suffix, qmlSourceTy.suffixes()) res[suffix] = Dialect::Qml; - MimeType qbsSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QBS_MIMETYPE)); + Utils::MimeType qbsSourceTy = mdb.mimeTypeForName(QLatin1String(Constants::QBS_MIMETYPE)); foreach (const QString &suffix, qbsSourceTy.suffixes()) res[suffix] = Dialect::QmlQbs; - MimeType qmlProjectSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QMLPROJECT_MIMETYPE)); + Utils::MimeType qmlProjectSourceTy = mdb.mimeTypeForName(QLatin1String(Constants::QMLPROJECT_MIMETYPE)); foreach (const QString &suffix, qmlProjectSourceTy.suffixes()) res[suffix] = Dialect::QmlProject; - MimeType qmlUiSourceTy = MimeDatabase::findByType(QLatin1String(Constants::QMLUI_MIMETYPE)); + Utils::MimeType qmlUiSourceTy = mdb.mimeTypeForName(QLatin1String(Constants::QMLUI_MIMETYPE)); foreach (const QString &suffix, qmlUiSourceTy.suffixes()) res[suffix] = Dialect::QmlQtQuick2Ui; - MimeType jsonSourceTy = MimeDatabase::findByType(QLatin1String(Constants::JSON_MIMETYPE)); + Utils::MimeType jsonSourceTy = mdb.mimeTypeForName(QLatin1String(Constants::JSON_MIMETYPE)); foreach (const QString &suffix, jsonSourceTy.suffixes()) res[suffix] = Dialect::Json; } @@ -269,23 +267,6 @@ void ModelManager::updateDefaultProjectInfo() } -// Check whether fileMimeType is the same or extends knownMimeType -bool ModelManager::matchesMimeType(const MimeType &fileMimeType, const MimeType &knownMimeType) -{ - const QStringList knownTypeNames = QStringList(knownMimeType.type()) + knownMimeType.aliases(); - - foreach (const QString &knownTypeName, knownTypeNames) - if (fileMimeType.matchesType(knownTypeName)) - return true; - - // recursion to parent types of fileMimeType - foreach (const QString &parentMimeType, fileMimeType.subClassesOf()) - if (matchesMimeType(MimeDatabase::findByType(parentMimeType), knownMimeType)) - return true; - - return false; -} - void ModelManager::addTaskInternal(QFuture<void> result, const QString &msg, const char *taskId) const { ProgressManager::addTask(result, msg, taskId); diff --git a/src/plugins/qmljstools/qmljsmodelmanager.h b/src/plugins/qmljstools/qmljsmodelmanager.h index 2b1e107a30..3cef07c227 100644 --- a/src/plugins/qmljstools/qmljsmodelmanager.h +++ b/src/plugins/qmljstools/qmljsmodelmanager.h @@ -46,7 +46,7 @@ QT_FORWARD_DECLARE_CLASS(QTimer) QT_FORWARD_DECLARE_CLASS(QLocale) -namespace Core { class MimeType; } +namespace Utils { class MimeType; } namespace QmlJSTools { namespace Internal { @@ -70,7 +70,6 @@ private slots: void updateDefaultProjectInfo(); private: void loadDefaultQmlTypeDescriptions(); - static bool matchesMimeType(const Core::MimeType &fileMimeType, const Core::MimeType &knownMimeType); }; } // namespace Internal diff --git a/src/plugins/qmljstools/qmljstoolsplugin.cpp b/src/plugins/qmljstools/qmljstoolsplugin.cpp index 114fabed71..15c1acb77f 100644 --- a/src/plugins/qmljstools/qmljstoolsplugin.cpp +++ b/src/plugins/qmljstools/qmljstoolsplugin.cpp @@ -42,8 +42,8 @@ #include <coreplugin/coreconstants.h> #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/actionmanager/actioncontainer.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/progressmanager/progressmanager.h> +#include <utils/mimetypes/mimedatabase.h> #include <QtPlugin> #include <QMenu> @@ -72,9 +72,9 @@ QmlJSToolsPlugin::~QmlJSToolsPlugin() bool QmlJSToolsPlugin::initialize(const QStringList &arguments, QString *error) { Q_UNUSED(arguments) + Q_UNUSED(error) - if (!MimeDatabase::addMimeTypes(QLatin1String(":/qmljstools/QmlJSTools.mimetypes.xml"), error)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/qmljstools/QmlJSTools.mimetypes.xml")); m_settings = new QmlJSToolsSettings(this); // force registration of qmljstools settings diff --git a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp index 0176b4eb2c..71e48493f3 100644 --- a/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp +++ b/src/plugins/qmlprojectmanager/qmlprojectplugin.cpp @@ -37,10 +37,11 @@ #include <coreplugin/fileiconprovider.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <qtsupport/qtsupportconstants.h> +#include <utils/mimetypes/mimedatabase.h> + #include <QtPlugin> #include <QApplication> @@ -58,18 +59,14 @@ QmlProjectPlugin::~QmlProjectPlugin() bool QmlProjectPlugin::initialize(const QStringList &, QString *errorMessage) { - using namespace Core; - - const QLatin1String mimetypesXml(":/qmlproject/QmlProjectManager.mimetypes.xml"); - - if (!MimeDatabase::addMimeTypes(mimetypesXml, errorMessage)) - return false; + Q_UNUSED(errorMessage) + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/qmlproject/QmlProjectManager.mimetypes.xml")); addAutoReleasedObject(new Internal::Manager); addAutoReleasedObject(new Internal::QmlProjectRunConfigurationFactory); addAutoReleasedObject(new Internal::QmlApplicationWizard); - FileIconProvider::registerIconOverlayForSuffix(":/qmlproject/images/qmlproject.png", "qmlproject"); + Core::FileIconProvider::registerIconOverlayForSuffix(":/qmlproject/images/qmlproject.png", "qmlproject"); return true; } diff --git a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp index 46c9dffece..5ba76147ce 100644 --- a/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp +++ b/src/plugins/qmlprojectmanager/qmlprojectrunconfiguration.cpp @@ -33,7 +33,6 @@ #include "qmlprojectmanagerconstants.h" #include "qmlprojectrunconfigurationwidget.h" #include "qmlprojectenvironmentaspect.h" -#include <coreplugin/mimedatabase.h> #include <coreplugin/editormanager/editormanager.h> #include <coreplugin/editormanager/ieditor.h> #include <coreplugin/icore.h> @@ -43,6 +42,7 @@ #include <qtsupport/qtsupportconstants.h> #include <utils/fileutils.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcprocess.h> #include <utils/winutils.h> @@ -264,22 +264,23 @@ void QmlProjectRunConfiguration::changeCurrentFile(IEditor *editor) void QmlProjectRunConfiguration::updateEnabled() { bool qmlFileFound = false; + Utils::MimeDatabase mdb; if (mainScriptSource() == FileInEditor) { IDocument *document = EditorManager::currentDocument(); if (document) { m_currentFileFilename = document->filePath().toString(); - if (MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qml")) + if (mdb.mimeTypeForFile(mainScript()).matchesName(QLatin1String("application/x-qml"))) qmlFileFound = true; } if (!document - || MimeDatabase::findByFile(mainScript()).type() == QLatin1String("application/x-qmlproject")) { + || mdb.mimeTypeForFile(mainScript()).matchesName(QLatin1String("application/x-qmlproject"))) { // find a qml file with lowercase filename. This is slow, but only done // in initialization/other border cases. foreach (const QString &filename, target()->project()->files(Project::AllFiles)) { const QFileInfo fi(filename); if (!filename.isEmpty() && fi.baseName()[0].isLower() - && MimeDatabase::findByFile(fi).type() == QLatin1String("application/x-qml")) + && mdb.mimeTypeForFile(fi).matchesName(QLatin1String("application/x-qml"))) { m_currentFileFilename = filename; qmlFileFound = true; diff --git a/src/plugins/qnx/Qnx.mimetypes.xml b/src/plugins/qnx/Qnx.mimetypes.xml new file mode 100644 index 0000000000..7a78496903 --- /dev/null +++ b/src/plugins/qnx/Qnx.mimetypes.xml @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> + <mime-type type="application/vnd.rim.qnx.bar_descriptor"> + <comment>BAR descriptor file (BlackBerry)</comment> + <sub-class-of type="application/xml"/> + <glob pattern="*.xml"/> + <magic> + <match value="<qnx>" type="string" offset="0:1000"/> + </magic> + </mime-type> +</mime-info> diff --git a/src/plugins/qnx/bardescriptormagicmatcher.cpp b/src/plugins/qnx/bardescriptormagicmatcher.cpp deleted file mode 100644 index d8f6b56c83..0000000000 --- a/src/plugins/qnx/bardescriptormagicmatcher.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/************************************************************************** -** -** Copyright (C) 2015 BlackBerry Limited. All rights reserved. -** -** Contact: BlackBerry (qt@blackberry.com) -** Contact: KDAB (info@kdab.com) -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms and -** conditions see http://www.qt.io/terms-conditions. For further information -** use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -****************************************************************************/ - -#include "bardescriptormagicmatcher.h" - -#include <QXmlStreamReader> - -using namespace Qnx; -using namespace Qnx::Internal; - -BarDescriptorMagicMatcher::BarDescriptorMagicMatcher() -{ -} - -bool BarDescriptorMagicMatcher::matches(const QByteArray &data) const -{ - QXmlStreamReader reader(data); - if (reader.readNextStartElement()) - return reader.name() == QLatin1String("qnx"); - - return false; -} - -int BarDescriptorMagicMatcher::priority() const -{ - return Core::MimeGlobPattern::MaxWeight; -} diff --git a/src/plugins/qnx/bardescriptormagicmatcher.h b/src/plugins/qnx/bardescriptormagicmatcher.h deleted file mode 100644 index 25e8be5c1d..0000000000 --- a/src/plugins/qnx/bardescriptormagicmatcher.h +++ /dev/null @@ -1,53 +0,0 @@ -/************************************************************************** -** -** Copyright (C) 2015 BlackBerry Limited. All rights reserved. -** -** Contact: BlackBerry (qt@blackberry.com) -** Contact: KDAB (info@kdab.com) -** -** This file is part of Qt Creator. -** -** Commercial License Usage -** Licensees holding valid commercial Qt licenses may use this file in -** accordance with the commercial license agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and The Qt Company. For licensing terms and -** conditions see http://www.qt.io/terms-conditions. For further information -** use the contact form at http://www.qt.io/contact-us. -** -** GNU Lesser General Public License Usage -** Alternatively, this file may be used under the terms of the GNU Lesser -** General Public License version 2.1 or version 3 as published by the Free -** Software Foundation and appearing in the file LICENSE.LGPLv21 and -** LICENSE.LGPLv3 included in the packaging of this file. Please review the -** following information to ensure the GNU Lesser General Public License -** requirements will be met: https://www.gnu.org/licenses/lgpl.html and -** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. -** -** In addition, as a special exception, The Qt Company gives you certain additional -** rights. These rights are described in The Qt Company LGPL Exception -** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. -** -****************************************************************************/ - -#ifndef QNX_INTERNAL_BARDESCRIPTORMAGICMATCHER_H -#define QNX_INTERNAL_BARDESCRIPTORMAGICMATCHER_H - -#include <coreplugin/mimedatabase.h> - -namespace Qnx { -namespace Internal { - -class BarDescriptorMagicMatcher : public Core::IMagicMatcher -{ -public: - BarDescriptorMagicMatcher(); - - bool matches(const QByteArray &data) const; - int priority() const; -}; - -} // namespace Internal -} // namespace Qnx - -#endif // QNX_INTERNAL_BARDESCRIPTORMAGICMATCHER_H diff --git a/src/plugins/qnx/qnx.pro b/src/plugins/qnx/qnx.pro index b032446f88..94b7092b6c 100644 --- a/src/plugins/qnx/qnx.pro +++ b/src/plugins/qnx/qnx.pro @@ -50,7 +50,6 @@ SOURCES += qnxplugin.cpp \ blackberryabstractdeploystep.cpp \ blackberryndksettingswidget.cpp \ blackberryndksettingspage.cpp \ - bardescriptormagicmatcher.cpp \ bardescriptoreditorfactory.cpp \ bardescriptoreditor.cpp \ bardescriptoreditorwidget.cpp \ @@ -161,7 +160,6 @@ HEADERS += qnxplugin.h\ blackberryabstractdeploystep.h \ blackberryndksettingswidget.h \ blackberryndksettingspage.h \ - bardescriptormagicmatcher.h \ bardescriptoreditorfactory.h \ bardescriptoreditor.h \ bardescriptoreditorwidget.h \ diff --git a/src/plugins/qnx/qnx.qrc b/src/plugins/qnx/qnx.qrc index 16047a4125..4f87659716 100644 --- a/src/plugins/qnx/qnx.qrc +++ b/src/plugins/qnx/qnx.qrc @@ -4,6 +4,6 @@ <file>images/target.png</file> <file>images/ok.png</file> <file>images/qnx-target.png</file> + <file>Qnx.mimetypes.xml</file> </qresource> - <qresource prefix="/"/> </RCC> diff --git a/src/plugins/qnx/qnxplugin.cpp b/src/plugins/qnx/qnxplugin.cpp index 10caf0d2c4..82055c72ac 100644 --- a/src/plugins/qnx/qnxplugin.cpp +++ b/src/plugins/qnx/qnxplugin.cpp @@ -51,7 +51,6 @@ #include "blackberryndksettingspage.h" #include "qnxsettingspage.h" #include "bardescriptoreditorfactory.h" -#include "bardescriptormagicmatcher.h" #include "blackberrykeyspage.h" #include "blackberrycheckdevicestatusstepfactory.h" #include "blackberrydeviceconnectionmanager.h" @@ -68,12 +67,12 @@ #include <coreplugin/actionmanager/actionmanager.h> #include <coreplugin/coreconstants.h> #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/kitinformation.h> #include <projectexplorer/projectexplorer.h> #include <projectexplorer/projectexplorerconstants.h> #include <projectexplorer/taskhub.h> #include <projectexplorer/kitmanager.h> +#include <utils/mimetypes/mimedatabase.h> #include <QAction> #include <QtPlugin> @@ -128,19 +127,8 @@ bool QnxPlugin::initialize(const QStringList &arguments, QString *errorString) // Handle Qcc Compiler addAutoReleasedObject(new QnxToolChainFactory); - // bar-descriptor.xml editor - Core::MimeGlobPattern barDescriptorGlobPattern(QLatin1String("*.xml"), Core::MimeGlobPattern::MinWeight + 1); - Core::MimeType barDescriptorMimeType; - barDescriptorMimeType.setType(QLatin1String(Constants::QNX_BAR_DESCRIPTOR_MIME_TYPE)); - barDescriptorMimeType.setComment(tr("BAR descriptor file (BlackBerry)")); - barDescriptorMimeType.setGlobPatterns(QList<Core::MimeGlobPattern>() << barDescriptorGlobPattern); - barDescriptorMimeType.addMagicMatcher(QSharedPointer<Core::IMagicMatcher>(new BarDescriptorMagicMatcher)); - barDescriptorMimeType.setSubClassesOf(QStringList() << QLatin1String("application/xml")); - - if (!Core::MimeDatabase::addMimeType(barDescriptorMimeType)) { - *errorString = tr("Could not add MIME type for bar-descriptor.xml editor."); - return false; - } + Utils::MimeDatabase::addMimeTypes(QLatin1String(":qnx/Qnx.mimetypes.xml")); + addAutoReleasedObject(new BarDescriptorEditorFactory); connect(KitManager::instance(), SIGNAL(kitsLoaded()), diff --git a/src/plugins/qtsupport/QtSupport.mimetypes.xml b/src/plugins/qtsupport/QtSupport.mimetypes.xml deleted file mode 100644 index 8737bdfbab..0000000000 --- a/src/plugins/qtsupport/QtSupport.mimetypes.xml +++ /dev/null @@ -1,8 +0,0 @@ -<?xml version="1.0"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="application/x-linguist"> - <sub-class-of type="application/xml"/> - <comment>message catalog</comment> - <glob pattern="*.ts"/> - </mime-type> -</mime-info> diff --git a/src/plugins/qtsupport/qtsupport.qrc b/src/plugins/qtsupport/qtsupport.qrc index e97078e35b..02b4ae2851 100644 --- a/src/plugins/qtsupport/qtsupport.qrc +++ b/src/plugins/qtsupport/qtsupport.qrc @@ -8,6 +8,5 @@ <file>images/dark_qml.png</file> <file>images/dark_qt_project.png</file> <file>images/dark_qt_qrc.png</file> - <file>QtSupport.mimetypes.xml</file> </qresource> </RCC> diff --git a/src/plugins/qtsupport/qtsupportplugin.cpp b/src/plugins/qtsupport/qtsupportplugin.cpp index 902f1d58f8..7fdcea8b4d 100644 --- a/src/plugins/qtsupport/qtsupportplugin.cpp +++ b/src/plugins/qtsupport/qtsupportplugin.cpp @@ -45,7 +45,6 @@ #include "profilereader.h" #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/jsexpander.h> #include <projectexplorer/project.h> @@ -70,9 +69,6 @@ bool QtSupportPlugin::initialize(const QStringList &arguments, QString *errorMes ProFileEvaluator::initialize(); new ProFileCacheManager(this); - if (!MimeDatabase::addMimeTypes(QLatin1String(":qtsupport/QtSupport.mimetypes.xml"), errorMessage)) - return false; - JsExpander::registerQObjectForJs(QLatin1String("QtSupport"), new CodeGenerator); addAutoReleasedObject(new QtVersionManager); diff --git a/src/plugins/resourceeditor/resourceeditorplugin.cpp b/src/plugins/resourceeditor/resourceeditorplugin.cpp index 90361b2463..df4d22a295 100644 --- a/src/plugins/resourceeditor/resourceeditorplugin.cpp +++ b/src/plugins/resourceeditor/resourceeditorplugin.cpp @@ -36,7 +36,6 @@ #include "resourcenode.h" #include <coreplugin/icore.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/coreconstants.h> #include <coreplugin/documentmanager.h> #include <coreplugin/id.h> @@ -50,6 +49,7 @@ #include <projectexplorer/projectnodes.h> #include <extensionsystem/pluginmanager.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/parameteraction.h> #include <utils/qtcassert.h> @@ -124,14 +124,12 @@ ResourceEditorPlugin::ResourceEditorPlugin() : bool ResourceEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) - if (!Core::MimeDatabase::addMimeTypes(QLatin1String(":/resourceeditor/ResourceEditor.mimetypes.xml"), errorMessage)) - return false; + Q_UNUSED(errorMessage) + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/resourceeditor/ResourceEditor.mimetypes.xml")); ResourceEditorFactory *editor = new ResourceEditorFactory(this); addAutoReleasedObject(editor); - errorMessage->clear(); - // Register undo and redo const Core::Context context(Constants::C_RESOURCEEDITOR); m_undoAction = new QAction(tr("&Undo"), this); diff --git a/src/plugins/resourceeditor/resourcenode.cpp b/src/plugins/resourceeditor/resourcenode.cpp index 96ed4ea5cc..d2dcb5fd23 100644 --- a/src/plugins/resourceeditor/resourcenode.cpp +++ b/src/plugins/resourceeditor/resourcenode.cpp @@ -36,10 +36,11 @@ #include <coreplugin/documentmanager.h> #include <coreplugin/fileiconprovider.h> -#include <coreplugin/mimedatabase.h> #include <qmljstools/qmljstoolsconstants.h> +#include <utils/mimetypes/mimedatabase.h> + #include <QCoreApplication> #include <QDir> #include <QDebug> @@ -51,8 +52,8 @@ static bool priority(const QStringList &files) { if (files.isEmpty()) return false; - Core::MimeType mt = Core::MimeDatabase::findByFile(files.at(0)); - QString type = mt.type(); + Utils::MimeDatabase mdb; + QString type = mdb.mimeTypeForFile(files.at(0)).name(); if (type.startsWith(QLatin1String("image/")) || type == QLatin1String(QmlJSTools::Constants::QML_MIMETYPE) || type == QLatin1String(QmlJSTools::Constants::JS_MIMETYPE)) diff --git a/src/plugins/subversion/subversionplugin.cpp b/src/plugins/subversion/subversionplugin.cpp index 0993c65efd..da2862c204 100644 --- a/src/plugins/subversion/subversionplugin.cpp +++ b/src/plugins/subversion/subversionplugin.cpp @@ -57,10 +57,10 @@ #include <coreplugin/id.h> #include <coreplugin/locator/commandlocator.h> #include <coreplugin/messagemanager.h> -#include <coreplugin/mimedatabase.h> #include <utils/fileutils.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/parameteraction.h> #include <utils/qtcassert.h> #include <utils/synchronousprocess.h> @@ -233,6 +233,7 @@ const VcsBaseSubmitEditorParameters submitParameters = { bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *errorMessage) { + Q_UNUSED(errorMessage) using namespace Constants; using namespace Core::Constants; @@ -242,8 +243,7 @@ bool SubversionPlugin::initialize(const QStringList & /*arguments */, QString *e m_subversionPluginInstance = this; - if (!MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":/trolltech.subversion/Subversion.mimetypes.xml")); m_settings.readSettings(ICore::settings()); m_client = new SubversionClient(&m_settings); diff --git a/src/plugins/tasklist/tasklistplugin.cpp b/src/plugins/tasklist/tasklistplugin.cpp index 9d2e01d661..a272b07dca 100644 --- a/src/plugins/tasklist/tasklistplugin.cpp +++ b/src/plugins/tasklist/tasklistplugin.cpp @@ -37,12 +37,12 @@ #include <coreplugin/icore.h> #include <coreplugin/idocumentfactory.h> #include <coreplugin/documentmanager.h> -#include <coreplugin/mimedatabase.h> #include <projectexplorer/projecttree.h> #include <projectexplorer/project.h> #include <projectexplorer/session.h> #include <projectexplorer/task.h> #include <projectexplorer/taskhub.h> +#include <utils/mimetypes/mimedatabase.h> #include <QDir> #include <QMessageBox> @@ -199,12 +199,12 @@ TaskListPlugin::TaskListPlugin() bool TaskListPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) + Q_UNUSED(errorMessage) //: Category under which tasklist tasks are listed in Issues view TaskHub::addCategory(Constants::TASKLISTTASK_ID, tr("My Tasks")); - if (!MimeDatabase::addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml"), errorMessage)) - return false; + Utils::MimeDatabase::addMimeTypes(QLatin1String(":tasklist/TaskList.mimetypes.xml")); m_fileFactory = new IDocumentFactory; m_fileFactory->addMimeType(QLatin1String("text/x-tasklist")); diff --git a/src/plugins/texteditor/TextEditor.mimetypes.xml b/src/plugins/texteditor/TextEditor.mimetypes.xml deleted file mode 100644 index 2431241c2e..0000000000 --- a/src/plugins/texteditor/TextEditor.mimetypes.xml +++ /dev/null @@ -1,29 +0,0 @@ -<?xml version="1.0"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="text/plain"> - <comment>Plain text document</comment> - <sub-class-of type="application/octet-stream"/> - <glob pattern="*.txt"/> - </mime-type> - <mime-type type="application/xml"> - <alias type="text/xml"/> - <sub-class-of type="text/plain"/> - <comment>XML document</comment> - <glob pattern="*.xml" weight="50"/><!-- reduce weight to allow application/vnd.rim.qnx.bar_descriptor to override by content --> - <glob pattern="*.xsl"/> - <glob pattern="*.xslt"/> - <glob pattern="*.xbl"/> - <alias type="text/xml"/> - </mime-type> - <mime-type type="text/x-asm"> - <sub-class-of type="text/plain"/> - <comment>Assembler</comment> - <glob pattern="*.asm"/> - </mime-type> - <!-- Catch-all for assemblers --> - <mime-type type="text/x-qtcreator-generic-asm"> - <sub-class-of type="text/x-asm"/> - <comment>Qt Creator Generic Assembler</comment> - <glob pattern="*.asm"/> - </mime-type> -</mime-info> diff --git a/src/plugins/texteditor/generichighlighter/manager.cpp b/src/plugins/texteditor/generichighlighter/manager.cpp index 08dc24856b..f625450999 100644 --- a/src/plugins/texteditor/generichighlighter/manager.cpp +++ b/src/plugins/texteditor/generichighlighter/manager.cpp @@ -43,6 +43,7 @@ #include <coreplugin/progressmanager/progressmanager.h> #include <utils/algorithm.h> #include <utils/QtConcurrentTools> +#include <utils/mimetypes/mimedatabase.h> #include <utils/networkaccessmanager.h> #include <QCoreApplication> @@ -150,18 +151,19 @@ static bool matchesPattern(const QString &fileName, DefinitionMetaDataPtr metaDa return false; } -QString Manager::definitionIdByMimeType(const Core::MimeType &mimeType) const +QString Manager::definitionIdByMimeType(const Utils::MimeType &mimeType) const { - QList<Core::MimeType> queue; + Utils::MimeDatabase mdb; + QList<Utils::MimeType> queue; queue.append(mimeType); while (!queue.isEmpty()) { - const Core::MimeType mt = queue.takeFirst(); - const QString id = m_register.m_idByMimeType.value(mt.type()); + const Utils::MimeType mt = queue.takeFirst(); + const QString id = m_register.m_idByMimeType.value(mt.name()); if (!id.isEmpty()) return id; - foreach (const QString &parent, mt.subClassesOf()) { - const Core::MimeType parentMt = Core::MimeDatabase::findByType(parent); - if (!parentMt.isNull()) + foreach (const QString &parent, mt.parentMimeTypes()) { + const Utils::MimeType parentMt = mdb.mimeTypeForName(parent); + if (parentMt.isValid()) queue.append(parentMt); } } @@ -186,7 +188,8 @@ QString Manager::definitionIdByFile(const QString &filePath) const return bestId; } -QString Manager::definitionIdByMimeTypeAndFile(const MimeType &mimeType, const QString &filePath) const +QString Manager::definitionIdByMimeTypeAndFile(const Utils::MimeType &mimeType, + const QString &filePath) const { QString id = definitionIdByMimeType(mimeType); if (!filePath.isEmpty()) { diff --git a/src/plugins/texteditor/generichighlighter/manager.h b/src/plugins/texteditor/generichighlighter/manager.h index 4105f65b64..22de4bbf42 100644 --- a/src/plugins/texteditor/generichighlighter/manager.h +++ b/src/plugins/texteditor/generichighlighter/manager.h @@ -33,8 +33,6 @@ #include "highlightdefinitionmetadata.h" -#include <coreplugin/mimedatabase.h> - #include <QString> #include <QHash> #include <QSet> @@ -51,6 +49,8 @@ class QIODevice; template <class> class QFutureInterface; QT_END_NAMESPACE +namespace Utils { class MimeType; } + namespace TextEditor { namespace Internal { @@ -69,9 +69,9 @@ public: static Manager *instance(); QString definitionIdByName(const QString &name) const; - QString definitionIdByMimeType(const Core::MimeType &mimeType) const; + QString definitionIdByMimeType(const Utils::MimeType &mimeType) const; QString definitionIdByFile(const QString &filePath) const; - QString definitionIdByMimeTypeAndFile(const Core::MimeType &mimeType, + QString definitionIdByMimeTypeAndFile(const Utils::MimeType &mimeType, const QString &filePath) const; DefinitionMetaDataPtr availableDefinitionByName(const QString &name) const; diff --git a/src/plugins/texteditor/highlighterutils.cpp b/src/plugins/texteditor/highlighterutils.cpp index 2c0dc7b6fa..57b1dd8577 100644 --- a/src/plugins/texteditor/highlighterutils.cpp +++ b/src/plugins/texteditor/highlighterutils.cpp @@ -33,11 +33,12 @@ #include "generichighlighter/highlightdefinition.h" #include "generichighlighter/manager.h" #include <coreplugin/icore.h> +#include <utils/mimetypes/mimetype.h> using namespace TextEditor; using namespace Internal; -void TextEditor::setMimeTypeForHighlighter(Highlighter *highlighter, const Core::MimeType &mimeType, +void TextEditor::setMimeTypeForHighlighter(Highlighter *highlighter, const Utils::MimeType &mimeType, const QString &filePath, QString *foundDefinitionId) { QString definitionId = Manager::instance()->definitionIdByMimeTypeAndFile(mimeType, filePath); diff --git a/src/plugins/texteditor/highlighterutils.h b/src/plugins/texteditor/highlighterutils.h index 0d9a9b0942..683b98ca2e 100644 --- a/src/plugins/texteditor/highlighterutils.h +++ b/src/plugins/texteditor/highlighterutils.h @@ -38,13 +38,13 @@ * but due to a very hackish test of that generic highlighter, * there functions must be outside. */ -namespace Core { class MimeType; } +namespace Utils { class MimeType; } namespace TextEditor { class Highlighter; -void setMimeTypeForHighlighter(Highlighter *highlighter, const Core::MimeType &mimeType, +void setMimeTypeForHighlighter(Highlighter *highlighter, const Utils::MimeType &mimeType, const QString &filePath, QString *foundDefinitionId = 0); diff --git a/src/plugins/texteditor/texteditor.cpp b/src/plugins/texteditor/texteditor.cpp index 56adaf2829..632bb1c18c 100644 --- a/src/plugins/texteditor/texteditor.cpp +++ b/src/plugins/texteditor/texteditor.cpp @@ -74,6 +74,7 @@ #include <utils/linecolumnlabel.h> #include <utils/fileutils.h> #include <utils/hostosinfo.h> +#include <utils/mimetypes/mimedatabase.h> #include <utils/qtcassert.h> #include <utils/stylehelper.h> #include <utils/tooltip/tooltip.h> @@ -2735,7 +2736,8 @@ void TextEditorWidgetPrivate::updateCodeFoldingVisible() void TextEditorWidgetPrivate::reconfigure() { - m_document->setMimeType(MimeDatabase::findByFile(m_document->filePath().toString()).type()); + Utils::MimeDatabase mdb; + m_document->setMimeType(mdb.mimeTypeForFile(m_document->filePath().toString()).name()); q->configureGenericHighlighter(); } @@ -7109,7 +7111,8 @@ bool BaseTextEditor::open(QString *errorString, const QString &fileName, const Q { if (!editorWidget()->open(errorString, fileName, realFileName)) return false; - textDocument()->setMimeType(MimeDatabase::findByFile(QFileInfo(fileName)).type()); + Utils::MimeDatabase mdb; + textDocument()->setMimeType(mdb.mimeTypeForFile(fileName).name()); return true; } @@ -7173,8 +7176,9 @@ void TextEditorWidget::configureGenericHighlighter() setCodeFoldingSupported(false); const QString type = textDocument()->mimeType(); - const MimeType mimeType = MimeDatabase::findByType(type); - if (!mimeType.isNull()) { + Utils::MimeDatabase mdb; + const Utils::MimeType mimeType = mdb.mimeTypeForName(type); + if (mimeType.isValid()) { d->m_isMissingSyntaxDefinition = true; QString definitionId; diff --git a/src/plugins/texteditor/texteditor.h b/src/plugins/texteditor/texteditor.h index 6634cd2b23..1ba72e2b36 100644 --- a/src/plugins/texteditor/texteditor.h +++ b/src/plugins/texteditor/texteditor.h @@ -59,8 +59,6 @@ class QRect; class QTextBlock; QT_END_NAMESPACE -namespace Core { class MimeType; } - namespace TextEditor { class BaseHoverHandler; diff --git a/src/plugins/texteditor/texteditor.qrc b/src/plugins/texteditor/texteditor.qrc index 49b0b46325..c58205cd2c 100644 --- a/src/plugins/texteditor/texteditor.qrc +++ b/src/plugins/texteditor/texteditor.qrc @@ -2,7 +2,6 @@ <qresource prefix="/texteditor"> <file>images/finddocuments.png</file> <file>images/finddirectory.png</file> - <file>TextEditor.mimetypes.xml</file> <file>images/refactormarker.png</file> <file>images/snippet.png</file> <file>images/f1.png</file> diff --git a/src/plugins/texteditor/texteditorplugin.cpp b/src/plugins/texteditor/texteditorplugin.cpp index efa8d8b4bd..88ac6b4469 100644 --- a/src/plugins/texteditor/texteditorplugin.cpp +++ b/src/plugins/texteditor/texteditorplugin.cpp @@ -91,9 +91,7 @@ TextEditorPlugin::~TextEditorPlugin() bool TextEditorPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) - - if (!MimeDatabase::addMimeTypes(QLatin1String(":/texteditor/TextEditor.mimetypes.xml"), errorMessage)) - return false; + Q_UNUSED(errorMessage) m_settings = new TextEditorSettings(this); diff --git a/src/plugins/vcsbase/VcsBase.mimetypes.xml b/src/plugins/vcsbase/VcsBase.mimetypes.xml deleted file mode 100644 index 3b48f22206..0000000000 --- a/src/plugins/vcsbase/VcsBase.mimetypes.xml +++ /dev/null @@ -1,17 +0,0 @@ -<?xml version="1.0"?> -<mime-info xmlns='http://www.freedesktop.org/standards/shared-mime-info'> - <mime-type type="text/x-patch"> - <sub-class-of type="text/plain"/> - <comment>Differences between files</comment> - <glob pattern="*.patch"/> - <glob pattern="*.diff"/> - <!-- Find unified diffs from code pasting utilities by checking for "+++ foo.cpp" - Note that this must have a higher priority than any content - rule for C++ as we want diffs to take preference when looking - at a C++ patch. - --> - <magic priority="60"> - <match value="
+++ " type="string" offset="0:10000"/> - </magic> - </mime-type> -</mime-info> diff --git a/src/plugins/vcsbase/vcsbase.qrc b/src/plugins/vcsbase/vcsbase.qrc index baec4aed45..4234890c3a 100644 --- a/src/plugins/vcsbase/vcsbase.qrc +++ b/src/plugins/vcsbase/vcsbase.qrc @@ -1,6 +1,5 @@ <RCC> - <qresource prefix="/vcsbase" > - <file>VcsBase.mimetypes.xml</file> + <qresource prefix="/vcsbase"> <file>images/category_vcs.png</file> <file>images/diff.png</file> <file>images/removesubmitfield.png</file> diff --git a/src/plugins/vcsbase/vcsplugin.cpp b/src/plugins/vcsbase/vcsplugin.cpp index 645a6d2702..a70794ad41 100644 --- a/src/plugins/vcsbase/vcsplugin.cpp +++ b/src/plugins/vcsbase/vcsplugin.cpp @@ -41,7 +41,6 @@ #include <coreplugin/iversioncontrol.h> #include <coreplugin/jsexpander.h> -#include <coreplugin/mimedatabase.h> #include <coreplugin/vcsmanager.h> #include <projectexplorer/jsonwizard/jsonwizardfactory.h> @@ -77,9 +76,7 @@ VcsPlugin::~VcsPlugin() bool VcsPlugin::initialize(const QStringList &arguments, QString *errorMessage) { Q_UNUSED(arguments) - - if (!MimeDatabase::addMimeTypes(QLatin1String(":/vcsbase/VcsBase.mimetypes.xml"), errorMessage)) - return false; + Q_UNUSED(errorMessage) m_coreListener = new CoreListener; addAutoReleasedObject(m_coreListener); |