示例#1
0
文件: vfile.cpp 项目: KDE/krusader
const QString& vfile::vfile_getMime()
{
    if (vfile_mimeType.isEmpty()) {
        if(vfile_isdir)
            vfile_mimeType = "inode/directory";
        else if(vfile_isBrokenLink())
            vfile_mimeType = "unknown";
        else {
            QMimeDatabase db;
            QMimeType mt = db.mimeTypeForUrl(vfile_getUrl());
            vfile_mimeType = mt.isValid() ? mt.name() : "unknown";
            if (mt.isValid())
                vfile_icon = mt.iconName();
            if (vfile_mimeType == "inode/directory") {
                vfile_perm[0] = 'd';
                vfile_isdir = true;
            }
        }

        if (vfile_isdir && vfile_userDefinedFolderIcons) {
            QUrl url = vfile_getUrl();
            if (url.isLocalFile()) {
                QString file = url.toLocalFile() + "/.directory";
                KDesktopFile cfg(file);
                QString icon = cfg.readIcon();
                if(icon.startsWith(QLatin1String("./"))) // relative path
                    icon = url.toLocalFile() + '/' + icon;
                if (!icon.isEmpty())
                    vfile_icon = icon;
            }
        }
    }
    return vfile_mimeType;
}
示例#2
0
QMimeType QMimeDatabasePrivate::mimeTypeForFileNameAndData(const QString &fileName, QIODevice *device, int *accuracyPtr)
{
    // 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.
    *accuracyPtr = 0;

    // Pass 1) Try to match on the file name
    QStringList candidatesByName = mimeTypeForFileName(fileName);
    if (candidatesByName.count() == 1) {
        *accuracyPtr = 100;
        const QMimeType mime = mimeTypeForName(candidatesByName.at(0));
        if (mime.isValid())
            return mime;
        candidatesByName.clear();
    }

    // Extension is unknown, or matches multiple mimetypes.
    // Pass 2) Match on content, if we can read the data
    if (device->isOpen()) {

        // Read 16K in one go (QIODEVICE_BUFFERSIZE in qiodevice_p.h).
        // This is much faster than seeking back and forth into QIODevice.
        const QByteArray data = device->peek(16384);

        int magicAccuracy = 0;
        QMimeType candidateByData(findByData(data, &magicAccuracy));

        // Disambiguate conflicting extensions (if magic matching found something)
        if (candidateByData.isValid() && magicAccuracy > 0) {
            // "for glob_match in glob_matches:"
            // "if glob_match is subclass or equal to sniffed_type, use glob_match"
            const QString sniffedMime = candidateByData.name();
            foreach (const QString &m, candidatesByName) {
                if (inherits(m, sniffedMime)) {
                    // We have magic + pattern pointing to this, so it's a pretty good match
                    *accuracyPtr = 100;
                    return mimeTypeForName(m);
                }
            }
            *accuracyPtr = magicAccuracy;
            return candidateByData;
        }
    }

    if (candidatesByName.count() > 1) {
        *accuracyPtr = 20;
        candidatesByName.sort(); // to make it deterministic
        const QMimeType mime = mimeTypeForName(candidatesByName.at(0));
        if (mime.isValid())
            return mime;
    }

    return mimeTypeForName(defaultMimeType());
}
示例#3
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

}
示例#4
0
EditWithMenu::EditWithMenu(const QUrl& url, QWidget* parent)
    : QObject(parent)
    , m_menu(0)
    , m_url(url)
{
    QMimeDatabase db;
    QMimeType type = db.mimeTypeForFile(url.path(), QMimeDatabase::MatchExtension);
    if ( !type.isValid() )
    {
        qCDebug(log_cervisia) << "Couldn't find mime type!";
        return;
    }

    m_offers = KMimeTypeTrader::self()->query(type.name());

    if( !m_offers.isEmpty() )
    {
        m_menu = new QMenu(i18n("Edit With"));

        KService::List::ConstIterator it = m_offers.constBegin();
        for( int i = 0 ; it != m_offers.constEnd(); ++it, ++i )
        {
            QAction* pAction = m_menu->addAction(QIcon::fromTheme((*it)->icon()), (*it)->name());
            pAction->setData(i);
        }

        connect(m_menu, SIGNAL(triggered(QAction*)),
                this, SLOT(actionTriggered(QAction*)));
    }
示例#5
0
QVariant MessageComposer::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.column() != 0 || index.row() < 0 || index.row() >= m_attachments.size())
        return QVariant();

    switch (role) {
    case Qt::DisplayRole:
        return m_attachments[index.row()]->caption();
    case Qt::ToolTipRole:
        return m_attachments[index.row()]->tooltip();
    case Qt::DecorationRole:
    {
        // This is more or less copy-pasted from Gui/AttachmentView.cpp. Unfortunately, sharing the implementation
        // is not trivial due to the way how the static libraries are currently built.
        QMimeType mimeType = QMimeDatabase().mimeTypeForName(QString::fromUtf8(m_attachments[index.row()]->mimeType()));
        if (mimeType.isValid() && !mimeType.isDefault()) {
            return QIcon::fromTheme(mimeType.iconName(), UiUtils::loadIcon(QStringLiteral("mail-attachment")));
        } else {
            return UiUtils::loadIcon(QStringLiteral("mail-attachment"));
        }
    }
    case Imap::Mailbox::RoleAttachmentContentDispositionMode:
        return static_cast<int>(m_attachments[index.row()]->contentDispositionMode());
    }
    return QVariant();
}
示例#6
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;
}
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.
}
示例#8
0
Vector<String> MIMETypeRegistry::getExtensionsForMIMEType(const String& mimeTypeName)
{
    Vector<String> extensions;
    QMimeType mimeType = QMimeDatabase().mimeTypeForName(mimeTypeName);
    if (mimeType.isValid() && !mimeType.isDefault()) {
        Q_FOREACH(const QString& suffix, mimeType.suffixes()) {
            extensions.append(suffix);
        }
    }
示例#9
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;
}
示例#10
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;
}
示例#11
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();
}
示例#12
0
文件: kiso.cpp 项目: KDE/krusader
KIso::KIso(const QString& filename, const QString & _mimetype)
        : KArchive(0L)
{
    KISOFUNC;
    KISODEBUG("Starting KIso: " << filename << " - type: " << _mimetype);

    m_startsec = -1;
    m_filename = filename;
    d = new KIsoPrivate;
    QString mimetype(_mimetype);
    bool forced = true;
    if (mimetype.isEmpty()) {
        QMimeDatabase db;
        QMimeType mt = db.mimeTypeForFile(filename, QMimeDatabase::MatchContent);
        if (mt.isValid())
            mimetype = mt.name();

        //qDebug() << "KIso::KIso mimetype=" << mimetype << endl;

        // Don't move to prepareDevice - the other constructor theoretically allows ANY filter
        if (mimetype == "application/x-tgz" || mimetype == "application/x-targz" ||  // the latter is deprecated but might still be around
                mimetype == "application/x-webarchive")
            // that's a gzipped tar file, so ask for gzip filter
            mimetype = "application/x-gzip";
        else if (mimetype == "application/x-tbz")   // that's a bzipped2 tar file, so ask for bz2 filter
            mimetype = "application/x-bzip2";
        else {
            // Something else. Check if it's not really gzip though (e.g. for KOffice docs)
            QFile file(filename);
            if (file.open(QIODevice::ReadOnly)) {
                char firstByte;
                char secondByte;
                char thirdByte;
                file.getChar(&firstByte);
                file.getChar(&secondByte);
                file.getChar(&thirdByte);
                if (firstByte == 0037 && secondByte == (char)0213)
                    mimetype = "application/x-gzip";
                else if (firstByte == 'B' && secondByte == 'Z' && thirdByte == 'h')
                    mimetype = "application/x-bzip2";
                else if (firstByte == 'P' && secondByte == 'K' && thirdByte == 3) {
                    char fourthByte;
                    file.getChar(&fourthByte);
                    if (fourthByte == 4)
                        mimetype = "application/x-zip";
                }
            }
        }
        forced = false;
    }

    prepareDevice(filename, mimetype, forced);
}
示例#13
0
文件: vfile.cpp 项目: KDE/krusader
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
String MIMETypeRegistry::getMIMETypeForPath(const String& path)
{
    QMimeType type = QMimeDatabase().mimeTypeForFile(path, QMimeDatabase::MatchExtension);
    if (type.isValid() && !type.isDefault())
        return type.name();

    const ExtensionMap *e = extensionMap;
    while (e->extension) {
        if (path.endsWith(e->dotExtension))
            return e->mimeType;
        ++e;
    }

    return defaultMIMEType();
}
示例#15
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()));
}
示例#16
0
bool StaticSimple::locateStaticFile(Context *c, const QString &relPath)
{
    Q_D(const StaticSimple);

    for (const QDir &includePath : d->includePaths) {
        QString path = includePath.absoluteFilePath(relPath);
        QFileInfo fileInfo(path);
        if (fileInfo.exists()) {
            Response *res = c->res();
            const QDateTime currentDateTime = fileInfo.lastModified();
            if (currentDateTime == c->req()->headers().ifModifiedSinceDateTime()) {
                res->setStatus(Response::NotModified);
                return true;
            }

            QFile *file = new QFile(path);
            if (file->open(QFile::ReadOnly)) {
                qCDebug(C_STATICSIMPLE) << "Serving" << path;
                Headers &headers = res->headers();

                // set our open file
                res->setBody(file);

                QMimeDatabase db;
                // use the extension to match to be faster
                QMimeType mimeType = db.mimeTypeForFile(path, QMimeDatabase::MatchExtension);
                if (mimeType.isValid()) {
                    headers.setContentType(mimeType.name());
                }
                headers.setContentLength(file->size());

                headers.setLastModified(currentDateTime);
                // Tell Firefox & friends its OK to cache, even over SSL
                headers.setHeader(QStringLiteral("Cache-Control"), QStringLiteral("public"));

                return true;
            }

            qCWarning(C_STATICSIMPLE) << "Could not serve" << path << file->errorString();
            return false;
        }
    }

    qCWarning(C_STATICSIMPLE) << "File not found" << relPath;
    return false;
}
示例#17
0
文件: window.cpp 项目: Jinxiaohai/QT
//! [5]
QStringList Window::findFiles(const QStringList &files, const QString &text) {
  QProgressDialog progressDialog(this);
  progressDialog.setCancelButtonText(tr("&Cancel"));
  progressDialog.setRange(0, files.size());
  progressDialog.setWindowTitle(tr("Find Files"));

  //! [5] //! [6]
  QMimeDatabase mimeDatabase;
  QStringList foundFiles;

  for (int i = 0; i < files.size(); ++i) {
    progressDialog.setValue(i);
    progressDialog.setLabelText(
        tr("Searching file number %1 of %n...", 0, files.size()).arg(i));
    QCoreApplication::processEvents();
    //! [6]

    if (progressDialog.wasCanceled()) break;

    //! [7]
    const QString fileName = files.at(i);
    const QMimeType mimeType = mimeDatabase.mimeTypeForFile(fileName);
    if (mimeType.isValid() &&
        !mimeType.inherits(QStringLiteral("text/plain"))) {
      qWarning() << "Not searching binary file "
                 << QDir::toNativeSeparators(fileName);
      continue;
    }
    QFile file(fileName);
    if (file.open(QIODevice::ReadOnly)) {
      QString line;
      QTextStream in(&file);
      while (!in.atEnd()) {
        if (progressDialog.wasCanceled()) break;
        line = in.readLine();
        if (line.contains(text, Qt::CaseInsensitive)) {
          foundFiles << files[i];
          break;
        }
      }
    }
  }
  return foundFiles;
}
示例#18
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);
        }
    }
示例#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
bool Helper::handleGetFromType()
    {
    if( !readArguments( 1 ))
        return false;
    QString type = getArgument();
    if( !allArgumentsUsed())
        return false;
    QMimeType mime = QMimeDatabase().mimeTypeForName(type);
    if (mime.isValid()) return writeMimeInfo(mime);
    // firefox also asks for protocol handlers using getfromtype
    QString app = getAppForProtocol( type );
    if( !app.isEmpty())
        {
        outputLine( type );
        outputLine( type ); // TODO probably no way to find a good description
        outputLine( app );
        return true;
        }
    return false;
    }
示例#21
0
QMimeType QMimeDatabasePrivate::findByData(const QByteArray &data, int *accuracyPtr)
{
    if (data.isEmpty()) {
        *accuracyPtr = 100;
        return mimeTypeForName(QLatin1String("application/x-zerosize"));
    }

    *accuracyPtr = 0;
    QMimeType candidate = provider()->findByMagic(data, accuracyPtr);

    if (candidate.isValid())
        return candidate;

    if (isTextFile(data)) {
        *accuracyPtr = 5;
        return mimeTypeForName(QLatin1String("text/plain"));
    }

    return mimeTypeForName(defaultMimeType());
}
示例#22
0
	bool TorrentFile::isMultimedia() const
	{
		if (filetype == UNKNOWN)
		{
			QMimeType ptr = QMimeDatabase().mimeTypeForFile(getPath());
			if (!ptr.isValid())
			{
				filetype = NORMAL;
				return false;
			}
			
			QString name = ptr.name();
			if (name.startsWith(QLatin1String("audio")) ||  name == QLatin1String("application/ogg"))
				filetype = AUDIO;
			else if (name.startsWith(QLatin1String("video")))
				filetype = VIDEO;
			else
				filetype = NORMAL;
		}
		return filetype == AUDIO || filetype == VIDEO;
	}
示例#23
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);
}
示例#24
0
bool Helper::handleOpen()
    {
    if( !readArguments( 1 ))
        return false;
    QUrl url = QUrl::fromUserInput(getArgument());
    QString mime;
    if( isArgument( "MIMETYPE" ))
        mime = getArgument();
    if( !allArgumentsUsed())
        return false;
    //KApplication::updateUserTimestamp( 0 ); // TODO
    // try to handle the case when the server has broken mimetypes and e.g. claims something is application/octet-stream
    QMimeType mimeType = QMimeDatabase().mimeTypeForName(mime);
    if (!mime.isEmpty() && mimeType.isValid() && KMimeTypeTrader::self()->preferredService(mimeType.name()))
        return KRun::runUrl( url, mime, NULL ); // TODO parent
    else
        {
        (void) new KRun( url, NULL ); // TODO parent
    //    QObject::connect( run, SIGNAL( finished()), &app, SLOT( openDone()));
    //    QObject::connect( run, SIGNAL( error()), &app, SLOT( openDone()));
        return true; // TODO check for errors?
        }
    }
示例#25
0
QString KisImportExportManager::importDocument(const QString& url,
                                               const QString& documentMimeType,
                                               KisImportExportFilter::ConversionStatus& status)
{
    // Find the mime type for the file to be imported.
    QString  typeName(documentMimeType);
    QUrl u(url);
    QMimeType t;
    if (documentMimeType.isEmpty()) {
        QMimeDatabase db;
        db.mimeTypeForFile(u.path(), QMimeDatabase::MatchExtension);
        if (t.isValid())
            typeName = t.name();
    }
    m_graph.setSourceMimeType(typeName.toLatin1()); // .latin1() is okay here (Werner)

    if (!m_graph.isValid()) {
        bool userCancelled = false;

        warnFile << "Can't open " << typeName << ", trying filter chooser";
        if (m_document) {
            if (!m_document->isAutoErrorHandlingEnabled()) {
                status = KisImportExportFilter::BadConversionGraph;
                return QString();
            }
            QByteArray nativeFormat = m_document->nativeFormatMimeType();

            QApplication::setOverrideCursor(Qt::ArrowCursor);
            KisFilterChooser chooser(0,
                                     KisImportExportManager::mimeFilter(nativeFormat, KisImportExportManager::Import,
                                                                        m_document->extraNativeMimeTypes()), nativeFormat, u);
            if (chooser.exec()) {
                QByteArray f = chooser.filterSelected().toLatin1();
                if (f == nativeFormat) {
                    status = KisImportExportFilter::OK;
                    QApplication::restoreOverrideCursor();
                    return url;
                }

                m_graph.setSourceMimeType(f);
            } else
                userCancelled = true;
            QApplication::restoreOverrideCursor();
        }

        if (!m_graph.isValid()) {
            errFile << "Couldn't create a valid graph for this source mimetype: "
                    << typeName;
            importErrorHelper(typeName, userCancelled);
            status = KisImportExportFilter::BadConversionGraph;
            return QString();
        }
    }

    KisFilterChain::Ptr chain(0);
    // Are we owned by a KisDocument?
    if (m_document) {
        QByteArray mimeType = m_document->nativeFormatMimeType();
        QStringList extraMimes = m_document->extraNativeMimeTypes();
        int i = 0;
        int n = extraMimes.count();
        chain = m_graph.chain(this, mimeType);
        while (i < n) {
            QByteArray extraMime = extraMimes[i].toUtf8();
            // TODO check if its the same target mime then continue
            KisFilterChain::Ptr newChain(0);
            newChain = m_graph.chain(this, extraMime);
            if (!chain || (newChain && newChain->weight() < chain->weight()))
                chain = newChain;
            ++i;
        }
    } else if (!d->importMimeType.isEmpty()) {
        chain = m_graph.chain(this, d->importMimeType);
    } else {
        errFile << "You aren't supposed to use import() from a filter!" << endl;
        status = KisImportExportFilter::UsageError;
        return QString();
    }

    if (!chain) {
        errFile << "Couldn't create a valid filter chain!" << endl;
        importErrorHelper(typeName);
        status = KisImportExportFilter::BadConversionGraph;
        return QString();
    }

    // Okay, let's invoke the filters one after the other
    m_direction = Import; // vital information!
    m_importUrl = url;  // We want to load that file
    m_exportUrl.clear();  // This is null for sure, as embedded stuff isn't
    // allowed to use that method
    status = chain->invokeChain();

    m_importUrl.clear();  // Reset the import URL

    if (status == KisImportExportFilter::OK)
        return chain->chainOutput();
    return QString();
}
示例#26
0
KisImportExportFilter::ConversionStatus KisImportExportManager::exportDocument(const QString& url, QByteArray& mimeType)
{
    bool userCancelled = false;

    // The import url should already be set correctly (null if we have a KisDocument
    // file manager and to the correct URL if we have an embedded manager)
    m_direction = Export; // vital information!
    m_exportUrl = url;

    KisFilterChain::Ptr chain;
    if (m_document) {
        // We have to pick the right native mimetype as source.
        QStringList nativeMimeTypes;
        nativeMimeTypes.append(m_document->nativeFormatMimeType());
        nativeMimeTypes += m_document->extraNativeMimeTypes();
        QStringList::ConstIterator it = nativeMimeTypes.constBegin();
        const QStringList::ConstIterator end = nativeMimeTypes.constEnd();
        for (; !chain && it != end; ++it) {
            m_graph.setSourceMimeType((*it).toLatin1());
            if (m_graph.isValid())
                chain = m_graph.chain(this, mimeType);
        }
    } else if (!m_importUrlMimetypeHint.isEmpty()) {
        dbgFile << "Using the mimetype hint:" << m_importUrlMimetypeHint;
        m_graph.setSourceMimeType(m_importUrlMimetypeHint);
    } else {
        QUrl u;
        u.setPath(m_importUrl);
        QMimeDatabase db;
        QMimeType t = db.mimeTypeForFile(u.path(), QMimeDatabase::MatchExtension);
        if (!t.isValid() || t.isDefault()) {
            errFile << "No mimetype found for" << m_importUrl;
            return KisImportExportFilter::BadMimeType;
        }
        m_graph.setSourceMimeType(t.name().toLatin1());

        if (!m_graph.isValid()) {
            warnFile << "Can't open" << t.name() << ", trying filter chooser";

            QApplication::setOverrideCursor(Qt::ArrowCursor);
            KisFilterChooser chooser(0, KisImportExportManager::mimeFilter(), QString(), u);
            if (chooser.exec())
                m_graph.setSourceMimeType(chooser.filterSelected().toLatin1());
            else
                userCancelled = true;

            QApplication::restoreOverrideCursor();
        }
    }

    if (!m_graph.isValid()) {
        errFile << "Couldn't create a valid graph for this source mimetype.";
        if (!d->batch && !userCancelled) {
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not export file: the export filter is missing."));
        }
        return KisImportExportFilter::BadConversionGraph;
    }

    if (!chain)   // already set when coming from the m_document case
        chain = m_graph.chain(this, mimeType);

    if (!chain) {
        errFile << "Couldn't create a valid filter chain to " << mimeType << " !" << endl;
        if (!d->batch) {
            QMessageBox::critical(0, i18nc("@title:window", "Krita"), i18n("Could not export file: the export filter is missing."));
        }
        return KisImportExportFilter::BadConversionGraph;
    }

    return chain->invokeChain();
}
示例#27
0
// Only called when a filename was given
bool KTar::createDevice(QIODevice::OpenMode mode)
{
    if (d->mimetype.isEmpty()) {
        // Find out mimetype manually

        QMimeDatabase db;
        QMimeType mime;
        if (mode != QIODevice::WriteOnly && QFile::exists(fileName())) {
            // Give priority to file contents: if someone renames a .tar.bz2 to .tar.gz,
            // we can still do the right thing here.
            QFile f(fileName());
            if (f.open(QIODevice::ReadOnly)) {
                mime = db.mimeTypeForData(&f);
            }
            if (!mime.isValid()) {
                // Unable to determine mimetype from contents, get it from file name
                mime = db.mimeTypeForFile(fileName(), QMimeDatabase::MatchExtension);
            }
        } else {
            mime = db.mimeTypeForFile(fileName(), QMimeDatabase::MatchExtension);
        }

        //qDebug() << mode << mime->name();

        if (mime.inherits(QString::fromLatin1("application/x-compressed-tar")) || mime.inherits(QString::fromLatin1(application_gzip))) {
            // gzipped tar file (with possibly invalid file name), ask for gzip filter
            d->mimetype = QString::fromLatin1(application_gzip);
        } else if (mime.inherits(QString::fromLatin1("application/x-bzip-compressed-tar")) || mime.inherits(QString::fromLatin1(application_bzip))) {
            // bzipped2 tar file (with possibly invalid file name), ask for bz2 filter
            d->mimetype = QString::fromLatin1(application_bzip);
        } else if (mime.inherits(QString::fromLatin1("application/x-lzma-compressed-tar")) || mime.inherits(QString::fromLatin1(application_lzma))) {
            // lzma compressed tar file (with possibly invalid file name), ask for xz filter
            d->mimetype = QString::fromLatin1(application_lzma);
        } else if (mime.inherits(QString::fromLatin1("application/x-xz-compressed-tar")) || mime.inherits(QString::fromLatin1(application_xz))) {
            // xz compressed tar file (with possibly invalid name), ask for xz filter
            d->mimetype = QString::fromLatin1(application_xz);
        }
    }

    if (d->mimetype == QLatin1String("application/x-tar")) {
        return KArchive::createDevice(mode);
    } else if (mode == QIODevice::WriteOnly) {
        if (!KArchive::createDevice(mode))
            return false;
        if (!d->mimetype.isEmpty()) {
            // Create a compression filter on top of the QSaveFile device that KArchive created.
            //qDebug() << "creating KFilterDev for" << d->mimetype;
            KCompressionDevice::CompressionType type = KFilterDev::compressionTypeForMimeType(d->mimetype);
            KCompressionDevice* compressionDevice = new KCompressionDevice(device(), true, type);
            setDevice(compressionDevice);
        }
        return true;
    } else {
        // The compression filters are very slow with random access.
        // So instead of applying the filter to the device,
        // the file is completely extracted instead,
        // and we work on the extracted tar file.
        // This improves the extraction speed by the tar ioslave dramatically,
        // if the archive file contains many files.
        // This is because the tar ioslave extracts one file after the other and normally
        // has to walk through the decompression filter each time.
        // Which is in fact nearly as slow as a complete decompression for each file.

        Q_ASSERT(!d->tmpFile);
        d->tmpFile = new QTemporaryFile();
        d->tmpFile->setFileTemplate(QLatin1String("ktar-XXXXXX.tar"));
        d->tmpFile->open();
        //qDebug() << "creating tempfile:" << d->tmpFile->fileName();

        setDevice(d->tmpFile);
        return true;
    }
}
int main(int argc, char **argv)
{
    KLocalizedString::setApplicationDomain( "koconverter" );

    K4AboutData aboutData("calligraconverter", 0, ki18n("CalligraConverter"), CalligraVersionWrapper::versionString().toLatin1(),
                         ki18n("Calligra Document Converter"),
                         K4AboutData::License_GPL,
                         ki18n("(c) 2001-2011 Calligra developers"));
    aboutData.addAuthor(ki18n("David Faure"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Nicolas Goutte"), KLocalizedString(), "*****@*****.**");
    aboutData.addAuthor(ki18n("Dan Leinir Turthra Jensen"), KLocalizedString(), "*****@*****.**");
    KCmdLineArgs::init(argc, argv, &aboutData);

    KCmdLineOptions options;
    options.add("+in", ki18n("Input file"));
    options.add("+out", ki18n("Output file"));
    options.add("backup", ki18n("Make a backup of the destination file"));
    options.add("batch", ki18n("Batch mode: do not show dialogs"));
    options.add("interactive", ki18n("Interactive mode: show dialogs (default)"));
    options.add("mimetype <mime>", ki18n("Mimetype of the output file"));

    // PDF related options.
    options.add("print-orientation <name>", ki18n("The print orientation. This could be either Portrait or Landscape."));
    options.add("print-papersize <name>", ki18n("The paper size. A4, Legal, Letter, ..."));
    options.add("print-margin <size>", ki18n("The size of the paper margin. By default this is 0.2."));

    KCmdLineArgs::addCmdLineOptions(options);

    KApplication app;

    // Get the command line arguments which we have to parse
    KCmdLineArgs *args = KCmdLineArgs::parsedArgs();
    if (args->count() != 2) {
        KCmdLineArgs::usageError(i18n("Two arguments required"));
        return 3;
    }

    const QUrl urlIn = args->url(0);
    const QUrl urlOut = args->url(1);

    // Are we in batch mode or in interactive mode.
    bool batch = args->isSet("batch");
    if (args->isSet("interactive")) {
        batch = false;
    }

    if (args->isSet("backup")) {
        // Code form koDocument.cc
        KIO::UDSEntry entry;
        if (KIO::NetAccess::stat(urlOut, entry, 0L)) {   // this file exists => backup
            kDebug() << "Making backup...";
            QUrl backup(urlOut);
            backup.setPath(urlOut.path() + '~');
            KIO::FileCopyJob *job = KIO::file_copy(urlOut, backup, -1, KIO::Overwrite | KIO::HideProgressInfo);
            job->exec();
        }
    }

    QMimeDatabase db;
    QMimeType inputMimetype = db.mimeTypeForUrl(urlIn);
    if (!inputMimetype.isValid() || inputMimetype.isDefault()) {
        kError() << i18n("Mimetype for input file %1 not found!", urlIn.toDisplayString()) << endl;
        return 1;
    }

    QMimeType outputMimetype;
    if (args->isSet("mimetype")) {
        QString mime = args->getOption("mimetype");
        outputMimetype = db.mimeTypeForName(mime);
        if (! outputMimetype.isValid()) {
            kError() << i18n("Mimetype not found %1", mime) << endl;
            return 1;
        }
    } else {
        outputMimetype = db.mimeTypeForUrl(urlOut);
        if (!outputMimetype.isValid() || outputMimetype.isDefault()) {
            kError() << i18n("Mimetype not found, try using the -mimetype option") << endl;
            return 1;
        }
    }

    QApplication::setOverrideCursor(Qt::WaitCursor);

    QString outputFormat = outputMimetype.name();
    bool ok = false;
    if (outputFormat == "application/pdf") {
        QString orientation = args->getOption("print-orientation");
        QString papersize = args->getOption("print-papersize");
        QString margin = args->getOption("print-margin");
        ok = convertPdf(urlIn, inputMimetype.name(), urlOut, outputFormat, orientation, papersize, margin);
    } else {
        ok = convert(urlIn, inputMimetype.name(), urlOut, outputFormat, batch);
    }

    QTimer::singleShot(0, &app, SLOT(quit()));
    app.exec();

    QApplication::restoreOverrideCursor();

    if (!ok) {
        kError() << i18n("*** The conversion failed! ***") << endl;
        return 2;
    }

    return 0;
}
示例#29
0
void CameraItemPropertiesTab::setCurrentItem(const CamItemInfo& itemInfo, const DMetadata& meta)
{
    if (itemInfo.isNull())
    {
        d->labelFile->setAdjustedText(QString());
        d->labelFolder->setAdjustedText(QString());
        d->labelFileIsReadable->setAdjustedText(QString());
        d->labelFileIsWritable->setAdjustedText(QString());
        d->labelFileDate->setAdjustedText(QString());
        d->labelFileSize->setAdjustedText(QString());
        d->labelImageMime->setAdjustedText(QString());
        d->labelImageDimensions->setAdjustedText(QString());
        d->labelImageRatio->setAdjustedText(QString());
        d->labelNewFileName->setAdjustedText(QString());
        d->labelAlreadyDownloaded->setAdjustedText(QString());

        d->labelPhotoMake->setAdjustedText(QString());
        d->labelPhotoModel->setAdjustedText(QString());
        d->labelPhotoDateTime->setAdjustedText(QString());
        d->labelPhotoLens->setAdjustedText(QString());
        d->labelPhotoAperture->setAdjustedText(QString());
        d->labelPhotoFocalLength->setAdjustedText(QString());
        d->labelPhotoExposureTime->setAdjustedText(QString());
        d->labelPhotoSensitivity->setAdjustedText(QString());
        d->labelPhotoExposureMode->setAdjustedText(QString());
        d->labelPhotoFlash->setAdjustedText(QString());
        d->labelPhotoWhiteBalance->setAdjustedText(QString());

        d->labelVideoAspectRatio->setAdjustedText(QString());
        d->labelVideoAudioBitRate->setAdjustedText(QString());
        d->labelVideoAudioChannelType->setAdjustedText(QString());
        d->labelVideoAudioCompressor->setAdjustedText(QString());
        d->labelVideoDuration->setAdjustedText(QString());
        d->labelVideoFrameRate->setAdjustedText(QString());
        d->labelVideoVideoCodec->setAdjustedText(QString());

        setEnabled(false);
        return;
    }

    setEnabled(true);

    QString str;
    QString unknown(i18n("<i>unknown</i>"));

    // -- Camera file system information ------------------------------------------

    d->labelFile->setAdjustedText(itemInfo.name);
    d->labelFolder->setAdjustedText(itemInfo.folder);

    if (itemInfo.readPermissions < 0)
    {
        str = unknown;
    }
    else if (itemInfo.readPermissions == 0)
    {
        str = i18n("No");
    }
    else
    {
        str = i18n("Yes");
    }

    d->labelFileIsReadable->setAdjustedText(str);

    if (itemInfo.writePermissions < 0)
    {
        str = unknown;
    }
    else if (itemInfo.writePermissions == 0)
    {
        str = i18n("No");
    }
    else
    {
        str = i18n("Yes");
    }

    d->labelFileIsWritable->setAdjustedText(str);

    if (itemInfo.ctime.isValid())
    {
        d->labelFileDate->setAdjustedText(QLocale().toString(itemInfo.ctime, QLocale::ShortFormat));
    }
    else
    {
        d->labelFileDate->setAdjustedText(unknown);
    }

    str = i18n("%1 (%2)", ImagePropertiesTab::humanReadableBytesCount(itemInfo.size), QLocale().toString(itemInfo.size));
    d->labelFileSize->setAdjustedText(str);

    // -- Image Properties --------------------------------------------------

    if (itemInfo.mime == QLatin1String("image/x-raw"))
    {
        d->labelImageMime->setAdjustedText(i18n("RAW Image"));
    }
    else
    {
        QMimeType mimeType = QMimeDatabase().mimeTypeForName(itemInfo.mime);

        if (mimeType.isValid())
        {
            d->labelImageMime->setAdjustedText(mimeType.comment());
        }
        else
        {
            d->labelImageMime->setAdjustedText(itemInfo.mime);    // last fallback
        }
    }

    QString mpixels;
    QSize dims;

    if (itemInfo.width == -1 && itemInfo.height == -1)
    {
        // delayed loading to list faster from UMSCamera
        if (itemInfo.mime == QLatin1String("image/x-raw"))
        {
            dims = meta.getImageDimensions();
        }
        else
        {
            dims = meta.getPixelSize();
        }
    }
    else
    {
        // if available (GPCamera), take dimensions directly from itemInfo
        dims = QSize(itemInfo.width, itemInfo.height);
    }

    mpixels.setNum(dims.width()*dims.height()/1000000.0, 'f', 2);
    str = (!dims.isValid()) ? unknown : i18n("%1x%2 (%3Mpx)",
            dims.width(), dims.height(), mpixels);
    d->labelImageDimensions->setAdjustedText(str);

    if (!dims.isValid()) str = unknown;
    else ImagePropertiesTab::aspectRatioToString(dims.width(), dims.height(), str);

    d->labelImageRatio->setAdjustedText(str);

    // -- Download information ------------------------------------------

    d->labelNewFileName->setAdjustedText(itemInfo.downloadName.isEmpty() ? i18n("<i>unchanged</i>") : itemInfo.downloadName);

    if (itemInfo.downloaded == CamItemInfo::DownloadUnknown)
    {
        str = unknown;
    }
    else if (itemInfo.downloaded == CamItemInfo::DownloadedYes)
    {
        str = i18n("Yes");
    }
    else
    {
        str = i18n("No");
    }

    d->labelAlreadyDownloaded->setAdjustedText(str);

    // -- Photograph information ------------------------------------------
    // Note: If something is changed here, please updated albumfiletip section too.

    QString unavailable(i18n("<i>unavailable</i>"));
    PhotoInfoContainer photoInfo = meta.getPhotographInformation();

    if (photoInfo.isEmpty())
    {
        widget(1)->hide();
    }
    else
    {
        widget(1)->show();
    }

    ImagePropertiesTab::shortenedMakeInfo(photoInfo.make);
    ImagePropertiesTab::shortenedModelInfo(photoInfo.model);
    d->labelPhotoMake->setAdjustedText(photoInfo.make.isEmpty()   ? unavailable : photoInfo.make);
    d->labelPhotoModel->setAdjustedText(photoInfo.model.isEmpty() ? unavailable : photoInfo.model);

    if (photoInfo.dateTime.isValid())
    {
        str = QLocale().toString(photoInfo.dateTime, QLocale::ShortFormat);
        d->labelPhotoDateTime->setAdjustedText(str);
    }
    else
    {
        d->labelPhotoDateTime->setAdjustedText(unavailable);
    }

    d->labelPhotoLens->setAdjustedText(photoInfo.lens.isEmpty() ? unavailable : photoInfo.lens);
    d->labelPhotoAperture->setAdjustedText(photoInfo.aperture.isEmpty() ? unavailable : photoInfo.aperture);

    if (photoInfo.focalLength35mm.isEmpty())
    {
        d->labelPhotoFocalLength->setAdjustedText(photoInfo.focalLength.isEmpty() ? unavailable : photoInfo.focalLength);
    }
    else
    {
        str = i18n("%1 (%2)", photoInfo.focalLength, photoInfo.focalLength35mm);
        d->labelPhotoFocalLength->setAdjustedText(str);
    }

    d->labelPhotoExposureTime->setAdjustedText(photoInfo.exposureTime.isEmpty() ? unavailable : photoInfo.exposureTime);
    d->labelPhotoSensitivity->setAdjustedText(photoInfo.sensitivity.isEmpty() ? unavailable : i18n("%1 ISO", photoInfo.sensitivity));

    if (photoInfo.exposureMode.isEmpty() && photoInfo.exposureProgram.isEmpty())
    {
        d->labelPhotoExposureMode->setAdjustedText(unavailable);
    }
    else if (!photoInfo.exposureMode.isEmpty() && photoInfo.exposureProgram.isEmpty())
    {
        d->labelPhotoExposureMode->setAdjustedText(photoInfo.exposureMode);
    }
    else if (photoInfo.exposureMode.isEmpty() && !photoInfo.exposureProgram.isEmpty())
    {
        d->labelPhotoExposureMode->setAdjustedText(photoInfo.exposureProgram);
    }
    else
    {
        str = QString::fromUtf8("%1 / %2").arg(photoInfo.exposureMode).arg(photoInfo.exposureProgram);
        d->labelPhotoExposureMode->setAdjustedText(str);
    }

    d->labelPhotoFlash->setAdjustedText(photoInfo.flash.isEmpty() ? unavailable : photoInfo.flash);
    d->labelPhotoWhiteBalance->setAdjustedText(photoInfo.whiteBalance.isEmpty() ? unavailable : photoInfo.whiteBalance);

    // -- Video information ------------------------------------------

    VideoInfoContainer videoInfo = meta.getVideoInformation();

    if (videoInfo.isEmpty())
    {
        widget(2)->hide();
    }
    else
    {
        widget(2)->show();
    }

    d->labelVideoAspectRatio->setAdjustedText(videoInfo.aspectRatio.isEmpty()           ? unavailable : videoInfo.aspectRatio);
    d->labelVideoAudioBitRate->setAdjustedText(videoInfo.audioBitRate.isEmpty()         ? unavailable : videoInfo.audioBitRate);
    d->labelVideoAudioChannelType->setAdjustedText(videoInfo.audioChannelType.isEmpty() ? unavailable : videoInfo.audioChannelType);
    d->labelVideoAudioCompressor->setAdjustedText(videoInfo.audioCompressor.isEmpty()   ? unavailable : videoInfo.audioCompressor);
    d->labelVideoDuration->setAdjustedText(videoInfo.duration.isEmpty()                 ? unavailable : videoInfo.duration);
    d->labelVideoFrameRate->setAdjustedText(videoInfo.frameRate.isEmpty()               ? unavailable : videoInfo.frameRate);
    d->labelVideoVideoCodec->setAdjustedText(videoInfo.videoCodec.isEmpty()             ? unavailable : videoInfo.videoCodec);
}
示例#30
0
QVariant DirModel::data(const QModelIndex &index, int role) const
{
//its not for QML
#if defined(REGRESSION_TEST_FOLDERLISTMODEL)
    if (!index.isValid() ||
        (role != Qt::DisplayRole && role != Qt::DecorationRole && role != Qt::BackgroundRole)
       )
    {
        return QVariant();
    }
    if (role == Qt::DecorationRole && index.column() == 0)
    {
        QIcon icon;
        QMimeType mime = mDirectoryContents.at(index.row()).mimeType();
        if (mime.isValid())
        {
            if (QIcon::hasThemeIcon(mime.iconName()) ) {
               icon = QIcon::fromTheme(mime.iconName());
            }
            else if (QIcon::hasThemeIcon(mime.genericIconName())) {
               icon = QIcon::fromTheme(mime.genericIconName());
            }
        }
        if (icon.isNull())
        {
            if (mDirectoryContents.at(index.row()).isLocal())
            {
                icon =  QFileIconProvider().icon(mDirectoryContents.at(index.row()).diskFileInfo());
            }
            else
            if (mDirectoryContents.at(index.row()).isDir())
            {
                icon =  QFileIconProvider().icon(QFileIconProvider::Folder);
            }
            else
            {
                icon =  QFileIconProvider().icon(QFileIconProvider::File);
            }
        }
        return icon;
    }
    if (role == Qt::BackgroundRole && index.column() == 0)
    {
        if (mDirectoryContents.at(index.row()).isSelected())
        {
           //TODO it'd better to get some style or other default
           //     background color
           return QBrush(Qt::lightGray);
        }
        return QVariant();
    }
    role = FileNameRole + index.column();
#else
    if (role < FileNameRole || role > TrackCoverRole) {
        qWarning() << Q_FUNC_INFO << this << "Got an out of range role: " << role;
        return QVariant();
    }

    if (index.row() < 0 || index.row() >= mDirectoryContents.count()) {
        qWarning() << "Attempted to access out of range row: " << index.row();
        return QVariant();
    }

    if (index.column() != 0)
        return QVariant();
#endif

    const DirItemInfo &fi = mDirectoryContents.at(index.row());

    switch (role) {
        case FileNameRole:
            return fi.fileName();
        case AccessedDateRole:
            return fi.lastRead();
        case CreationDateRole:
            return fi.created();
        case ModifiedDateRole:
            return fi.lastModified();
        case FileSizeRole: {
             if (fi.isDir() && fi.isLocal())
             {
                return dirItems(fi.diskFileInfo());
             }
             return fileSize(fi.size());
        }
        case IconSourceRole: {
            const QString &fileName = fi.fileName();

            if (fi.isDir())
                return QLatin1String("image://theme/icon-m-common-directory");

            if (fileName.endsWith(QLatin1String(".jpg"), Qt::CaseInsensitive) ||
                fileName.endsWith(QLatin1String(".png"), Qt::CaseInsensitive)) {
                return QLatin1String("image://nemoThumbnail/") + fi.filePath();
            }

            return "image://theme/icon-m-content-document";
        }
        case FilePathRole:
            return fi.filePath();
        case MimeTypeRole:
            return fi.mimeType().name();
        case MimeTypeDescriptionRole:
            return fi.mimeType().comment();
        case IsDirRole:
            return fi.isDir();
        case IsFileRole:
            return !fi.isDir();
        case IsReadableRole:
            return fi.isReadable();
        case IsWritableRole:
            return fi.isWritable();
        case IsExecutableRole:
            return fi.isExecutable();
        case IsSelectedRole:
            return fi.isSelected();
#ifndef DO_NOT_USE_TAG_LIB
        case TrackTitleRole:
        case TrackArtistRole:
        case TrackAlbumRole:
        case TrackYearRole:
        case TrackNumberRole:
        case TrackGenreRole:
        case TrackLengthRole:
        case TrackCoverRole:
             if (mReadsMediaMetadata && fi.isLocal())
             {
                 return getAudioMetaData(fi.diskFileInfo(), role);
             }
             break;
#endif
        default:
#if !defined(REGRESSION_TEST_FOLDERLISTMODEL)
            // this should not happen, ever
            Q_ASSERT(false);
            qWarning() << Q_FUNC_INFO << this << "Got an unknown role: " << role;
#endif
            break;
    }

    return QVariant();
}