Beispiel #1
0
void KMimeTypeTest::testMimeTypeParent()
{
    // All file-like mimetypes inherit from octet-stream
    const KMimeType::Ptr wordperfect = KMimeType::mimeType("application/vnd.wordperfect");
    QVERIFY(wordperfect);
    QCOMPARE(wordperfect->parentMimeTypes().join(","), QString("application/octet-stream"));
    QVERIFY(wordperfect->is("application/octet-stream"));

    QVERIFY(KMimeType::mimeType("image/svg+xml-compressed")->is("application/x-gzip"));

    // Check that msword derives from ole-storage [it didn't in 0.20, but we added it to kde.xml]
    const KMimeType::Ptr msword = KMimeType::mimeType("application/msword");
    QVERIFY(msword);
    const KMimeType::Ptr olestorage = KMimeType::mimeType("application/x-ole-storage");
    QVERIFY(olestorage);
    QVERIFY(msword->is(olestorage->name()));
    QVERIFY(msword->is("application/octet-stream"));

    const KMimeType::Ptr directory = KMimeType::mimeType("inode/directory");
    QVERIFY(directory);
    QCOMPARE(directory->parentMimeTypes().count(), 0);
    QVERIFY(!directory->is("application/octet-stream"));

    // Check that text/x-patch knows that it inherits from text/plain (it says so explicitly)
    const KMimeType::Ptr plain = KMimeType::mimeType("text/plain");
    const KMimeType::Ptr derived = KMimeType::mimeType("text/x-patch");
    QVERIFY(derived);
    QCOMPARE(derived->parentMimeTypes().join(","), plain->name());
    QVERIFY(derived->is("text/plain"));
    QVERIFY(derived->is("application/octet-stream"));

    // Check that application/x-shellscript inherits from application/x-executable
    // (Otherwise KRun cannot start shellscripts...)
    // This is a test for multiple inheritance...
    const KMimeType::Ptr shellscript = KMimeType::mimeType("application/x-shellscript");
    QVERIFY(shellscript);
    QVERIFY(shellscript->is("text/plain"));
    QVERIFY(shellscript->is("application/x-executable"));
    const QStringList shellParents = shellscript->parentMimeTypes();
    QVERIFY(shellParents.contains("text/plain"));
    QVERIFY(shellParents.contains("application/x-executable"));
    QCOMPARE(shellParents.count(), 2); // only the above two
    const QStringList allShellParents = shellscript->allParentMimeTypes();
    QVERIFY(allShellParents.contains("text/plain"));
    QVERIFY(allShellParents.contains("application/x-executable"));
    QVERIFY(allShellParents.contains("application/octet-stream"));
    // Must be least-specific last, i.e. breadth first.
    QCOMPARE(allShellParents.last(), QString("application/octet-stream"));

    // Check that text/x-mrml knows that it inherits from text/plain (implicitly)
    const KMimeType::Ptr mrml = KMimeType::mimeType("text/x-mrml");
    if (!mrml) {
        QSKIP("kdelibs not installed");
    }
    QVERIFY(mrml->is("text/plain"));
    QVERIFY(mrml->is("application/octet-stream"));
}
Beispiel #2
0
bool Utilities::isM3u(const QString &url)
{
    if (!url.isEmpty()) {
        KMimeType::Ptr result = KMimeType::findByUrl(KUrl(url), 0, true);
        return (result->is("audio/m3u") ||
                result->is("application/vnd.apple.mpegurl") ||
                result->is("audio/x-mpegurl"));
    } else {
        return false;
    }
}
Beispiel #3
0
void AudioPreview::initView( const QString& mimeType )
{
  KUrl url = KUrl::fromPath( m_localFile );
  pic->setText( QString() );
  pic->setPixmap(KIO::pixmapForUrl( url ));
  pic->adjustSize();

  KFileMetaInfo info(m_localFile);
  KMimeType::Ptr mimeptr = KMimeType::mimeType(mimeType);

  QString desc;
  if (info.isValid())
  {
    if (mimeptr->is("audio/mpeg") || mimeptr->is("application/ogg"))
    {
      // following 3 labels might be very long; make sure they get squeezed
      KSqueezedTextLabel *sl;

      sl = new KSqueezedTextLabel(this);
      sl->setText(i18n("Artist: %1", info.item("Artist").value().toString()));

      sl = new KSqueezedTextLabel(this);
      sl->setText(i18n("Title: %1", info.item("Title").value().toString()));

      sl = new KSqueezedTextLabel(this);
      sl->setText(i18n("Comment: %1", info.item("Comment").value().toString()));

      desc.append(i18nc("Bitrate: 160 kbits/s", "Bitrate: %1 %2\n", info.item("Bitrate").value().toString(), info.item("Bitrate").suffix() ));
    }
    desc.append(i18n("Sample rate: %1 %2\n", info.item("Sample Rate").value().toString(), info.item("Sample Rate").suffix() ));
    desc.append(i18n("Length: "));

    /* Calculate length in mm:ss format */
    int length = info.item("Length").value().toInt();
    if (length/60 < 10)
      desc.append("0");
    desc.append(QString("%1:").arg(length/60, 0, 10));
    if (length%60 < 10)
      desc.append("0");
    desc.append(QString("%1\n").arg(length%60, 0, 10));
  }

  description = new QLabel(this);
  description->setText( desc );
  description->adjustSize();
  m_player = KServiceTypeTrader::createInstanceFromQuery<KMediaPlayer::Player>( "KMediaPlayer/Player", QString(), this );
  if ( m_player )
  {
    static_cast<KParts::ReadOnlyPart*>(m_player)->openUrl( url );
    m_player->widget()->show();
  }
}
Beispiel #4
0
void IconApplet::dropEvent(QGraphicsSceneDragDropEvent *event)
{
    if (!KUrl::List::canDecode(event->mimeData())) {
        return;
    }

    KUrl::List urls = KUrl::List::fromMimeData(event->mimeData());
    if (urls.isEmpty()) {
        return;
    }

    event->accept();

    if (m_url.isEmpty()) {
        setUrl(urls.first());
        //TODO: why we don't call updateConstraints()?
        constraintsEvent(Plasma::FormFactorConstraint);
        return;
    } else if (m_service) {
        KRun::run(*m_service, urls, 0);
        return;
    }

    KMimeType::Ptr mimetype = KMimeType::findByUrl(m_url);

    if (m_url.isLocalFile() &&
        ((mimetype && (mimetype->is("application/x-executable") ||
                       mimetype->is("application/x-shellscript"))) ||
          KDesktopFile::isDesktopFile(m_url.toLocalFile()))) {

        if (KDesktopFile::isDesktopFile(m_url.toLocalFile())) {
            //Extract the command from the Desktop file
            KService service(m_url.toLocalFile());
            KRun::run(service, urls, 0);
            return;
        }

        // Just exec the local executable
        QString params;
        foreach (const KUrl &url, urls) {
            if (url.isLocalFile()) {
                params += ' ' + KShell::quoteArg(url.toLocalFile());
            } else {
                params += ' ' + KShell::quoteArg(url.prettyUrl());
            }
        }

        QString commandStr = KShell::quoteArg(m_url.path());
        KRun::runCommand(commandStr + ' ' + params, 0);
    } else if (mimetype && mimetype->is("inode/directory")) {
void DolphinView::updateURL()
{
    KFileView* fileView = (m_iconsView != 0) ? static_cast<KFileView*>(m_iconsView) :
                                               static_cast<KFileView*>(m_detailsView);

    KFileItem* fileItem = fileView->currentFileItem();
    if (fileItem == 0) {
        return;
    }

    if (fileItem->isDir()) {
        // Prefer the local path over the URL. This assures that the
        // volume space information is correct. Assuming that the URL is media:/sda1,
        // and the local path is /windows/C: For the URL the space info is related
        // to the root partition (and hence wrong) and for the local path the space
        // info is related to the windows partition (-> correct).
        const QString localPath(fileItem->localPath());
        if (localPath.isEmpty()) {
            setURL(fileItem->url());
        }
        else {
            setURL(KURL(localPath));
        }
    }
    else if (fileItem->isFile()) {
       // allow to browse through ZIP and tar files
       KMimeType::Ptr mime = fileItem->mimeTypePtr();
       if (mime->is("application/x-zip")) {
           KURL url = fileItem->url();
           url.setProtocol("zip");
           setURL(url);
       }
       else if (mime->is("application/x-tar") ||
                mime->is("application/x-tarz") ||
                mime->is("application/x-tbz") ||
                mime->is("application/x-tgz") ||
                mime->is("application/x-tzo")) {
           KURL url = fileItem->url();
           url.setProtocol("tar");
           setURL(url);
       }
       else {
           fileItem->run();
       }
    }
    else {
        fileItem->run();
    }
}
Beispiel #6
0
void KMimeTypeTest::testAlias()
{
    const KMimeType::Ptr canonical = KMimeType::mimeType("application/xml");
    QVERIFY(canonical);
    KMimeType::Ptr alias = KMimeType::mimeType("text/xml");
    QVERIFY(alias);
    QCOMPARE(alias->name(), QString("application/xml"));

    QVERIFY(alias->is("application/xml"));
    QVERIFY(canonical->is("text/xml"));

    // Test for bug 197346: does nspluginscan see that audio/mp3 already exists?
    bool mustWriteMimeType = !KMimeType::mimeType("audio/mp3");
    QVERIFY(!mustWriteMimeType);
}
Beispiel #7
0
void KMimeTypeTest::testMimeTypeInheritancePerformance()
{
    // Check performance of is(). In kde3 the list of mimetypes with previews had 63 items...
    // We could get it with KServiceTypeTrader::self()->query("ThumbCreator") and the "MimeTypes"
    // property, but this would give variable results and requires other modules installed.
    QStringList mimeTypes; mimeTypes << "image/jpeg" << "image/png" << "image/tiff" << "text/plain" << "text/html";
    mimeTypes += mimeTypes;
    mimeTypes += mimeTypes;
    mimeTypes += mimeTypes;
    QCOMPARE(mimeTypes.count(), 40);
    KMimeType::Ptr mime = KMimeType::mimeType("text/x-chdr");
    QVERIFY(mime);
    QTime dt; dt.start();
    QBENCHMARK {
        QString match;
        foreach (const QString &mt, mimeTypes)
        {
            if (mime->is(mt)) {
                match = mt;
                // of course there would normally be a "break" here, but we're testing worse-case
                // performance here
            }
        }
        QCOMPARE(match, QString("text/plain"));
    }
    // Results on David's machine (April 2009):
    // With the KMimeType::is() code that loaded every parent KMimeType:
    // 3.5 msec / 7,000,000 ticks / 5,021,498 instr. loads per iteration
    // After the QHash for parent mimetypes in ksycoca, removing the need to load full mimetypes:
    // 0.57 msec / 1,115,000 ticks / 938,356 instr. loads per iteration
    // After converting the QMap for aliases into a QHash too:
    // 0.48 msec / 960,000 ticks / 791,404 instr. loads per iteration
    // July 2010: After moving KMimeType out of ksycoca:
    // 0.21 msec / 494,000 ticks / 568,345 instr. loads per iteration
}
bool Cb7Creator::create( const QString &path, int width, int height, QImage &img )
{
    Q_UNUSED(width);
    Q_UNUSED(height);

    bool result( false );

    // Detect mime type.
    const KMimeType::Ptr mime = KMimeType::findByFileContent( path );

    if ( mime->is( "application/x-cb7" ) || mime->name() == "application/x-7z-compressed" ) {
        // 7Z archive.
        result = Cb7Creator::extract7zImage( path );
    } else {
        result = false;
    }

    if( !m_comicCover || !result ) {
        kDebug( KIO_THUMB )<<"Error creating the cb7 thumbnail.";
        return false;
    }

    // Copy the extracted image over to KIO::ThumbCreator's img reference.
    img = m_comicCover->copy();
    delete m_comicCover;

    return result;
}
Beispiel #9
0
QString KFileItem::mimeComment() const
{
    const QString displayType = d->m_entry.stringValue( KIO::UDSEntry::UDS_DISPLAY_TYPE );
    if (!displayType.isEmpty())
        return displayType;

    KMimeType::Ptr mType = determineMimeType();

    bool isLocalUrl;
    KUrl url = mostLocalUrl(isLocalUrl);

    KMimeType::Ptr mime = mimeTypePtr();
    // This cannot move to kio_file (with UDS_DISPLAY_TYPE) because it needs
    // the mimetype to be determined, which is done here, and possibly delayed...
    if (isLocalUrl && mime->is("application/x-desktop")) {
        KDesktopFile cfg( url.toLocalFile() );
        QString comment = cfg.desktopGroup().readEntry( "Comment" );
        if (!comment.isEmpty())
            return comment;
    }

    QString comment = mType->comment( url );
    //kDebug() << "finding comment for " << url.url() << " : " << d->m_pMimeType->name();
    if (!comment.isEmpty())
        return comment;
    else
        return mType->name();
}
Beispiel #10
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;

    KMimeType::Ptr mimeTypePtr = KMimeType::mimeType( mimeType, KMimeType::ResolveAliases );
    if ( mimeTypePtr.isNull() )
      continue;

   if ( mimeTypePtr->is( wantedMimeType ) )
     return true;
  }

  return false;
}
Beispiel #11
0
QString KFileItem::iconName() const
{
    if (d->m_useIconNameCache && !d->m_iconName.isEmpty()) {
        return d->m_iconName;
    }

    d->m_iconName = d->m_entry.stringValue( KIO::UDSEntry::UDS_ICON_NAME );
    if (!d->m_iconName.isEmpty()) {
        d->m_useIconNameCache = d->m_bMimeTypeKnown;
        return d->m_iconName;
    }

    bool isLocalUrl;
    KUrl url = mostLocalUrl(isLocalUrl);

    KMimeType::Ptr mime = mimeTypePtr();
    if (isLocalUrl && mime->is("application/x-desktop")) {
        d->m_iconName = iconFromDesktopFile(url.toLocalFile());
        if (!d->m_iconName.isEmpty()) {
            d->m_useIconNameCache = d->m_bMimeTypeKnown;
            return d->m_iconName;
        }
    }

    // KDE5: handle .directory files here too, and get rid of
    // KFolderMimeType and the url argument in KMimeType::iconName().

    d->m_iconName = mime->iconName(url);
    d->m_useIconNameCache = d->m_bMimeTypeKnown;
    //kDebug() << "finding icon for" << url << ":" << d->m_iconName;
    return d->m_iconName;
}
Beispiel #12
0
bool Utilities::isFSDirectory(const QString& url)
{
    if (!url.isEmpty()) {
        KMimeType::Ptr result = KMimeType::findByUrl(KUrl(url), 0, true);
        return result->is("inode/directory");
    } else {
        return false;
    }
}
Beispiel #13
0
int main(int argc, char **argv) {
	static KCmdLineOptions options[] = {
		{"show", I18N_NOOP("Show window on startup"), 0},
		{"kwalletd", I18N_NOOP("For use by kwalletd only"), 0},
		{"+name", I18N_NOOP("A wallet name"), 0},
		KCmdLineLastOption
	};

	KAboutData about("kwalletmanager", I18N_NOOP("KDE Wallet Manager"), "1.1",
		I18N_NOOP("KDE Wallet Management Tool"),
		KAboutData::License_GPL,
		I18N_NOOP("(c) 2003,2004 George Staikos"), 0,
		"http://www.kde.org/");

	about.addAuthor("George Staikos", I18N_NOOP("Primary author and maintainer"), "*****@*****.**");
	about.addAuthor("Isaac Clerencia", I18N_NOOP("Developer"), "*****@*****.**");

	KCmdLineArgs::init(argc, argv, &about);
	KCmdLineArgs::addCmdLineOptions(options);

	if (!KUniqueApplication::start()) {
		return 0;
	}

	MyApp a;

	KWalletManager wm;
	wm.setCaption(i18n("KDE Wallet Manager"));

	a.setMainWidget(&wm);

	KGlobal::dirs()->addResourceType("kwallet", "share/apps/kwallet");

	KCmdLineArgs *args = KCmdLineArgs::parsedArgs();

	if (args->isSet("show")) {
		wm.show();
	}

	if (args->isSet("kwalletd")) {
		wm.kwalletdLaunch();
	}

	for (int i = 0; i < args->count(); ++i) {
		QString fn = QFileInfo(args->arg(i)).absFilePath();
		KMimeType::Ptr ptr;
		if (QFile::exists(fn) &&
			(ptr = KMimeType::findByFileContent(fn)) &&
			ptr->is("application/x-kde-wallet")) {
			wm.openWalletFile(fn);
		} else {
			wm.openWallet(args->arg(i));
		}
	}
	args->clear();
	return a.exec();
}
Beispiel #14
0
void KNewFileMenuPrivate::executeStrategy()
{
    m_tempFileToDelete = m_copyData.tempFileToDelete();
    const QString src = m_copyData.sourceFileToCopy();
    QString chosenFileName = expandTilde(m_copyData.chosenFileName(), true);

    if (src.isEmpty())
        return;
    KUrl uSrc(src);
    if (uSrc.isLocalFile()) {
        // In case the templates/.source directory contains symlinks, resolve
        // them to the target files. Fixes bug #149628.
        KFileItem item(uSrc, QString(), KFileItem::Unknown);
        if (item.isLink())
            uSrc.setPath(item.linkDest());

        if (!m_copyData.m_isSymlink) {
            // If the file is not going to be detected as a desktop file, due to a
            // known extension (e.g. ".pl"), append ".desktop". #224142.
            QFile srcFile(uSrc.toLocalFile());
            if (srcFile.open(QIODevice::ReadOnly)) {
                KMimeType::Ptr wantedMime = KMimeType::findByUrl(uSrc);
                KMimeType::Ptr mime = KMimeType::findByNameAndContent(m_copyData.m_chosenFileName, srcFile.read(1024));
                //kDebug() << "mime=" << mime->name() << "wantedMime=" << wantedMime->name();
                if (!mime->is(wantedMime->name()))
                    chosenFileName += wantedMime->mainExtension();
            }
        }
    }

    // The template is not a desktop file [or it's a URL one]
    // Copy it.
    KUrl::List::const_iterator it = m_popupFiles.constBegin();
    for (; it != m_popupFiles.constEnd(); ++it)
    {
        KUrl dest(*it);
        dest.addPath(KIO::encodeFileName(chosenFileName));

        KUrl::List lstSrc;
        lstSrc.append(uSrc);
        KIO::Job* kjob;
        if (m_copyData.m_isSymlink) {
            kjob = KIO::symlink(src, dest);
            // This doesn't work, FileUndoManager registers new links in copyingLinkDone,
            // which KIO::symlink obviously doesn't emit... Needs code in FileUndoManager.
            //KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Link, lstSrc, dest, kjob);
        } else {
            //kDebug(1203) << "KIO::copyAs(" << uSrc.url() << "," << dest.url() << ")";
            KIO::CopyJob * job = KIO::copyAs(uSrc, dest);
            job->setDefaultPermissions(true);
            kjob = job;
            KIO::FileUndoManager::self()->recordJob(KIO::FileUndoManager::Copy, lstSrc, dest, job);
        }
        kjob->ui()->setWindow(m_parentWidget);
        QObject::connect(kjob, SIGNAL(result(KJob*)), q, SLOT(slotResult(KJob*)));
    }
}
Beispiel #15
0
bool Utilities::isPls(const QString &url)
{
    if (!url.isEmpty()) {
        KMimeType::Ptr result = KMimeType::findByUrl(KUrl(url), 0, true);
        return result->is("audio/x-scpls");
    } else {
        return false;
    }
}
Beispiel #16
0
KParts::ReadOnlyPart *KWebDesktop::createPart(const QString &mimeType)
{
    delete m_part;
    m_part = 0;

    KMimeType::Ptr mime = KMimeType::mimeType(mimeType);
    if(!mime || mime == KMimeType::defaultMimeTypePtr())
        return 0;
    if(mime->is("text/html") || mime->is("text/xml") || mime->is("application/xhtml+xml"))
    {
        KHTMLPart *htmlPart = new KHTMLPart;
        htmlPart->widget()->resize(m_width, m_height);

        htmlPart->setMetaRefreshEnabled(false);
        htmlPart->setJScriptEnabled(false);
        htmlPart->setJavaEnabled(false);

        ((QScrollView *)htmlPart->widget())->setHScrollBarMode(QScrollView::AlwaysOff);
        ((QScrollView *)htmlPart->widget())->setVScrollBarMode(QScrollView::AlwaysOff);

        connect(htmlPart, SIGNAL(completed()), this, SLOT(slotCompleted()));
        m_part = htmlPart;
    }
    else
    {
        // Try to find an appropriate viewer component
        m_part = KParts::ComponentFactory::createPartInstanceFromQuery< KParts::ReadOnlyPart >(mimeType, QString::null, 0, 0, this, 0);
        if(!m_part)
            kdWarning() << "No handler found for " << mimeType << endl;
        else
        {
            kdDebug() << "Loaded " << m_part->className() << endl;
            connect(m_part, SIGNAL(completed()), this, SLOT(slotCompleted()));
        }
    }
    if(m_part)
    {
        connect(m_part, SIGNAL(canceled(const QString &)), this, SLOT(slotCompleted()));
    }
    return m_part;
}
Beispiel #17
0
void Frame::setImage(const QString &path)
{
    if (d->imagePath == path) {
        return;
    }

    delete d->image;
    d->image = 0;
    d->imagePath = path;
    delete d->pixmap;
    d->pixmap = 0;

    bool absolutePath = !path.isEmpty() &&
                        #ifdef Q_WS_WIN
                            !QDir::isRelativePath(path)
                        #else
                            (path[0] == '/' || path.startsWith(QLatin1String(":/")))
                        #endif
        ;

    if (absolutePath) {
        d->absImagePath = path;
    } else {
        //TODO: package support
        d->absImagePath = Theme::defaultTheme()->imagePath(path);
    }

    if (path.isEmpty()) {
        return;
    }

    KMimeType::Ptr mime = KMimeType::findByPath(d->absImagePath);

    if (!mime->is("image/svg+xml") && !mime->is("application/x-gzip")) {
        d->pixmap = new QPixmap(d->absImagePath);
    } else {
        d->image = new Plasma::Svg(this);
        d->image->setImagePath(path);
    }
}
Beispiel #18
0
 /* TODO This looses the current expanded tree's.
  * Needs to update the model rahter than replace it.
  */
void XmlTree::update ( const KMimeType::Ptr mime,  const QDomDocument& doc ) {
    setModel ( 0 );
    if ( m_treeModel )
        delete m_treeModel;
    if ( mime->is ( "application/xsd" ) )
        m_treeModel = new XsdDocumentModel();
    else
        m_treeModel = new XmlDocumentModel();
    m_treeModel->update ( doc );
    setModel ( m_treeModel );
    expandToDepth ( 0 );
    resizeColumnToContents ( 0 );
    resizeColumnToContents ( 1 );
}
Beispiel #19
0
bool KPreviewPropsPlugin::supports( const KFileItemList &_items )
{
    if ( _items.count() != 1 )
        return false;
    bool metaDataEnabled = KGlobalSettings::showFilePreview(_items.first().url());
    if (!metaDataEnabled)
        return false;
    const KMimeType::Ptr mime = _items.first().mimeTypePtr();
    const QStringList supportedMimeTypes = KIO::PreviewJob::supportedMimeTypes();
    foreach(const QString& supportedMime, supportedMimeTypes) {
        if (mime->is(supportedMime))
    return true;
    }
    return false;
}
Beispiel #20
0
bool Utilities::isVideo(const QString &url)
{
    if (!url.isEmpty()) {
        KMimeType::Ptr result = KMimeType::findByUrl(KUrl(url), 0, true);
        //NOTE: Special handling for .wma extensions
        //It turns out that wma files may pass the "video/x-ms-asf" mimetype test.
        //Per Microsoft KB284094, the only way to distinguish between audio-only
        //and audio+video content is to look at the file extenstion.
        if (result->is("video/x-ms-asf") && KUrl(url).fileName().endsWith(QLatin1String(".wma"))) {
            return false;
        }
        return isVideoMimeType(result);
    } else {
        return false;
    }
}
Beispiel #21
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;

  KMimeType::Ptr mimeTypePtr = KMimeType::mimeType( mimeType, KMimeType::ResolveAliases );
  if ( mimeTypePtr.isNull() )
    return false;

  return mimeTypePtr->is( wantedMimeType );
}
Beispiel #22
0
/**
 * Returns true if this is a desktop file.
 * Mimetype determination is optional.
 */
static bool checkDesktopFile(const KFileItem& item, bool _determineMimeType)
{
    // only local files
    bool isLocal;
    const KUrl url = item.mostLocalUrl(isLocal);
    if (!isLocal)
        return false;

    // only regular files
    if (!item.isRegularFile())
        return false;

    // only if readable
    if (!item.isReadable())
        return false;

    // return true if desktop file
    KMimeType::Ptr mime = _determineMimeType ? item.determineMimeType() : item.mimeTypePtr();
    return mime->is("application/x-desktop");
}
Beispiel #23
0
bool KonqRun::tryOpenView(const QString& mimeType, bool associatedAppIsKonqueror)
{
    KMimeType::Ptr mime = KMimeType::mimeType(mimeType, KMimeType::ResolveAliases);
    if (associatedAppIsKonqueror)
        m_req.forceAutoEmbed = true;

    // When text/html is associated with another browser,
    // we need to find out if we should keep browsing the web in konq,
    // or if we are clicking on an html file in a directory view (which should
    // then open the other browser)
    else if (mime &&
             (mime->is("text/html")
              || mime->name().startsWith("image/")) // #83513
              && (m_pView && !m_pView->showsDirectory())) {
            m_req.forceAutoEmbed = true;
    }

    const bool ok = m_pMainWindow->openView(mimeType, KRun::url(), m_pView, m_req);
    setFinished(ok);
    return ok;
}
Beispiel #24
0
/** Return true, if the url belong to the mimetype group. */
bool QuantaCommon::checkMimeGroup(const KUrl& url, const QString& group)
{
 bool status = false;
 KMimeType::Ptr mime = KMimeType::findByUrl(url);
 QString mimetype = mime->name();
 mimetype = mimetype.section('/',-1);
#if 0
 // This is really a slow way to lookup one mimetype - why do it this way? (DF)
 const KMimeType::List list = KMimeType::allMimeTypes(); // slow. We need a allMimeTypeNames for this.
 KMimeType::List::const_iterator it;
 for ( it = list.begin(); it != list.end(); ++it )
 {
    // ## why indexOf and not just == ?
    if ( ((*it)->name().startsWith(group)) && ((*it)->name().indexOf(mimetype) != -1)
)    {
      status = true;
      break;
    }
 }
#endif
 status = mime->name().startsWith(group);

 if (!status && group == "text")
 {
   if (url.isLocalFile())
   {
     status = !KMimeType::isBinaryData(url.path());
   } else
   {
     status = mime->is("text/plain");
   }
 }
 if (!status && group == "text" && mimetype == "x-zerosize")
     status = true;

 return status;
}
bool RKWorkplace::openAnyUrl (const KUrl &url) {
	RK_TRACE (APP);

#warning TODO support rkward:\/\/-protocol, here, too
	KMimeType::Ptr mimetype = KMimeType::findByUrl (url);
	if (mimetype->is ("text/html")) {
		openHelpWindow (url, true);
		return true;	// TODO
	}
	if (url.fileName ().toLower ().endsWith (".rdata")) {
		RKWardMainWindow::getMain ()->fileOpenAskSave (url);
		return true;	// TODO
	}
	if (mimetype->name ().startsWith ("text")) {
		return (openScriptEditor (url, QString (), false));
	}

	if (KMessageBox::questionYesNo (this, i18n ("The url you are trying to open ('%1') is not a local file or the filetype is not supported by RKWard. Do you want to open the url in the default application?", url.prettyUrl ()), i18n ("Open in default application?")) != KMessageBox::Yes) {
		return false;
	}
	KRun *runner = new KRun (url, topLevelWidget());		// according to KRun-documentation, KRun will self-destruct when done.
	runner->setRunExecutables (false);
	return false;
}
Beispiel #26
0
static void extractMimeTypeFor(const QUrl& url, QString& mimeType)
{
    const QString fname(url.fileName());
 
    if (fname.isEmpty() || url.hasFragment() || url.hasQuery())
        return;
 
    KMimeType::Ptr pmt = KMimeType::findByPath(fname, 0, true);

    // Further check for mime types guessed from the extension which,
    // on a web page, are more likely to be a script delivering content
    // of undecidable type. If the mime type from the extension is one
    // of these, don't use it.  Retain the original type 'text/html'.
    if (pmt->name() == KMimeType::defaultMimeType() ||
        pmt->is(QL1S("application/x-perl")) ||
        pmt->is(QL1S("application/x-perl-module")) ||
        pmt->is(QL1S("application/x-php")) ||
        pmt->is(QL1S("application/x-python-bytecode")) ||
        pmt->is(QL1S("application/x-python")) ||
        pmt->is(QL1S("application/x-shellscript")))
        return;

    mimeType = pmt->name();
}
Beispiel #27
0
void KNewFileMenuPrivate::fillMenu()
{
    QMenu* menu = q->menu();
    menu->clear();
    m_menuDev->menu()->clear();
    m_newDirAction = 0;

    QSet<QString> seenTexts;
    // these shall be put at special positions
    QAction* linkURL = 0;
    QAction* linkApp = 0;
    QAction* linkPath = 0;

    KNewFileMenuSingleton* s = kNewMenuGlobals;
    int i = 1;
    KNewFileMenuSingleton::EntryList::iterator templ = s->templatesList->begin();
    const KNewFileMenuSingleton::EntryList::iterator templ_end = s->templatesList->end();
    for (; templ != templ_end; ++templ, ++i)
    {
        KNewFileMenuSingleton::Entry& entry = *templ;
        if (entry.entryType != KNewFileMenuSingleton::Separator) {
            // There might be a .desktop for that one already, if it's a kdelnk
            // This assumes we read .desktop files before .kdelnk files ...

            // In fact, we skip any second item that has the same text as another one.
            // Duplicates in a menu look bad in any case.

            const bool bSkip = seenTexts.contains(entry.text);
            if (bSkip) {
                kDebug(1203) << "skipping" << entry.filePath;
            } else {
                seenTexts.insert(entry.text);
                //const KNewFileMenuSingleton::Entry entry = templatesList->at(i-1);

                const QString templatePath = entry.templatePath;
                // The best way to identify the "Create Directory", "Link to Location", "Link to Application" was the template
                if (templatePath.endsWith("emptydir")) {
                    QAction * act = new QAction(q);
                    m_newDirAction = act;
                    act->setIcon(KIcon(entry.icon));
                    act->setText(entry.text);
                    act->setActionGroup(m_newMenuGroup);
                    menu->addAction(act);

                    QAction *sep = new QAction(q);
                    sep->setSeparator(true);
                    menu->addAction(sep);
                } else {

                    if (!m_supportedMimeTypes.isEmpty()) {
                        bool keep = false;

                        // We need to do mimetype filtering, for real files.
                        const bool createSymlink = entry.templatePath == "__CREATE_SYMLINK__";
                        if (createSymlink) {
                            keep = true;
                        } else if (!KDesktopFile::isDesktopFile(entry.templatePath)) {

                            // Determine mimetype on demand
                            KMimeType::Ptr mime;
                            if (entry.mimeType.isEmpty()) {
                                mime = KMimeType::findByPath(entry.templatePath);
                                if (mime) {
                                    //kDebug() << entry.templatePath << "is" << mime->name();
                                    entry.mimeType = mime->name();
                                } else {
                                    entry.mimeType = KMimeType::defaultMimeType();
                                }
                            } else {
                                mime = KMimeType::mimeType(entry.mimeType);
                            }
                            Q_FOREACH(const QString& supportedMime, m_supportedMimeTypes) {
                                if (mime && mime->is(supportedMime)) {
                                    keep = true;
                                    break;
                                }
                            }
                        }

                        if (!keep) {
                            //kDebug() << "Not keeping" << entry.templatePath;
                            continue;
                        }
                    }

                    QAction * act = new QAction(q);
                    act->setData(i);
                    act->setIcon(KIcon(entry.icon));
                    act->setText(entry.text);
                    act->setActionGroup(m_newMenuGroup);

                    //kDebug() << templatePath << entry.filePath;

                    if (templatePath.endsWith("/URL.desktop")) {
                        linkURL = act;
                    } else if (templatePath.endsWith("/Program.desktop")) {
                        linkApp = act;
                    } else if (entry.filePath.endsWith("/linkPath.desktop")) {
                        linkPath = act;
                    } else if (KDesktopFile::isDesktopFile(templatePath)) {
                        KDesktopFile df(templatePath);
                        if (df.readType() == "FSDevice")
                            m_menuDev->menu()->addAction(act);
                        else
                            menu->addAction(act);
                    }
                    else
                    {
                        menu->addAction(act);
                    }
                }
            }
        } else { // Separate system from personal templates
Beispiel #28
0
TagLib::File *MimeTypeFileTypeResolver::createFile(const char *fileName,
        bool readProperties,
        TagLib::AudioProperties::ReadStyle propertiesStyle) const
{
    QString fn = QFile::decodeName( fileName );
    int accuracy = 0;

    KMimeType::Ptr mimetype = KMimeType::findByFileContent( fn, &accuracy );
    if( accuracy <= 0 )
        mimetype = KMimeType::findByPath( fn );

    if( mimetype->is( "audio/aac" )
            || mimetype->is( "audio/mpeg" )
            || mimetype->is( "audio/mpegurl" )
            || mimetype->is( "audio/x-mpegurl" )
            || mimetype->is( "audio/x-mp3" ))
    {
        return new TagLib::MPEG::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/mp4" ) || mimetype->is( "video/mp4" ) )
    {
        return new TagLib::MP4::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/x-ms-wma" )
            || mimetype->is( "video/x-ms-asf" )
            || mimetype->is( "video/x-msvideo" )
            || mimetype->is( "video/x-ms-wmv" ) )
    {
        return new TagLib::ASF::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/vnd.rn-realaudio" )
            || mimetype->is( "audio/x-pn-realaudio" )
            || mimetype->is( "audio/x-pn-realaudioplugin" )
            || mimetype->is( "audio/vnd.rn-realvideo" ) )
    {
        return new TagLib::RealMedia::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/vorbis" ) )
    {
        return new TagLib::Ogg::Vorbis::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/x-oggflac" ) )
    {
        return new TagLib::Ogg::FLAC::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/x-flac" ) )
    {
        return new TagLib::FLAC::File(fileName, readProperties, propertiesStyle);
    }
    else if( mimetype->is( "audio/x-musepack" ) )
    {
        return new TagLib::MPC::File(fileName, readProperties, propertiesStyle);
    }

    debug() << "kmimetype filetype guessing failed for" << fileName << endl;

    return 0;
}
TagLib::File *Meta::Tag::FileTypeResolver::createFile(TagLib::FileName fileName,
        bool readProperties,
        TagLib::AudioProperties::ReadStyle propertiesStyle) const
{
    TagLib::File* result = 0;

    QString fn = QFile::decodeName(fileName);
    QString suffix = QFileInfo(fn).suffix();

    #ifdef ENABLE_KDE_SUPPORT
    KMimeType::Ptr mimetype = KMimeType::findByPath(fn);

    // -- check by mime type
    if (mimetype->is(QLatin1String("audio/mpeg")) || mimetype->is(QLatin1String("audio/x-mpegurl"))
            || mimetype->is(QLatin1String("audio/mpeg"))) {
        result = new TagLib::MPEG::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/mp4")) || mimetype->is(QLatin1String("video/mp4"))) {
        result = new TagLib::MP4::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-ms-wma")) /*|| mimetype->is(QLatin1String("video/x-ms-asf"))
            || mimetype->is(QLatin1String("video/x-msvideo")) || mimetype->is(QLatin1String("video/x-ms-wmv"))*/) {
        result = new TagLib::ASF::File(fileName, readProperties, propertiesStyle);
    }
    #ifdef TAGLIB_EXTRAS_FOUND
    else if (mimetype->is(QLatin1String("audio/vnd.rn-realaudio")) || mimetype->is(QLatin1String("audio/x-pn-realaudioplugin"))
            /*|| mimetype->is(QLatin1String("audio/vnd.rn-realvideo"))*/) {
        result = new TagLibExtras::RealMedia::File(fileName, readProperties, propertiesStyle);
    }
    #endif
    #ifdef TAGLIB_OPUS_FOUND
    else if (mimetype->is(QLatin1String("audio/opus")) || mimetype->is(QLatin1String("audio/x-opus+ogg"))) {
        result = new TagLib::Ogg::Opus::File(fileName, readProperties, propertiesStyle);
    }
    #endif
    else if (mimetype->is(QLatin1String("audio/x-vorbis+ogg"))) {
        result = new TagLib::Ogg::Vorbis::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-flac+ogg"))) {
        result = new TagLib::Ogg::FLAC::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-aiff"))) {
        result = new TagLib::RIFF::AIFF::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-flac"))) {
        result = new TagLib::FLAC::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-musepack"))) {
        result = new TagLib::MPC::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-wav"))) {
        result = new TagLib::RIFF::WAV::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-wavpack"))) {
        result = new TagLib::WavPack::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-tta"))) {
        result = new TagLib::TrueAudio::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-speex")) || mimetype->is(QLatin1String("audio/x-speex+ogg"))) {
        result = new TagLib::TrueAudio::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-speex")) || mimetype->is(QLatin1String("audio/x-speex+ogg"))) {
        result = new TagLib::TrueAudio::File(fileName, readProperties, propertiesStyle);
    } else if (mimetype->is(QLatin1String("audio/x-ape"))) {
        result = new TagLib::APE::File(fileName, readProperties, propertiesStyle);
    }

    // -- check by extension
    #else // ENABLE_KDE_SUPPORT
    if (suffix == QLatin1String("mp3")) {
        result = new TagLib::MPEG::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("flac")) {
        result = new TagLib::FLAC::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("ogg")) {
        result = new TagLib::Ogg::Vorbis::File(fileName, readProperties, propertiesStyle);
        if (!result->isValid()) {
            delete result;
            result = new TagLib::Ogg::FLAC::File(fileName, readProperties, propertiesStyle);
        }
        if (!result->isValid()) {
            delete result;
            result = new TagLib::TrueAudio::File(fileName, readProperties, propertiesStyle);
        }
        #ifdef TAGLIB_OPUS_FOUND
        if (!result->isValid()) {
            delete result;
            result = new TagLib::Ogg::Opus::File(fileName, readProperties, propertiesStyle);
        }
        #endif
    }
    #endif //
    else if (suffix == QLatin1String("m4a") || suffix == QLatin1String("m4b")
        || suffix == QLatin1String("m4p") || suffix == QLatin1String("mp4")
        /*|| suffix == QLatin1String("m4v") || suffix == QLatin1String("mp4v") */) {
        result = new TagLib::MP4::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("wav")) {
        result = new TagLib::RIFF::WAV::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("wma") /*|| suffix == QLatin1String("asf")*/) {
        result = new TagLib::ASF::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("wvp") || suffix == QLatin1String("wv")) {
        result = new TagLib::WavPack::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("ape")) {
        result = new TagLib::APE::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("spx")) {
        result = new TagLib::TrueAudio::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("tta")) {
        result = new TagLib::TrueAudio::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("aiff") || suffix == QLatin1String("aif") || suffix == QLatin1String("aifc")) {
        result = new TagLib::RIFF::AIFF::File(fileName, readProperties, propertiesStyle);
    } else if (suffix == QLatin1String("mpc") || suffix == QLatin1String("mpp") || suffix == QLatin1String("mp+")) {
        result = new TagLib::MPC::File(fileName, readProperties, propertiesStyle);
    }
    #ifdef TAGLIB_OPUS_FOUND
    else if (suffix == QLatin1String("opus")) {
        result = new TagLib::Ogg::Opus::File(fileName, readProperties, propertiesStyle);
    }
    #endif

    if (result && !result->isValid()) {
        delete result;
        result = 0;
    }

    return result;
}
Beispiel #30
0
bool TextCreator::create(const QString &path, int width, int height, QImage &img)
{
    // Filter out unwanted mimetypes
    KMimeType::Ptr mimeType = KMimeType::findByPath(path);
    if(mimeType->is("text/rtf"))
        return false;

    if(!m_splitter)
    {
        m_splitter = new KPixmapSplitter;
        QString pixmap = locate("data", "konqueror/pics/thumbnailfont_7x4.png");
        if(!pixmap.isEmpty())
        {
            // FIXME: make font/glyphsize configurable...
            m_splitter->setPixmap(QPixmap(pixmap));
            m_splitter->setItemSize(QSize(4, 7));
        }
    }

    bool ok = false;

    // determine some sizes...
    // example: width: 60, height: 64
    QSize pixmapSize(width, height);
    if(height * 3 > width * 4)
        pixmapSize.setHeight(width * 4 / 3);
    else
        pixmapSize.setWidth(height * 3 / 4);

    if(pixmapSize != m_pixmap.size())
        m_pixmap.resize(pixmapSize);

    // one pixel for the rectangle, the rest. whitespace
    int xborder = 1 + pixmapSize.width() / 16;  // minimum x-border
    int yborder = 1 + pixmapSize.height() / 16; // minimum y-border

    QSize chSize = m_splitter->itemSize(); // the size of one char
    int xOffset = chSize.width();
    int yOffset = chSize.height();

    // calculate a better border so that the text is centered
    int canvasWidth = pixmapSize.width() - 2 * xborder;
    int canvasHeight = pixmapSize.height() - 2 * yborder;
    int numCharsPerLine = (int)(canvasWidth / chSize.width());
    int numLines = (int)(canvasHeight / chSize.height());

    // assumes an average line length of <= 120 chars
    const int bytesToRead = 120 * numLines;

    // create text-preview
    QFile file(path);
    if(file.open(IO_ReadOnly))
    {
        if(!m_data || m_dataSize < bytesToRead + 1)
        {
            delete[] m_data;
            m_data = new char[bytesToRead + 1];
            m_dataSize = bytesToRead + 1;
        }

        int read = file.readBlock(m_data, bytesToRead);
        if(read > 0)
        {
            ok = true;
            m_data[read] = '\0';
            QString text = QString::fromLocal8Bit(m_data);
            // FIXME: maybe strip whitespace and read more?

            m_pixmap.fill(QColor(245, 245, 245)); // light-grey background

            QRect rect;

            int rest = m_pixmap.width() - (numCharsPerLine * chSize.width());
            xborder = QMAX(xborder, rest / 2); // center horizontally
            rest = m_pixmap.height() - (numLines * chSize.height());
            yborder = QMAX(yborder, rest / 2); // center vertically
            // end centering

            int x = xborder, y = yborder; // where to paint the characters
            int posNewLine = m_pixmap.width() - (chSize.width() + xborder);
            int posLastLine = m_pixmap.height() - (chSize.height() + yborder);
            bool newLine = false;
            Q_ASSERT(posNewLine > 0);
            const QPixmap *fontPixmap = &(m_splitter->pixmap());

            for(uint i = 0; i < text.length(); i++)
            {
                if(x > posNewLine || newLine) // start a new line?
                {
                    x = xborder;
                    y += yOffset;

                    if(y > posLastLine) // more text than space
                        break;

                    // after starting a new line, we also jump to the next
                    // physical newline in the file if we don't come from one
                    if(!newLine)
                    {
                        int pos = text.find('\n', i);
                        if(pos == -1)
                            break;
                        i = pos + 1;
                    }

                    newLine = false;
                }

                // check for newlines in the text (unix,dos)
                QChar ch = text.at(i);
                if(ch == '\n')
                {
                    newLine = true;
                    continue;
                }
                else if(ch == '\r' && text.at(i + 1) == '\n')
                {
                    newLine = true;
                    i++; // skip the next character (\n) as well
                    continue;
                }

                rect = m_splitter->coordinates(ch);
                if(!rect.isEmpty())
                {
                    bitBlt(&m_pixmap, QPoint(x, y), fontPixmap, rect, Qt::CopyROP);
                }

                x += xOffset; // next character
            }
            if(ok)
                img = m_pixmap.convertToImage();
        }

        file.close();
    }
    return ok;
}