Пример #1
0
static QMimeType mimeType(const QString &name, const QString& fallback)
{
    QMimeDatabase mime;
    QMimeType type;
    if ( !name.isEmpty() )
        type = mime.mimeTypeForName(name);
    if ( !type.isValid() && fallback != name )
        type = mime.mimeTypeForName(fallback);
    return type;
}
Пример #2
0
void tst_QMimeDatabase::inheritsPerformance()
{
    // Check performance of inherits().
    // This benchmark (which started in 2009 in kmimetypetest.cpp) uses 40 mimetypes.
    QStringList mimeTypes;
    mimeTypes << QLatin1String("image/jpeg") << QLatin1String("image/png") << QLatin1String("image/tiff") << QLatin1String("text/plain") << QLatin1String("text/html");
    mimeTypes += mimeTypes;
    mimeTypes += mimeTypes;
    mimeTypes += mimeTypes;
    QCOMPARE(mimeTypes.count(), 40);
    QMimeDatabase db;
    QMimeType mime = db.mimeTypeForName(QString::fromLatin1("text/x-chdr"));
    QVERIFY(mime.isValid());
    QBENCHMARK {
        QString match;
        foreach (const QString &mt, mimeTypes) {
            if (mime.inherits(mt)) {
                match = mt;
                // of course there would normally be a "break" here, but we're testing worse-case
                // performance here
            }
        }
        QCOMPARE(match, QString::fromLatin1("text/plain"));
    }
    // Numbers from 2011, in release mode:
    // KDE 4.7 numbers: 0.21 msec / 494,000 ticks / 568,345 instr. loads per iteration
    // QMimeBinaryProvider (with Qt 5): 0.16 msec / NA / 416,049 instr. reads per iteration
    // QMimeXmlProvider (with Qt 5): 0.062 msec / NA / 172,889 instr. reads per iteration
    //   (but the startup time is way higher)
    // And memory usage is flat at 200K with QMimeBinaryProvider, while it peaks at 6 MB when
    // parsing XML, and then keeps being around 4.5 MB for all the in-memory hashes.
}
Пример #3
0
QMimeType KFileItem::determineMimeType() const
{
    if (!d) {
        return QMimeType();
    }

    if (!d->m_mimeType.isValid() || !d->m_bMimeTypeKnown) {
        QMimeDatabase db;
        if (isDir()) {
            d->m_mimeType = db.mimeTypeForName(QStringLiteral("inode/directory"));
        } else {
            bool isLocalUrl;
            const QUrl url = mostLocalUrl(&isLocalUrl);
            d->m_mimeType = db.mimeTypeForUrl(url);
            // was:  d->m_mimeType = KMimeType::findByUrl( url, d->m_fileMode, isLocalUrl );
            // => we are no longer using d->m_fileMode for remote URLs.
            Q_ASSERT(d->m_mimeType.isValid());
            //qDebug() << d << "finding final mimetype for" << url << ":" << d->m_mimeType.name();
        }
        d->m_bMimeTypeKnown = true;
    }

    if (d->m_delayedMimeTypes) { // if we delayed getting the iconName up till now, this is the right point in time to do so
        d->m_delayedMimeTypes = false;
        d->m_useIconNameCache = false;
        (void)iconName();
    }

    return d->m_mimeType;
}
Пример #4
0
bool MimeTypeChecker::isWantedCollection(const Collection &collection, const QString &wantedMimeType)
{
    if (wantedMimeType.isEmpty() || !collection.isValid()) {
        return false;
    }

    const QStringList contentMimeTypes = collection.contentMimeTypes();
    if (contentMimeTypes.isEmpty()) {
        return false;
    }

    foreach (const QString &mimeType, contentMimeTypes) {
        if (mimeType.isEmpty()) {
            continue;
        }

        if (mimeType == wantedMimeType) {
            return true;
        }

        QMimeDatabase db;
        const QMimeType mt = db.mimeTypeForName(mimeType);
        if (!mt.isValid()) {
            continue;
        }

        if (mt.inherits(wantedMimeType)) {
            return true;
        }
    }

    return false;
}
Пример #5
0
int main(int argc, char **argv)
{
    QApplication app(argc, argv);
    KLocalizedString::setApplicationDomain("fatcrm");

    KAboutData aboutData(QStringLiteral("fatcrm"), i18n("FatCRM"),
                     version, i18n(description),
                     KAboutLicense::GPL_V2, i18n("(C) 2010-2018 KDAB"),
                     QString(), QStringLiteral("*****@*****.**"));

    QCommandLineParser parser;
    KAboutData::setApplicationData(aboutData);
    parser.addVersionOption();
    parser.addHelpOption();
    QCommandLineOption noOverlayOption("nooverlay", i18n("Do not display the overlay during initial data loading"));
    parser.addOption(noOverlayOption);
    aboutData.setupCommandLine(&parser);
    parser.process(app);
    aboutData.processCommandLine(&parser);

    QMimeDatabase db;
    if (!db.mimeTypeForName("application/x-vnd.kdab.crm.opportunity").isValid()) {
        KMessageBox::error(nullptr, i18n("Mimetype application/x-vnd.kdab.crm.opportunity not found, please check your FatCRM installation"));
        return 1;
    }

    KDBusService service(KDBusService::Multiple);

    auto *window = new MainWindow(!parser.isSet(noOverlayOption));
    window->setAttribute(Qt::WA_DeleteOnClose);
    window->show();
    return app.exec();
}
Пример #6
0
static KServiceOfferList mimeTypeSycocaOffers(const QString& mimeType)
{
    KServiceOfferList lst;

    QMimeDatabase db;
    QString mime = db.mimeTypeForName(mimeType).name();
    if (mime.isEmpty()) {
        if (!mimeType.startsWith(QLatin1String("x-scheme-handler/"))) { // don't warn for unknown scheme handler mimetypes
            qWarning() << "KMimeTypeTrader: mimeType" << mimeType << "not found";
            return lst; // empty
        }
        mime = mimeType;
    }
    KMimeTypeFactory *factory = KMimeTypeFactory::self();
    const int offset = factory->entryOffset(mime);
    if (!offset) { // shouldn't happen, now that we know the mimetype exists
        if (!mimeType.startsWith(QLatin1String("x-scheme-handler/"))) // don't warn for unknown scheme handler mimetypes
            qDebug() << "KMimeTypeTrader: no entry offset for" << mimeType;
        return lst; // empty
    }

    const int serviceOffersOffset = factory->serviceOffersOffset(mime);
    if ( serviceOffersOffset > -1 ) {
        lst = KServiceFactory::self()->offers(offset, serviceOffersOffset);
    }
    return lst;
}
Пример #7
0
KFileItem::KFileItem(const QUrl &url, const QString &mimeType, mode_t mode)
    : d(new KFileItemPrivate(KIO::UDSEntry(), mode, KFileItem::Unknown,
                             url, false, false))
{
    d->m_bMimeTypeKnown = !mimeType.isEmpty();
    if (d->m_bMimeTypeKnown) {
        QMimeDatabase db;
        d->m_mimeType = db.mimeTypeForName(mimeType);
    }
}
Пример #8
0
Файл: paste.cpp Проект: KDE/kio
static QByteArray chooseFormatAndUrl(const QUrl &u, const QMimeData *mimeData,
                                     const QStringList &formats,
                                     const QString &text,
                                     const QString &suggestedFileName,
                                     QWidget *widget,
                                     bool clipboard,
                                     QUrl *newUrl)
{
    QMimeDatabase db;
    QStringList formatLabels;
    for (int i = 0; i < formats.size(); ++i) {
        const QString &fmt = formats[i];
        QMimeType mime = db.mimeTypeForName(fmt);
        if (mime.isValid()) {
            formatLabels.append(i18n("%1 (%2)", mime.comment(), fmt));
        } else {
            formatLabels.append(fmt);
        }
    }

    QString dialogText(text);
    if (dialogText.isEmpty()) {
        dialogText = i18n("Filename for clipboard content:");
    }
    //using QString() instead of QString::null didn't compile (with gcc 3.2.3), because the ctor was mistaken as a function declaration, Alex //krazy:exclude=nullstrassign
    KIO::PasteDialog dlg(QString::null, dialogText, suggestedFileName, formatLabels, widget, clipboard);   //krazy:exclude=nullstrassign

    if (dlg.exec() != QDialog::Accepted) {
        return QByteArray();
    }

    if (clipboard && dlg.clipboardChanged()) {
        KMessageBox::sorry(widget,
                           i18n("The clipboard has changed since you used 'paste': "
                                "the chosen data format is no longer applicable. "
                                "Please copy again what you wanted to paste."));
        return QByteArray();
    }

    const QString result = dlg.lineEditText();
    const QString chosenFormat = formats[ dlg.comboItem() ];

    //qDebug() << " result=" << result << " chosenFormat=" << chosenFormat;
    *newUrl = u;
    newUrl->setPath(newUrl->path() + '/' + result);
    // In Qt3, the result of clipboard()->mimeData() only existed until the next
    // event loop run (see dlg.exec() above), so we re-fetched it.
    // TODO: This should not be necessary with Qt5; remove this conditional
    // and test that it still works.
    if (clipboard) {
        mimeData = QApplication::clipboard()->mimeData();
    }
    const QByteArray ba = mimeData->data(chosenFormat);
    return ba;
}
Пример #9
0
KoDocumentInfoDlg::KoDocumentInfoDlg(QWidget* parent, KoDocumentInfo* docInfo)
    : KPageDialog(parent)
    , d(new KoDocumentInfoDlgPrivate)
{
    d->info = docInfo;

    setWindowTitle(i18n("Document Information"));
//    setInitialSize(QSize(500, 500));
    setFaceType(KPageDialog::List);
    setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
    button(QDialogButtonBox::Ok)->setDefault(true);

    d->aboutUi = new Ui::KoDocumentInfoAboutWidget();
    QWidget *infodlg = new QWidget();
    d->aboutUi->setupUi(infodlg);
    d->aboutUi->cbLanguage->addItems(KoGlobal::listOfLanguages());
    d->aboutUi->cbLanguage->setCurrentIndex(-1);

    KPageWidgetItem *page = new KPageWidgetItem(infodlg, i18n("General"));
    page->setHeader(i18n("General"));

    // Ugly hack, the mimetype should be a parameter, instead
    KoDocumentBase* doc = dynamic_cast< KoDocumentBase* >(d->info->parent());
    if (doc) {
        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForName(doc->mimeType());
        if (mime.isValid()) {
            page->setIcon(KisIconUtils::loadIcon(mime.iconName()));
        }
    } else {
        // hide all entries not used in pages for KoDocumentInfoPropsPage
        d->aboutUi->filePathInfoLabel->setVisible(false);
        d->aboutUi->filePathLabel->setVisible(false);
        d->aboutUi->filePathSeparatorLine->setVisible(false);
        d->aboutUi->lblTypeDesc->setVisible(false);
        d->aboutUi->lblType->setVisible(false);
    }
    addPage(page);
    d->pages.append(page);

    initAboutTab();

    d->authorUi = new Ui::KoDocumentInfoAuthorWidget();
    QWidget *authordlg = new QWidget();
    d->authorUi->setupUi(authordlg);
    page = new KPageWidgetItem(authordlg, i18n("Author"));
    page->setHeader(i18n("Last saved by"));
    page->setIcon(koIcon("user-identity"));
    addPage(page);
    d->pages.append(page);

    initAuthorTab();
}
Пример #10
0
void InfoPanel::showMetaDataFor(const QModelIndex &index)
{
    showMetaData();

    const Archive::Entry *entry = m_model->entryForIndex(index);

    QMimeDatabase db;
    QMimeType mimeType;

    if (entry->isDir()) {
        mimeType = db.mimeTypeForName(QStringLiteral("inode/directory"));
    } else {
        mimeType = db.mimeTypeForFile(entry->fullPath(), QMimeDatabase::MatchExtension);
    }

    m_typeValueLabel->setText(mimeType.comment());

    if (!entry->property("owner").toString().isEmpty()) {
        m_ownerLabel->show();
        m_ownerValueLabel->show();
        m_ownerValueLabel->setText(entry->property("owner").toString());
    } else {
        m_ownerLabel->hide();
        m_ownerValueLabel->hide();
    }

    if (!entry->property("group").toString().isEmpty()) {
        m_groupLabel->show();
        m_groupValueLabel->show();
        m_groupValueLabel->setText(entry->property("group").toString());
    } else {
        m_groupLabel->hide();
        m_groupValueLabel->hide();
    }

    if (!entry->property("link").toString().isEmpty()) {
        m_targetLabel->show();
        m_targetValueLabel->show();
        m_targetValueLabel->setText(entry->property("link").toString());
    } else {
        m_targetLabel->hide();
        m_targetValueLabel->hide();
    }

    if (entry->property("isPasswordProtected").toBool()) {
        m_passwordLabel->show();
        m_passwordValueLabel->show();
    } else {
        m_passwordLabel->hide();
        m_passwordValueLabel->hide();
    }
}
QStringList DBusFileDialogManager::globPatternsForMime(const QString &mimeType) const
{
    QMimeDatabase db;
    QMimeType mime(db.mimeTypeForName(mimeType));
    if (mime.isValid()) {
        if (mime.isDefault()) {
            return QStringList(QStringLiteral("*"));
        } else {
            return mime.globPatterns();
        }
    }
    return QStringList();
}
Пример #12
0
void tst_QMimeDatabase::mimeTypeForName()
{
    QMimeDatabase db;
    QMimeType s0 = db.mimeTypeForName(QString::fromLatin1("application/x-zerosize"));
    QVERIFY(s0.isValid());
    QCOMPARE(s0.name(), QString::fromLatin1("application/x-zerosize"));
    QCOMPARE(s0.comment(), QString::fromLatin1("empty document"));

    QMimeType s0Again = db.mimeTypeForName(QString::fromLatin1("application/x-zerosize"));
    QCOMPARE(s0Again.name(), s0.name());

    QMimeType s1 = db.mimeTypeForName(QString::fromLatin1("text/plain"));
    QVERIFY(s1.isValid());
    QCOMPARE(s1.name(), QString::fromLatin1("text/plain"));
    //qDebug("Comment is %s", qPrintable(s1.comment()));

    QMimeType krita = db.mimeTypeForName(QString::fromLatin1("application/x-krita"));
    QVERIFY(krita.isValid());

    // Test <comment> parsing with application/rdf+xml which has the english comment after the other ones
    QMimeType rdf = db.mimeTypeForName(QString::fromLatin1("application/rdf+xml"));
    QVERIFY(rdf.isValid());
    QCOMPARE(rdf.comment(), QString::fromLatin1("RDF file"));

    QMimeType bzip2 = db.mimeTypeForName(QString::fromLatin1("application/x-bzip2"));
    QVERIFY(bzip2.isValid());
    QCOMPARE(bzip2.comment(), QString::fromLatin1("Bzip archive"));

    QMimeType defaultMime = db.mimeTypeForName(QString::fromLatin1("application/octet-stream"));
    QVERIFY(defaultMime.isValid());
    QVERIFY(defaultMime.isDefault());

    QMimeType doesNotExist = db.mimeTypeForName(QString::fromLatin1("foobar/x-doesnot-exist"));
    QVERIFY(!doesNotExist.isValid());

    // TODO move to findByFile
#ifdef Q_OS_LINUX
    QString exePath = QStandardPaths::findExecutable(QLatin1String("ls"));
    if (exePath.isEmpty())
        qWarning() << "ls not found";
    else {
        const QString executableType = QString::fromLatin1("application/x-executable");
        //QTest::newRow("executable") << exePath << executableType;
        QCOMPARE(db.mimeTypeForFile(exePath).name(), executableType);
    }
#endif

}
Пример #13
0
QString vfile::vfile_getIcon()
{
    if (vfile_icon.isEmpty()) {
        QString mime = vfile_getMime();
        if (vfile_isBrokenLink())
            vfile_icon = "file-broken";
        else if (vfile_icon.isEmpty()) {
            QMimeDatabase db;
            QMimeType mt = db.mimeTypeForName(mime);
            vfile_icon = mt.isValid() ? mt.iconName() : "file-broken";
        }
    }
    return vfile_icon;
}
Пример #14
0
const QImage ThumbnailProtocol::getIcon()
{
    const QMimeDatabase db;

    ///@todo Can we really do this? It doesn't seem to respect the size
    if (!m_iconDict.contains(m_mimeType)) { // generate it
        QImage icon(KIconLoader::global()->loadMimeTypeIcon(db.mimeTypeForName(m_mimeType).iconName(), KIconLoader::Desktop, m_iconSize).toImage());
        icon = icon.convertToFormat(QImage::Format_ARGB32);
        m_iconDict.insert(m_mimeType, icon);

        return icon;
    }

    return m_iconDict.value(m_mimeType);
}
Пример #15
0
/** ***************************************************************************/
Files::Extension::Extension()
    : Core::Extension("org.albert.extension.files"),
      Core::QueryHandler(Core::Extension::id),
      d(new FilesPrivate(this)) {

    // Load settings
    QSettings s(qApp->applicationName());
    s.beginGroup(Core::Extension::id);
    d->indexSettings.filters =  s.value(CFG_FILTERS, DEF_FILTERS).toStringList();
    d->indexSettings.indexHidden = s.value(CFG_INDEX_HIDDEN, DEF_INDEX_HIDDEN).toBool();
    d->indexSettings.followSymlinks = s.value(CFG_FOLLOW_SYMLINKS, DEF_FOLLOW_SYMLINKS).toBool();
    d->offlineIndex.setFuzzy(s.value(CFG_FUZZY, DEF_FUZZY).toBool());
    d->indexIntervalTimer.setInterval(s.value(CFG_SCAN_INTERVAL, DEF_SCAN_INTERVAL).toInt()*60000); // Will be started in the initial index update
    d->indexSettings.rootDirs = s.value(CFG_PATHS).toStringList();
    if (d->indexSettings.rootDirs.isEmpty())
        restorePaths();
    s.endGroup();

    // Deserialize data
    QFile file(QDir(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).
                   filePath(QString("%1.txt").arg(Core::Extension::id)));
    if (file.exists()) {
        if (file.open(QIODevice::ReadOnly| QIODevice::Text)) {
            qDebug() << qPrintable(QString("Deserializing files from '%1'.").arg(file.fileName()));
            QTextStream in(&file);
            QMimeDatabase mimedatabase;
            while (!in.atEnd())
                d->index.emplace_back(new File(in.readLine(), mimedatabase.mimeTypeForName(in.readLine())));
            file.close();

            // Build the offline index
            for (const auto &item : d->index)
                d->offlineIndex.add(item);
        } else
            qWarning() << qPrintable(QString("Could not read from file '%1': %2").arg(file.fileName(), file.errorString()));
    }

    // Index timer
    connect(&d->indexIntervalTimer, &QTimer::timeout, this, &Extension::updateIndex);

    // If the root dirs change write it to the settings
    connect(this, &Extension::rootDirsChanged, [this](const QStringList& dirs){
        QSettings(qApp->applicationName()).setValue(QString("%1/%2").arg(Core::Extension::id, CFG_PATHS), dirs);
    });

    // Trigger an initial update
    updateIndex();
}
Пример #16
0
KisFilterChooser::KisFilterChooser(QWidget *parent, const QStringList &mimeTypes, const QString &/*nativeFormat*/, const QUrl &url)
        : KoDialog(parent),
        m_mimeTypes(mimeTypes)
{
    setObjectName("kofilterchooser");
    setInitialSize(QSize(300, 350));
    setButtons(KoDialog::Ok|KoDialog::Cancel);
    setDefaultButton(KoDialog::Ok);
    setCaption(i18n("Choose Filter"));
    setModal(true);

    QWidget *page = new QWidget(this);
    setMainWidget(page);

    QVBoxLayout *layout = new QVBoxLayout(page);
    if (url.isValid()) {
        KSqueezedTextLabel *l = new KSqueezedTextLabel(url.path(), page);
        layout->addWidget(l);
    }
    m_filterList = new QListWidget(page);
    layout->addWidget(m_filterList);
    page->setLayout(layout);

    Q_ASSERT(!m_mimeTypes.isEmpty());
    for (QStringList::ConstIterator it = m_mimeTypes.constBegin();
            it != m_mimeTypes.constEnd();
            ++it) {

        QMimeDatabase db;
        QMimeType mime = db.mimeTypeForName(*it);
        const QString name = mime.isValid() ? mime.comment() : *it;
        if (! name.isEmpty()) {
            QListWidgetItem *item = new QListWidgetItem(name, m_filterList);
            item->setData(32, *it);
        }
    }

    m_filterList->sortItems();

    if (m_filterList->currentRow() == -1)
        m_filterList->setCurrentRow(0);

    m_filterList->setFocus();

    connect(m_filterList, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(accept()));
    resize(QSize(520, 400));//.expandedTo(minimumSizeHint()));
}
Пример #17
0
void KFileItemPrivate::readUDSEntry(bool _urlIsDirectory)
{
    // extract fields from the KIO::UDS Entry

    m_fileMode = m_entry.numberValue(KIO::UDSEntry::UDS_FILE_TYPE, KFileItem::Unknown);
    m_permissions = m_entry.numberValue(KIO::UDSEntry::UDS_ACCESS, KFileItem::Unknown);
    m_strName = m_entry.stringValue(KIO::UDSEntry::UDS_NAME);

    const QString displayName = m_entry.stringValue(KIO::UDSEntry::UDS_DISPLAY_NAME);
    if (!displayName.isEmpty()) {
        m_strText = displayName;
    } else {
        m_strText = KIO::decodeFileName(m_strName);
    }

    const QString urlStr = m_entry.stringValue(KIO::UDSEntry::UDS_URL);
    const bool UDS_URL_seen = !urlStr.isEmpty();
    if (UDS_URL_seen) {
        m_url = QUrl(urlStr);
        if (m_url.isLocalFile()) {
            m_bIsLocalUrl = true;
        }
    }
    QMimeDatabase db;
    const QString mimeTypeStr = m_entry.stringValue(KIO::UDSEntry::UDS_MIME_TYPE);
    m_bMimeTypeKnown = !mimeTypeStr.isEmpty();
    if (m_bMimeTypeKnown) {
        m_mimeType = db.mimeTypeForName(mimeTypeStr);
    }

    m_guessedMimeType = m_entry.stringValue(KIO::UDSEntry::UDS_GUESSED_MIME_TYPE);
    m_bLink = !m_entry.stringValue(KIO::UDSEntry::UDS_LINK_DEST).isEmpty();   // we don't store the link dest

    const int hiddenVal = m_entry.numberValue(KIO::UDSEntry::UDS_HIDDEN, -1);
    m_hidden = hiddenVal == 1 ? Hidden : (hiddenVal == 0 ? Shown : Auto);

    if (_urlIsDirectory && !UDS_URL_seen && !m_strName.isEmpty() && m_strName != QLatin1String(".")) {
        if (!m_url.path().endsWith('/')) {
            m_url.setPath(m_url.path() + '/');
        }
        m_url.setPath(m_url.path() + m_strName);
    }

    m_iconName.clear();
}
Пример #18
0
bool DropHandler::handleURL(const QList<QUrl>& urls_) {
  bool hasUnknown = false;
  QList<QUrl> tc, pdf, bib, ris, ciw;
  foreach(const QUrl& url, urls_) {
    QMimeType ptr;
    // findByURL doesn't work for http, so actually query
    // the url itself
    if(url.scheme() != QLatin1String("http")) {
      QMimeDatabase db;
      ptr = db.mimeTypeForUrl(url);
    } else {
      KIO::MimetypeJob* job = KIO::mimetype(url, KIO::HideProgressInfo);
      KJobWidgets::setWindow(job, GUI::Proxy::widget());
      job->exec();
      QMimeDatabase db;
      ptr = db.mimeTypeForName(job->mimetype());
    }
    if(ptr.inherits(QLatin1String("application/x-tellico"))) {
      tc << url;
    } else if(ptr.inherits(QLatin1String("application/pdf"))) {
      pdf << url;
    } else if(ptr.inherits(QLatin1String("text/x-bibtex")) ||
              ptr.inherits(QLatin1String("application/x-bibtex")) ||
              ptr.inherits(QLatin1String("application/bibtex"))) {
      bib << url;
    } else if(ptr.inherits(QLatin1String("application/x-research-info-systems"))) {
      ris << url;
    } else if(url.fileName().endsWith(QLatin1String(".bib"))) {
      bib << url;
    } else if(url.fileName().endsWith(QLatin1String(".ris"))) {
      ris << url;
    } else if(url.fileName().endsWith(QLatin1String(".ciw"))) {
      ciw << url;
    } else if(ptr.inherits(QLatin1String("text/plain")) && Import::BibtexImporter::maybeBibtex(url)) {
      bib << url;
    } else if(ptr.inherits(QLatin1String("text/plain")) && Import::RISImporter::maybeRIS(url)) {
      ris << url;
    } else if(ptr.inherits(QLatin1String("text/plain")) && Import::CIWImporter::maybeCIW(url)) {
      ciw << url;
    } else {
      myDebug() << "unrecognized type: " << ptr.name() << " (" << url << ")";
      hasUnknown = true;
    }
  }
Пример #19
0
 PluginRegistry()
     : mDefaultPlugin(PluginEntry(QStringLiteral("application/octet-stream@QByteArray"), s_defaultItemSerializerPlugin))
     , mOverridePlugin(0)
 {
     const PluginLoader *pl = PluginLoader::self();
     if (!pl) {
         qWarning() << "Cannot instantiate plugin loader!" << endl;
         return;
     }
     const QStringList names = pl->names();
     qDebug() << "ItemSerializerPluginLoader: "
              << "found" << names.size() << "plugins." << endl;
     QMap<QString, MimeTypeEntry> map;
     QRegExp rx(QStringLiteral("(.+)@(.+)"));
     QMimeDatabase mimeDb;
     Q_FOREACH (const QString &name, names) {
         if (rx.exactMatch(name)) {
             const QMimeType mime = mimeDb.mimeTypeForName(rx.cap(1));
             if (mime.isValid()) {
                 const QString mimeType = mime.name();
                 const QByteArray classType = rx.cap(2).toLatin1();
                 QMap<QString, MimeTypeEntry>::iterator it = map.find(mimeType);
                 if (it == map.end()) {
                     it = map.insert(mimeType, MimeTypeEntry(mimeType));
                 }
                 it->add(classType, PluginEntry(name));
             }
         } else {
             qDebug() << "ItemSerializerPluginLoader: "
                      << "name" << name << "doesn't look like mimetype@classtype" << endl;
         }
     }
     const QString APPLICATION_OCTETSTREAM = QLatin1String(_APPLICATION_OCTETSTREAM);
     QMap<QString, MimeTypeEntry>::iterator it = map.find(APPLICATION_OCTETSTREAM);
     if (it == map.end()) {
         it = map.insert(APPLICATION_OCTETSTREAM, MimeTypeEntry(APPLICATION_OCTETSTREAM));
     }
     it->add("QByteArray", mDefaultPlugin);
     it->add(LEGACY_NAME,  mDefaultPlugin);
     const int size = map.size();
     allMimeTypes.reserve(size);
     std::copy(map.begin(), map.end(), std::back_inserter(allMimeTypes));
 }
Пример #20
0
void Imagesplit::slotImagesplit()
{
    // Taking the title - url from caption function and removing file extension
    QStringList strList = ((m_view->document())->caption()).split('.');
    QString suffix = strList.at(0);

    // Getting all mime types and converting them into names which are displayed at combo box
    QStringList listMimeFilter = KisImportExportManager::mimeFilter("application/x-krita", KisImportExportManager::Export);
    QStringList filteredMimeTypes;
    QStringList listFileType;
    foreach(const QString & tempStr, listMimeFilter) {
        QMimeDatabase db;
        QMimeType type = db.mimeTypeForName(tempStr);
        dbgKrita << tempStr << type;
        if (type.isValid()) {
            listFileType.append(type.comment());
            filteredMimeTypes.append(tempStr);
        }
    }
Пример #21
0
void InfoPanel::setIndex(const QModelIndex& index)
{
    if (!index.isValid()) {
        updateWithDefaults();
    } else {
        const Archive::Entry *entry = m_model->entryForIndex(index);
        if (!entry) {
            return;
        }

        QMimeDatabase db;
        QMimeType mimeType;
        if (entry->isDir()) {
            mimeType = db.mimeTypeForName(QStringLiteral("inode/directory"));
        } else {
            mimeType = db.mimeTypeForFile(entry->fullPath(), QMimeDatabase::MatchExtension);
        }

        iconLabel->setPixmap(getDesktopIconForName(mimeType.iconName()));
        if (entry->isDir()) {
            uint dirs;
            uint files;
            entry->countChildren(dirs, files);
            additionalInfo->setText(KIO::itemsSummaryString(dirs + files, files, dirs, 0, false));
        } else if (!entry->property("link").toString().isEmpty()) {
            additionalInfo->setText(i18n("Symbolic Link"));
        } else {
            if (entry->property("size") != 0) {
                additionalInfo->setText(KIO::convertSize(entry->property("size").toULongLong()));
            } else {
                additionalInfo->setText(i18n("Unknown size"));

            }
        }

        const QStringList nameParts = entry->fullPath().split(QLatin1Char( '/' ), QString::SkipEmptyParts);
        const QString name = (nameParts.count() > 0) ? nameParts.last() : entry->fullPath();
        fileName->setText(name);

        showMetaDataFor(index);
    }
}
Пример #22
0
void Goose::post(const QUrl &url, const QByteArray &data)
{
    QNetworkRequest request(url);

    m_geese->prepare(request);
    auto reply = m_geese->post(request, data);

    connect(reply, &QNetworkReply::finished,
    this, [ = ]() {
        QMimeDatabase mdb;
        auto contentType = reply->header(QNetworkRequest::ContentTypeHeader).toString();
        qDebug() << mdb.mimeTypeForName(contentType);
        emit arrive(QNetworkReply::NoError, reply->readAll());
    });

    connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error),
    this, [ = ](QNetworkReply::NetworkError error) {
        qWarning() << "Goose: get" << reply->errorString();
        emit arrive(error, reply->readAll());
    });
}
Пример #23
0
static KService::List mimeTypeSycocaServiceOffers(const QString& mimeType)
{
    KService::List lst;
    QMimeDatabase db;
    const QString mime = db.mimeTypeForName(mimeType).name();
    if (mime.isEmpty()) {
        qWarning() << "KMimeTypeTrader: mimeType" << mimeType << "not found";
        return lst; // empty
    }
    KMimeTypeFactory *factory = KMimeTypeFactory::self();
    const int offset = factory->entryOffset(mime);
    if ( !offset ) {
        qWarning() << "KMimeTypeTrader: mimeType" << mimeType << "not found";
        return lst; // empty
    }
    const int serviceOffersOffset = factory->serviceOffersOffset(mime);
    if ( serviceOffersOffset > -1 ) {
        lst = KServiceFactory::self()->serviceOffers(offset, serviceOffersOffset);
    }
    return lst;
}
Пример #24
0
// static
QStringList ClipCreationDialog::getExtensions()
{
    // Build list of mime types
    QStringList mimeTypes = QStringList() << QStringLiteral("application/x-kdenlive") << QStringLiteral("application/x-kdenlivetitle") << QStringLiteral("video/mlt-playlist") << QStringLiteral("text/plain");

    // Video mimes
    mimeTypes <<  QStringLiteral("video/x-flv") << QStringLiteral("application/vnd.rn-realmedia") << QStringLiteral("video/x-dv") << QStringLiteral("video/dv") << QStringLiteral("video/x-msvideo") << QStringLiteral("video/x-matroska") << QStringLiteral("video/mpeg") << QStringLiteral("video/ogg") << QStringLiteral("video/x-ms-wmv") << QStringLiteral("video/mp4") << QStringLiteral("video/quicktime") << QStringLiteral("video/webm") << QStringLiteral("video/3gpp") << QStringLiteral("video/mp2t");

    // Audio mimes
    mimeTypes << QStringLiteral("audio/x-flac") << QStringLiteral("audio/x-matroska") << QStringLiteral("audio/mp4") << QStringLiteral("audio/mpeg") << QStringLiteral("audio/x-mp3") << QStringLiteral("audio/ogg") << QStringLiteral("audio/x-wav") << QStringLiteral("audio/x-aiff") << QStringLiteral("audio/aiff") << QStringLiteral("application/ogg") << QStringLiteral("application/mxf") << QStringLiteral("application/x-shockwave-flash") << QStringLiteral("audio/ac3");

    // Image mimes
    mimeTypes << QStringLiteral("image/gif") << QStringLiteral("image/jpeg") << QStringLiteral("image/png") << QStringLiteral("image/x-tga") << QStringLiteral("image/x-bmp") << QStringLiteral("image/svg+xml") << QStringLiteral("image/tiff") << QStringLiteral("image/x-xcf") << QStringLiteral("image/x-xcf-gimp") << QStringLiteral("image/x-vnd.adobe.photoshop") << QStringLiteral("image/x-pcx") << QStringLiteral("image/x-exr") << QStringLiteral("image/x-portable-pixmap");

    QMimeDatabase db;
    QStringList allExtensions;
    foreach(const QString & mimeType, mimeTypes) {
        QMimeType mime = db.mimeTypeForName(mimeType);
        if (mime.isValid()) {
            allExtensions.append(mime.globPatterns());
        }
    }
Пример #25
0
QUrl KexiReportView::getExportUrl(const QString &mimetype, const QString &caption,
                                  const QString &lastExportPath, const QString &extension)
{
    QUrl result;
    QString defaultSavePath;

    if (lastExportPath.startsWith("kfiledialog:///")) {
        defaultSavePath = lastExportPath + window()->partItem()->captionOrName() + "." + extension;
    }

    // loop until an url has been chosen or the file selection has been cancelled
    const QMimeDatabase db;
    const QString filterString = db.mimeTypeForName(mimetype).filterString();

    while (true) {
        QUrl result = QFileDialog::getSaveFileUrl(this, caption, QUrl::fromLocalFile(defaultSavePath),
                                             filterString);

        // not cancelled?
        if (result.isValid()) {
            if (KIO::NetAccess::exists(result, KIO::NetAccess::DestinationSide, this)) {
                const KMessageBox::ButtonCode answer = KMessageBox::warningContinueCancel(this,
                    xi18n("The file %1 exists.\nDo you want to overwrite it?", result.path()),
                    caption, KGuiItem(xi18nc("@action:button Overwrite File", "Overwrite")));

                // if overwriting not wanted, let select another url
                if (answer == KMessageBox::Cancel) {
                    continue;
                }
            }
        }

        // decision has been made, leave loop
        break;
    }

    return result;
}
Пример #26
0
//! [4]
void MainWindow::save()
{
    QMimeDatabase mimeDatabase;
    QString fileName = QFileDialog::getSaveFileName(this,
                        tr("Choose a file name"), ".",
                        mimeDatabase.mimeTypeForName("text/html").filterString());
    if (fileName.isEmpty())
        return;
    QFile file(fileName);
    if (!file.open(QFile::WriteOnly | QFile::Text)) {
        QMessageBox::warning(this, tr("Dock Widgets"),
                             tr("Cannot write file %1:\n%2.")
                             .arg(QDir::toNativeSeparators(fileName), file.errorString()));
        return;
    }

    QTextStream out(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    out << textEdit->toHtml();
    QApplication::restoreOverrideCursor();

    statusBar()->showMessage(tr("Saved '%1'").arg(fileName), 2000);
}
Пример #27
0
bool MimeTypeChecker::isWantedItem(const Item &item, const QString &wantedMimeType)
{
    if (wantedMimeType.isEmpty() || !item.isValid()) {
        return false;
    }

    const QString mimeType = item.mimeType();
    if (mimeType.isEmpty()) {
        return false;
    }

    if (mimeType == wantedMimeType) {
        return true;
    }

    QMimeDatabase db;
    const QMimeType mt = db.mimeTypeForName(mimeType);
    if (!mt.isValid()) {
        return false;
    }

    return mt.inherits(wantedMimeType);
}
Пример #28
0
void ArkViewer::view(const QString& fileName)
{
    QMimeDatabase db;
    QMimeType mimeType = db.mimeTypeForFile(fileName);
    qCDebug(ARK) << "viewing" << fileName << "with mime type:" << mimeType.name();
    KService::Ptr viewer = ArkViewer::getViewer(mimeType.name());

    const bool needsExternalViewer = (viewer &&
                                      !viewer->hasServiceType(QStringLiteral("KParts/ReadOnlyPart")));
    if (needsExternalViewer) {
        // We have already resolved the MIME type and the service above.
        // So there is no point in using KRun::runUrl() which would need
        // to do the same again.

        qCDebug(ARK) << "Using external viewer";

        const QList<QUrl> fileUrlList = {QUrl::fromLocalFile(fileName)};
        // The last argument (tempFiles) set to true means that the temporary
        // file will be removed when the viewer application exits.
        KRun::runService(*viewer, fileUrlList, nullptr, true);
        return;
    }

    qCDebug(ARK) << "Attempting to use internal viewer";
    bool viewInInternalViewer = true;
    if (!viewer) {
        // No internal viewer available for the file.  Ask the user if it
        // should be previewed as text/plain.

        qCDebug(ARK) << "Internal viewer not available";

        int response;
        if (!mimeType.isDefault()) {
            // File has a defined MIME type, and not the default
            // application/octet-stream.  So it could be viewable as
            // plain text, ask the user.
            response = KMessageBox::warningContinueCancel(nullptr,
                xi18n("The internal viewer cannot preview this type of file<nl/>(%1).<nl/><nl/>Do you want to try to view it as plain text?", mimeType.name()),
                i18nc("@title:window", "Cannot Preview File"),
                KGuiItem(i18nc("@action:button", "Preview as Text"), QIcon::fromTheme(QStringLiteral("text-plain"))),
                KStandardGuiItem::cancel(),
                QStringLiteral("PreviewAsText_%1").arg(mimeType.name()));
        }
        else {
            // No defined MIME type, or the default application/octet-stream.
            // There is still a possibility that it could be viewable as plain
            // text, so ask the user.  Not the same as the message/question
            // above, because the wording and default are different.
            response = KMessageBox::warningContinueCancel(nullptr,
                xi18n("The internal viewer cannot preview this unknown type of file.<nl/><nl/>Do you want to try to view it as plain text?"),
                i18nc("@title:window", "Cannot Preview File"),
                KGuiItem(i18nc("@action:button", "Preview as Text"), QIcon::fromTheme(QStringLiteral("text-plain"))),
                KStandardGuiItem::cancel(),
                QString(),
                KMessageBox::Dangerous);
        }

        if (response == KMessageBox::Cancel) {
            viewInInternalViewer = false;
        }
        else {						// set for viewer later
            mimeType = db.mimeTypeForName(QStringLiteral("text/plain"));
        }
    }

    if (viewInInternalViewer) {
        qCDebug(ARK) << "Opening internal viewer";
        ArkViewer *internalViewer = new ArkViewer();
        internalViewer->show();
        if (internalViewer->viewInInternalViewer(fileName, mimeType)) {
            // The internal viewer is showing the file, and will
            // remove the temporary file in its destructor.  So there
            // is no more to do here.
            return;
        }
        else {
            KMessageBox::sorry(nullptr, i18n("The internal viewer cannot preview this file."));
            delete internalViewer;
        }
    }

    // Only get here if there is no internal viewer available or could be
    // used for the file, and no external viewer was opened.  Nothing can be
    // done with the temporary file, so remove it now.
    qCDebug(ARK) << "Removing temporary file:" << fileName;
    QFile::remove(fileName);
}
Пример #29
0
/** ***************************************************************************/
void Files::File::deserialize(QDataStream &in) {
    QMimeDatabase db;
    QString mimetype;
    in >> path_ >> usage_ >> mimetype;
    mimetype_ = db.mimeTypeForName(mimetype);
}
Пример #30
0
QImage ThumbnailProtocol::thumbForDirectory(const QUrl& directory)
{
    QImage img;
    if (m_propagationDirectories.isEmpty()) {
        // Directories that the directory preview will be propagated into if there is no direct sub-directories
        const KConfigGroup globalConfig(KSharedConfig::openConfig(), "PreviewSettings");
        m_propagationDirectories = globalConfig.readEntry("PropagationDirectories", QStringList() << "VIDEO_TS").toSet();
        m_maxFileSize = globalConfig.readEntry("MaximumSize", 5 * 1024 * 1024); // 5 MByte default
    }

    const int tiles = 2; //Count of items shown on each dimension
    const int spacing = 1;
    const int visibleCount = tiles * tiles;

    // TODO: the margins are optimized for the Oxygen iconset
    // Provide a fallback solution for other iconsets (e. g. draw folder
    // only as small overlay, use no margins)

    //Use the current (custom) folder icon
    const QMimeDatabase db;
    const QString iconName = db.mimeTypeForName("inode/directory").iconName();

    const QPixmap folder = QIcon::fromTheme(iconName).pixmap(qMin(m_width, m_height));

    const int folderWidth  = folder.width();
    const int folderHeight = folder.height();

    const int topMargin = folderHeight * 30 / 100;
    const int bottomMargin = folderHeight / 6;
    const int leftMargin = folderWidth / 13;
    const int rightMargin = leftMargin;

    const int segmentWidth  = (folderWidth  - leftMargin - rightMargin  + spacing) / tiles - spacing;
    const int segmentHeight = (folderHeight - topMargin  - bottomMargin + spacing) / tiles - spacing;
    if ((segmentWidth < 5) || (segmentHeight <  5)) {
        // the segment size is too small for a useful preview
        return img;
    }

    QString localFile = directory.path();

    // Multiply with a high number, so we get some semi-random sequence
    int skipValidItems = ((int)sequenceIndex()) * tiles * tiles;

    img = QImage(QSize(folderWidth, folderHeight), QImage::Format_ARGB32);
    img.fill(0);

    QPainter p;
    p.begin(&img);

    p.setCompositionMode(QPainter::CompositionMode_Source);
    p.drawPixmap(0, 0, folder);
    p.setCompositionMode(QPainter::CompositionMode_SourceOver);

    int xPos = leftMargin;
    int yPos = topMargin;

    int frameWidth = qRound(folderWidth / 85.);

    int iterations = 0;
    QString hadFirstThumbnail;
    int skipped = 0;

    const int maxYPos = folderHeight - bottomMargin - segmentHeight;

    // Setup image object for preview with only one tile
    QImage oneTileImg(folder.size(), QImage::Format_ARGB32);
    oneTileImg.fill(0);

    QPainter oneTilePainter(&oneTileImg);
    oneTilePainter.setCompositionMode(QPainter::CompositionMode_Source);
    oneTilePainter.drawPixmap(0, 0, folder);
    oneTilePainter.setCompositionMode(QPainter::CompositionMode_SourceOver);

    const int oneTileWidth = folderWidth - leftMargin - rightMargin;
    const int oneTileHeight = folderHeight - topMargin - bottomMargin;

    int validThumbnails = 0;

    while ((skipped <= skipValidItems) && (yPos <= maxYPos) && validThumbnails == 0) {
        QDirIterator dir(localFile, QDir::Files | QDir::Readable);
        if (!dir.hasNext()) {
            break;
        }

        while (dir.hasNext() && (yPos <= maxYPos)) {
            ++iterations;
            if (iterations > 500) {
                skipValidItems = skipped = 0;
                break;
            }

            dir.next();

            if (validThumbnails > 0 && hadFirstThumbnail == dir.filePath()) {
                break; // Never show the same thumbnail twice
            }

            if (dir.fileInfo().size() > m_maxFileSize) {
                // don't create thumbnails for files that exceed
                // the maximum set file size
                continue;
            }

            if (!drawSubThumbnail(p, dir.filePath(), segmentWidth, segmentHeight, xPos, yPos, frameWidth)) {
                continue;
            }

            if (validThumbnails == 0) {
                drawSubThumbnail(oneTilePainter, dir.filePath(), oneTileWidth, oneTileHeight, xPos, yPos, frameWidth);
            }

            if (skipped < skipValidItems) {
                ++skipped;
                continue;
            }

            if (hadFirstThumbnail.isEmpty()) {
                hadFirstThumbnail = dir.filePath();
            }

            ++validThumbnails;

            xPos += segmentWidth + spacing;
            if (xPos > folderWidth - rightMargin - segmentWidth) {
                xPos = leftMargin;
                yPos += segmentHeight + spacing;
            }
        }

        if (skipped != 0) { // Round up to full pages
            const int roundedDown = (skipped / visibleCount) * visibleCount;
            if (roundedDown < skipped) {
                skipped = roundedDown + visibleCount;
            } else {
                skipped = roundedDown;
            }
        }

        if (skipped == 0) {
            break; // No valid items were found
        }

        // We don't need to iterate again and again: Subtract any multiple of "skipped" from the count we still need to skip
        skipValidItems -= (skipValidItems / skipped) * skipped;
        skipped = 0;
    }

    p.end();

    if (validThumbnails == 0) {
        // Eventually propagate the contained items from a sub-directory
        QDirIterator dir(localFile, QDir::Dirs);
        int max = 50;
        while (dir.hasNext() && max > 0) {
            --max;
            dir.next();
            if (m_propagationDirectories.contains(dir.fileName())) {
                return thumbForDirectory(QUrl(dir.filePath()));
            }
        }

        // If no thumbnail could be found, return an empty image which indicates
        // that no preview for the directory is available.
        img = QImage();
    }

    // If only for one file a thumbnail could be generated then use image with only one tile
    if (validThumbnails == 1) {
        return oneTileImg;
    }

    return img;
}