Example #1
0
void KMimeTypeTest::testFindByUrl()
{
    // Tests with local files are already done in testFindByPath,
    // here we test for remote urls only.
    KMimeType::Ptr mime;
    mime = KMimeType::findByUrl(KUrl("http://foo/bar.png"));
    QVERIFY(mime);

    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));     // HTTP can't know before downloading

    mime = KMimeType::findByUrl(KUrl("http://foo/s0/"));
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));     // HTTP can't know before downloading

#if 0 // no such logic in QMimeType, we get default mimetype, KRun will figure it out
    if (!KProtocolInfo::isKnownProtocol(KUrl("man:/"))) {
        QSKIP("man protocol not installed");
    }

    mime = KMimeType::findByUrl(KUrl("man:/ls"));
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("text/html"));

    mime = KMimeType::findByUrl(KUrl("man:/ls/"));
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("text/html"));
#endif

    mime = KMimeType::findByUrl(KUrl("fish://host/test1")); // like fish does, to test for known extensions
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));
}
Example #2
0
void KMimeTypeTest::testFindByUrl()
{
    // Tests with local files are already done in testFindByPath,
    // here we test for remote urls only.
    KMimeType::Ptr mime;
    QVERIFY( KProtocolInfo::isKnownProtocol(KUrl("http:/")) );
    QVERIFY( KProtocolInfo::isKnownProtocol(KUrl("file:/")) );
    mime = KMimeType::findByUrl( KUrl("http://foo/bar.png") );
    QVERIFY( mime );

    QCOMPARE( mime->name(), QString::fromLatin1( "application/octet-stream" ) ); // HTTP can't know before downloading

    if ( !KProtocolInfo::isKnownProtocol(KUrl("man:/")) )
        QSKIP( "man protocol not installed", SkipSingle );

    mime = KMimeType::findByUrl( KUrl("man:/ls") );
    QVERIFY( mime );
    QCOMPARE( mime->name(), QString::fromLatin1("text/html") );

    mime = KMimeType::findByUrl( KUrl("man:/ls/") );
    QVERIFY( mime );
    QCOMPARE( mime->name(), QString::fromLatin1("text/html") );

    mime = KMimeType::findByUrl(KUrl("fish://host/test1")); // like fish does, to test for known extensions
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));
}
Example #3
0
void KMimeTypeTest::testAllMimeTypes()
{
    const KMimeType::List lst = KMimeType::allMimeTypes(); // does NOT include aliases
    QVERIFY(!lst.isEmpty());

    for (KMimeType::List::ConstIterator it = lst.begin();
            it != lst.end(); ++it) {
        const KMimeType::Ptr mime = (*it);
        const QString name = mime->name();
        //qDebug( "%s", qPrintable( name ) );
        QVERIFY(!name.isEmpty());
        QCOMPARE(name.count('/'), 1);

        const KMimeType::Ptr lookedupMime = KMimeType::mimeType(name);
        QVERIFY(lookedupMime);   // not null
        if (name != "application/vnd.ms-word" && name != "application/x-pkcs7-certificates"
                && name != "application/x-x509-ca-cert"
                && name != "application/x-vnd.kde.kexi" // due to /usr/share/mime/packages/kde.xml from KDE4
                && name != "application/x-kexiproject-sqlite" // due to /usr/share/mime/packages/kde.xml from KDE4
                && name != "application/vnd.sun.xml.base" // libreoffice.xml messing things up yet again
           ) {
            QCOMPARE(lookedupMime->name(), name);
            // if this fails, you have an alias defined as a real mimetype too!
            //
            // Note: this also happens with x-win-lnk when your kde.xml defines it as an alias, while
            // /usr/share/mime/packages/kde.xml defines it as a real mimetype. This is a false positive,
            // remove one of the kde.xml files.
            //
            // It also happens with application/x-pkcs7-certificates due to
            // /usr/share/mime/packages/gcr-crypto-types.xml. Remove that file and run
            // `update-mime-database /usr/share/mime`.
        }
    }
}
Example #4
0
void URLGrabber::matchingMimeActions(const QString& clipData)
{
    KUrl url(clipData);
    KConfigGroup cg(KGlobal::config(), "Actions");
    if(!cg.readEntry("EnableMagicMimeActions",true)) {
        //kDebug() << "skipping mime magic due to configuration";
        return;
    }
    if(!url.isValid()) {
        //kDebug() << "skipping mime magic due to invalid url";
        return;
    }
    if(url.isRelative()) {  //openinng a relative path will just not work. what path should be used?
        //kDebug() << "skipping mime magic due to relative url";
        return;
    }
    if(url.isLocalFile()) {
        if ( clipData == "//") {
            //kDebug() << "skipping mime magic due to C++ comment //";
            return;
        }
        if(!QFile::exists(url.toLocalFile())) {
            //kDebug() << "skipping mime magic due to nonexistent localfile";
            return;
        }
    }

    // try to figure out if clipData contains a filename
    KMimeType::Ptr mimetype = KMimeType::findByUrl( url, 0,
                                                    false,
                                                    true /*fast mode*/ );

    // let's see if we found some reasonable mimetype.
    // If we do we'll populate menu with actions for apps
    // that can handle that mimetype

    // first: if clipboard contents starts with http, let's assume it's "text/html".
    // That is even if we've url like "http://www.kde.org/somescript.pl", we'll
    // still treat that as html page, because determining a mimetype using kio
    // might take a long time, and i want this function to be quick!
    if ( ( clipData.startsWith( QLatin1String("http://") ) || clipData.startsWith( QLatin1String("https://") ) )
         && mimetype->name() != "text/html" )
    {
        // use a fake path to create a mimetype that corresponds to "text/html"
        mimetype = KMimeType::findByPath( "/tmp/klipper.html", 0, true /*fast mode*/ );
    }

    if ( !mimetype->isDefault() ) {
        ClipAction* action = new ClipAction( QString(), mimetype->comment() );
        KService::List lst = KMimeTypeTrader::self()->query( mimetype->name(), "Application" );
        foreach( const KService::Ptr &service, lst ) {
            QHash<QChar,QString> map;
            map.insert( 'i', "--icon " + service->icon() );
            map.insert( 'c', service->name() );

            QString exec = service->exec();
            exec = KMacroExpander::expandMacros( exec, map ).trimmed();

            action->addCommand( ClipCommand( exec, service->name(), true, service->icon() ) );
        }
Example #5
0
void ProjectView::slotClicked(QTreeWidgetItem *item)
{
	if(!item) {
		item = currentItem();
	}

	ProjectViewItem *itm = static_cast<ProjectViewItem*>(item);
	if(itm) {
		if(itm->type() == KileType::File) {
			emit(fileSelected(itm->url()));
		}
		else if(itm->type() == KileType::ProjectItem) {
			emit(fileSelected(itm->projectItem()));
		}
		else if(itm->type() != KileType::Folder) {
			// don't open project configuration files (*.kilepr)
			if(itm->url().toLocalFile().right(7) != ".kilepr") {
				//determine mimeType and open file with preferred application
				KMimeType::Ptr pMime = KMimeType::findByUrl(itm->url());
				if(pMime->name().startsWith("text/")) {
					emit(fileSelected(itm->url()));
				}
				else {
					KRun::runUrl(itm->url(), pMime->name(), this);
				}
			}
		}
		clearSelection();
	}
}
Example #6
0
void KMimeTypeTest::testFindByNameAndContent()
{
    KMimeType::Ptr mime;

    QByteArray textData = "Hello world";
    // textfile -> text/plain. No extension -> mimetype is found from the contents.
    mime = KMimeType::findByNameAndContent("textfile", textData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("text/plain"));

    // textfile.foo -> text/plain. Unknown extension -> mimetype is found from the contents.
    mime = KMimeType::findByNameAndContent("textfile.foo", textData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("text/plain"));

    // textfile.doc -> text/plain. We added this to the mimetype database so that it can be handled.
    mime = KMimeType::findByNameAndContent("textfile.doc", textData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("text/plain"));

    // mswordfile.doc -> application/msword. Found by contents, because of the above case.
    // Note that it's application/msword, not application/vnd.ms-word, since it's the former that is registered to IANA.
    QByteArray mswordData = "\320\317\021\340\241\261\032\341";
    mime = KMimeType::findByNameAndContent("mswordfile.doc", mswordData);
    QVERIFY(mime);
    if (mime->name() == "application/vnd.ms-word") { // this comes from /usr/share/mime/packages/libreoffice.xml....
        QEXPECT_FAIL("", "libreoffice.xml is messing with us", Continue);
    }
    // If you get powerpoint instead, then you're hit by https://bugs.freedesktop.org/show_bug.cgi?id=435 - upgrade to shared-mime-info >= 0.22
    QCOMPARE(mime->name(), QString::fromLatin1("application/msword"));

    // excelfile.xls -> application/vnd.ms-excel. Found by extension.
    mime = KMimeType::findByNameAndContent("excelfile.xls", mswordData /*same magic*/);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/vnd.ms-excel"));

    // textfile.xls -> application/vnd.ms-excel. Found by extension. User shouldn't rename a text file to .xls ;)
    mime = KMimeType::findByNameAndContent("textfile.xls", textData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/vnd.ms-excel"));

#if 0   // needs shared-mime-info >= 0.20
    QByteArray tnefData = "\x78\x9f\x3e\x22";
    mime = KMimeType::findByNameAndContent("tneffile", mswordData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/vnd.ms-tnef"));
#endif

    QByteArray pdfData = "%PDF-";
    mime = KMimeType::findByNameAndContent("foo", pdfData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/pdf"));

    // High-priority rule (80)
    QByteArray phpData = "<?php";
    mime = KMimeType::findByNameAndContent("foo", phpData);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/x-php"));
}
Example #7
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"));
}
Example #8
0
void FileManager::openFile( const QString& fileName, const QString& name, const QString& title, const QString& partName, const QVariantList& partParams )
{
    if( fileName.isEmpty() )
        return;

    QString fullName = name.isEmpty() ? KUrl( fileName ).fileName() : name;
    QString fullTitle = title.isEmpty() ? fullName : title;
    if( d->parts.contains( fullName ) )
    {
        emit newPart( fullName, fullTitle );
        return;
    }

    KMimeType::Ptr mime = KMimeType::findByPath( fileName );

    KParts::ReadOnlyPart* part = 0;
    KService::List parts;

    if( !partName.isEmpty() )
    {
        KService::Ptr service = KService::serviceByDesktopName( partName );
        if( !service.isNull() )
            parts.append( service );
    }

    if( parts.count() == 0 )
    {
        parts.append( KMimeTypeTrader::self()->query( mime->name(), "KParts/ReadWritePart" ) );
        parts.append( KMimeTypeTrader::self()->query( mime->name(), "KParts/ReadOnlyPart" ) );

        if( mime->name().contains( "audio" ) && parts.count() == 0 )
            parts.append( KService::serviceByStorageId( "dragonplayer_part.desktop" ) );
    }

    if( parts.count() > 0 )
    {
        part = parts.first()->createInstance<KParts::ReadWritePart>( 0, partParams );
        if( !part )
            part = parts.first()->createInstance<KParts::ReadOnlyPart>( 0, partParams );
    }

    if( part )
    {
        // Add the part if it is found
        KUrl url( fileName );
        part->openUrl( url );
        d->parts.insert( fullName, part );
        d->partManager->addPart( part, true );
        emit newPart( fullName, fullTitle );

        return;
    }

    // There really is no part that can be used.
    // Instead, just open it in an external application.
    // KRun* runner = new KRun( KUrl( fileName ), qApp->activeWindow() );
}
Example #9
0
// All the simple tests for findByPath are in testFindByPathUsingFileName_data.
// In here we do the tests that need some content in a temporary file.
void KMimeTypeTest::testFindByPathWithContent()
{
    KMimeType::Ptr mime;

    // Test a real PDF file.
    // If we find x-matlab because it starts with '%' then we are not ordering by priority.
    KTemporaryFile tempFile;
    QVERIFY(tempFile.open());
    QString tempFileName = tempFile.fileName();
    tempFile.write("%PDF-");
    tempFile.close();
    mime = KMimeType::findByPath( tempFileName );
    QVERIFY( mime );
    QCOMPARE( mime->name(), QString::fromLatin1( "application/pdf" ) );
    // fast mode cannot find the mimetype
    mime = KMimeType::findByPath( tempFileName, 0, true );
    QVERIFY( mime );
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));

    // Test the case where the extension doesn't match the contents: extension wins
    {
        KTemporaryFile txtTempFile;
        txtTempFile.setSuffix(".txt");
        QVERIFY(txtTempFile.open());
        txtTempFile.write("%PDF-");
        QString txtTempFileName = txtTempFile.fileName();
        txtTempFile.close();
        mime = KMimeType::findByPath( txtTempFileName );
        QVERIFY( mime );
        QCOMPARE( mime->name(), QString::fromLatin1( "text/plain" ) );
        // fast mode finds the same
        mime = KMimeType::findByPath( txtTempFileName, 0, true );
        QVERIFY( mime );
        QCOMPARE( mime->name(), QString::fromLatin1( "text/plain" ) );
    }

    // Now the case where extension differs from contents, but contents has >80 magic rule
    // XDG spec says: contents wins. But we can't sniff all files...
    {
        KTemporaryFile txtTempFile;
        txtTempFile.setSuffix(".txt");
        QVERIFY(txtTempFile.open());
        txtTempFile.write("<smil");
        QString txtTempFileName = txtTempFile.fileName();
        txtTempFile.close();
        mime = KMimeType::findByPath( txtTempFileName );
        QVERIFY( mime );
        QCOMPARE( mime->name(), QString::fromLatin1( "text/plain" ) );
    }
}
Example #10
0
void ThemesDlg::installNewTheme(const QString &newTheme)
{
    // The created signal is already emitted before the file is
    // completely written, so wait until the new theme exists
    KMimeType::Ptr result;
    do {
        result = KMimeType::findByUrl(newTheme);
    } while (result->name() == "application/x-zerosize");

    if (result->name() == "application/x-gzip" ||
        result->name() == "application/x-compressed-tar" ||
        result->name() == "application/x-bzip" ||
        result->name() == "application/x-bzip" ||
        result->name() == "application/x-bzip-compressed-tar" ||
        result->name() == "application/x-bzip-compressed-tar2" ||
        result->name() == "application/x-tar" ||
        result->name() == "application/x-tarz") {

        kDebug() << "SKNewStuff::install() gzip/bzip2 mimetype encountered" << endl;

        KTar archive(newTheme);
        if (!archive.open(QIODevice::ReadOnly)) {
            return;
        }

        QString destDir = KStandardDirs::locateLocal("appdata", "themes/");

        const KArchiveDirectory *archiveDir = archive.directory();
        archiveDir->copyTo(destDir);
        //Add the theme to the Theme Dialog
        addThemeToDialog(archiveDir, destDir);
        archive.close();
    } else if (result->name() == "application/zip" ||
               result->name() == "application/x-superkaramba") {

        kDebug() << "SKNewStuff::install() zip mimetype encountered" << endl;
        //TODO: write a routine to check if this is a valid .skz file
        //otherwise we need to unpack it like it is an old theme that was packaged
        //as a .zip instead of .bz2 or .tar.gz

        //Add the skz theme to the Theme Dialog
        addSkzThemeToDialog(newTheme);
    } else if (result->name() == "plain/text") {
        kDebug() << "SKNewStuff::install() plain text" << endl;
    } else if (result->name() == "text/html" ||
        result->name() == "application/x-php") {

        kDebug() << "SKNewStuff::install() text/html" << endl;
        KRun::runUrl(newTheme, "text/html", 0);
    } else {
        kDebug() << "SKNewStuff::install() Error no compatible mimetype encountered to install" << endl;
        return;
    }
}
Example #11
0
void KFileFilterCombo::setMimeFilter(const QStringList &types, const QString &defaultType)
{
    clear();
    filters.clear();
    QString delim = QString::fromLatin1(", ");
    d->hasAllSupportedFiles = false;

    m_allTypes = defaultType.isEmpty() && (types.count() > 1);

    QString allComments, allTypes;
    int i = 0;
    for(QStringList::ConstIterator it = types.begin(); it != types.end(); ++it, ++i)
    {
        if(m_allTypes && it != types.begin())
        {
            allComments += delim;
            allTypes += ' ';
        }

        kdDebug(kfile_area) << *it << endl;
        KMimeType::Ptr type = KMimeType::mimeType(*it);
        filters.append(type->name());
        if(m_allTypes)
        {
            allTypes += type->name();
            allComments += type->comment();
        }
        insertItem(type->comment());
        if(type->name() == defaultType)
            setCurrentItem(i);
    }

    if(m_allTypes)
    {
        if(i < 3) // show the mime-comments of at max 3 types
            insertItem(allComments, 0);
        else
        {
            insertItem(i18n("All Supported Files"), 0);
            d->hasAllSupportedFiles = true;
        }

        filters.prepend(allTypes);
    }

    d->lastFilter = currentText();
    d->isMimeFilter = true;
}
Example #12
0
void BinaryWidget::setData( const QByteArray &data )
{
  delete mMainWidget;

  QString mimetype;
  KMimeType::Ptr mime = KMimeType::findByContent( data );
  if ( mime && !mime->isDefault() )
    mimetype = mime->name();

  if ( !mimetype.isEmpty() ) {
    KParts::ReadOnlyPart *part = KParts::ComponentFactory::createPartInstanceFromQuery<KParts::ReadOnlyPart>( mimetype, QString(), this, this );
    if ( part ) {
      KTemporaryFile file;
      file.setAutoRemove(false);
      file.open();
      file.write( data );
      file.flush();
      part->openUrl( KUrl( file.fileName() ) );
      mMainWidget = part->widget();
    } else {
      mMainWidget = new QLabel( i18n( "No part found for visualization of mimetype %1", mimetype ), this );
    }

    mData = data;
    mSaveButton->setEnabled( true );
  } else {
    mMainWidget = new QLabel( i18n( "Got data of unknown mimetype" ), this );
  }

  mLayout->addWidget( mMainWidget, 0, 0, 3, 1);
  mMainWidget->show();
}
Example #13
0
void KateFileTree::slotFixOpenWithMenu()
{
  QMenu *menu = (QMenu*)sender();
  menu->clear();
  
   KTextEditor::Document *doc = model()->data(m_indexContextMenu, KateFileTreeModel::DocumentRole).value<KTextEditor::Document *>();
  if (!doc) return;

  // get a list of appropriate services.
  KMimeType::Ptr mime = KMimeType::mimeType(doc->mimeType());
  //kDebug(13001) << "mime type: " << mime->name();

  QAction *a = 0;
  KService::List offers = KMimeTypeTrader::self()->query(mime->name(), "Application");
  // for each one, insert a menu item...
  for(KService::List::Iterator it = offers.begin(); it != offers.end(); ++it)
  {
    KService::Ptr service = *it;
    if (service->name() == "Kate") continue;
    a = menu->addAction(KIcon(service->icon()), service->name());
    a->setData(service->entryPath());
  }
  // append "Other..." to call the KDE "open with" dialog.
  a = menu->addAction(i18n("&Other..."));
  a->setData(QString());
}
Example #14
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();
}
Example #15
0
bool MPForm::addFile(const QString& name, const QString& path)
{
    KMimeType::Ptr ptr = KMimeType::findByUrl(path);
    QString mime       = ptr->name();
    if (mime.isEmpty())
        return false;

    QFile imageFile(path);
    if (!imageFile.open(QIODevice::ReadOnly))
        return false;
    QByteArray imageData = imageFile.readAll();

    //QString file_size = QString::number(imageFile.size());
    imageFile.close();

    QByteArray str;
    str += "--";
    str += m_boundary;
    str += "\r\n";
    str += "Content-Disposition: form-data; filename=\"";
    str += QFile::encodeName(name);
    str += "\"\r\n";
    //str += "Content-Length: ";
    //str += file_size.toAscii();
    //str += "\r\n";
    str += "Content-Type: ";
    str += mime.toAscii();
    str += "\r\n\r\n";

    m_buffer.append(str);
    m_buffer.append(imageData);
    m_buffer.append("\r\n");

    return true;
}
    void readAttachment()
    {
      if ( mAttachment->label().isEmpty() ) {
        if ( mAttachment->isUri() ) {
          setText( mAttachment->uri() );
        } else {
          setText( i18nc( "@label attachment contains binary data", "[Binary data]" ) );
        }
      } else {
        setText( mAttachment->label() );
      }

      setRenameEnabled( true );

      if ( mAttachment->mimeType().isEmpty() ||
           !( KMimeType::mimeType( mAttachment->mimeType() ) ) ) {
        KMimeType::Ptr mimeType;
        if ( mAttachment->isUri() ) {
          mimeType = KMimeType::findByUrl( mAttachment->uri() );
        } else {
          mimeType = KMimeType::findByContent( mAttachment->decodedData() );
        }
        mAttachment->setMimeType( mimeType->name() );
      }

      setPixmap( icon() );
    }
Example #17
0
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;
}
	void DownloadAndConvertJob::downloadFileFinished(KJob* j)
	{
		active_job = 0;
		if (j->error())
		{
			Out(SYS_IPF|LOG_NOTICE) << "IP filter update failed: " << j->errorString() << endl;
			if (mode == Verbose)
			{
				((KIO::Job*)j)->ui()->showErrorMessage();
			}
			else
			{
				QString msg = i18n("Automatic update of IP filter failed: %1", j->errorString());
				notification(msg);
			}
			
			setError(DOWNLOAD_FAILED); 
			emitResult();
			return;
		}
		
		QString temp = kt::DataDir() + "tmp-" + url.fileName();
		
		//now determine if it's ZIP or TXT file
		KMimeType::Ptr ptr = KMimeType::findByPath(temp);
		if (ptr->name() == "application/zip")
		{
			active_job = KIO::file_move(temp,QString(kt::DataDir() + QLatin1String("level1.zip")),-1,KIO::HideProgressInfo|KIO::Overwrite);
			connect(active_job,SIGNAL(result(KJob*)),this,SLOT(extract(KJob*)));
		}
Example #19
0
STDMETHODIMP CShellExt::InvokeCommand(LPCMINVOKECOMMANDINFO lpcmi)
{
    TCHAR   szFileUserClickedOn[MAX_PATH];
    TCHAR   dllPath[MAX_PATH];
    QString command;

    FORMATETC fmte = {
        CF_HDROP,
        (DVTARGETDEVICE FAR *)NULL,
        DVASPECT_CONTENT,
        -1,
        TYMED_HGLOBAL
    };

    GetModuleFileName(_hModule, dllPath, MAX_PATH);
    QString module = lptstr2QString(dllPath);
    command += module.left(module.lastIndexOf('\\'));
    command += '\\';

    for (unsigned i = 0; i < m_cbFiles; i++) {
        DragQueryFile((HDROP)m_stgMedium.hGlobal, i, szFileUserClickedOn, MAX_PATH);
        QString path = lptstr2QString(szFileUserClickedOn);
        
        if(0 == i)
        {
            KMimeType::Ptr ptr = KMimeType::findByPath(path);

            KService::List lst = KMimeTypeTrader::self()->query(ptr->name(), "Application");

            if(lst.size() > 0)
            {
                QString exec = lst.at(0)->exec();
                if( -1 != exec.indexOf("%u", 0, Qt::CaseInsensitive) )
                {
                    exec = exec.left(exec.indexOf("%u", 0, Qt::CaseInsensitive));
                }            
                command += exec;
            }
        };
        
        command += "\"" + path + "\"";
    }

    STARTUPINFO si;
    PROCESS_INFORMATION pi;
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);
    si.dwFlags = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_RESTORE;
    if (!CreateProcess(NULL, (LPTSTR)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) {
        MessageBox(lpcmi->hwnd,
                   TEXT("Error creating process: kdecm.dll needs to be in the same directory as the executable"),
                   TEXT("KDE Extension"),
                   MB_OK);
    }

    return NOERROR;
}
Example #20
0
void DocumentPreviewTab::setResource(Nepomuk2::Resource & resource)
{
    m_resource = resource;
    ui->urlSelector->clear();
    if(m_part) {
        m_part->closeUrl();
    }

    QString specificUrl;
    if(resource.isValid()) {

        specificUrl = resource.property(Nepomuk2::Vocabulary::NIE::url()).toString();
        if(!specificUrl.isEmpty()) {
            resource = resource.property(Nepomuk2::Vocabulary::NBIB::publishedAs()).toResource();
            m_resource = resource;
        }

        QList<Nepomuk2::Resource> fileList;

        if(resource.hasType(Nepomuk2::Vocabulary::NBIB::Reference())) {
            Nepomuk2::Resource publication = resource.property(Nepomuk2::Vocabulary::NBIB::publication()).toResource();
            fileList = publication.property(Nepomuk2::Vocabulary::NBIB::isPublicationOf()).toResourceList();
            fileList.append( publication.property(Nepomuk2::Vocabulary::NIE::links()).toResourceList() );
        }
        else if(resource.hasType(Nepomuk2::Vocabulary::NBIB::Publication())) {
            fileList = resource.property(Nepomuk2::Vocabulary::NBIB::isPublicationOf()).toResourceList();
            fileList.append( resource.property(Nepomuk2::Vocabulary::NIE::links()).toResourceList() );
        }
        else {
            fileList.append(resource);
        }

        // add all DataObjects to the preview
        foreach(const Nepomuk2::Resource & r, fileList) {
            KUrl url = KUrl(r.property(Nepomuk2::Vocabulary::NIE::url()).toString());
            KIcon icon;
            QString mimetype;

            if( r.hasType(Nepomuk2::Vocabulary::NFO::Website())// || r.hasType(Nepomuk2::Vocabulary::NFO::WebDataObject())
                || url.scheme() == QLatin1String("http")) {

                QString favIcon = KMimeType::favIconForUrl(url);
                if(favIcon.isEmpty()) {
                    favIcon = QLatin1String("text-html");
                }

                icon = KIcon(favIcon);
                mimetype = QLatin1String("text/html");
            }
            else {
                KMimeType::Ptr mimeTypePtr = KMimeType::findByUrl(url);

                icon = KIcon(mimeTypePtr->iconName());
                mimetype = mimeTypePtr->name();
            }

            ui->urlSelector->addItem(icon,url.url(),QVariant(mimetype));
        }
bool GalleryMPForm::addFile(const QString& path, const QString& displayFilename)
{

    QString filename = "userfile_name";
    if (GalleryTalker::isGallery2())
        filename = "g2_userfile_name";

    if (!addPairRaw(filename, displayFilename)) 
    {
        return false;
    }

    KMimeType::Ptr ptr = KMimeType::findByUrl(path);
    QString mime = ptr->name();
    if (mime.isEmpty())
    {
        // if we ourselves can't determine the mime of the local file,
        // very unlikely the remote gallery will be able to identify it
        return false;
    }

    QFile imageFile(path);
    if (!imageFile.open(QIODevice::ReadOnly))
        return false;
    QByteArray imageData = imageFile.readAll();
    imageFile.close();

    QString str;

    str += "--";
    str += m_boundary;
    str += "\r\n";
    str += "Content-Disposition: form-data; name=\"";

    if (GalleryTalker::isGallery2())
        str += "g2_userfile";
    else
        str += "userfile";

    str += "\"; ";
    str += "filename=\"";
    str += QFile::encodeName(KUrl(path).fileName());
    str += "\"";
    str += "\r\n";
    str += "Content-Type: ";
    str +=  mime.toAscii();
    str += "\r\n\r\n";

    m_buffer.append(str.toUtf8());

    int oldSize = m_buffer.size();
    m_buffer.resize(oldSize + imageData.size() + 2);
    memcpy(m_buffer.data() + oldSize, imageData.data(), imageData.size());
    m_buffer[m_buffer.size()-2] = '\r';
    m_buffer[m_buffer.size()-1] = '\n';

    return true;
}
Example #22
0
void KMimeTypeTest::testFindByPathUsingFileName()
{
    QFETCH(QString, fileName);
    QFETCH(QString, expectedMimeType);
    KMimeType::Ptr mime = KMimeType::findByPath(fileName);
    QVERIFY(mime);
    QCOMPARE(mime->name(), expectedMimeType);

}
Example #23
0
void KMimeTypeTest::testFindByFileContent()
{
    KMimeType::Ptr mime;
    int accuracy = 0;

    // Calling findByFileContent on a directory
    mime = KMimeType::findByFileContent("/", &accuracy);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("inode/directory"));
    QCOMPARE(accuracy, 100);

    // Albert calls findByFileContent with a URL instead of a path and gets 11021 as accuracy :)
    // It was not set inside findByFileContent -> fixed.
    mime = KMimeType::findByFileContent("file:///etc/passwd" /*bad example code, use a path instead*/, &accuracy);
    QVERIFY(mime);
    QCOMPARE(mime->name(), QString::fromLatin1("application/octet-stream"));
    QCOMPARE(accuracy, 0);
}
Example #24
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*)));
    }
}
Example #25
0
void KMimeTypeTest::testFindByContent()
{
    QFETCH(QByteArray, data);
    QFETCH(QString, expectedMimeType);

    KMimeType::Ptr mime = KMimeType::findByContent(data);
    QVERIFY(mime);
    QCOMPARE(mime->name(), expectedMimeType);
}
Example #26
0
void KMimeTypeTest::testAllMimeTypes()
{
    const KMimeType::List lst = KMimeType::allMimeTypes(); // does NOT include aliases
    QVERIFY( !lst.isEmpty() );

    for ( KMimeType::List::ConstIterator it = lst.begin();
          it != lst.end(); ++it ) {
        const KMimeType::Ptr mime = (*it);
        const QString name = mime->name();
        //qDebug( "%s", qPrintable( name ) );
        QVERIFY( !name.isEmpty() );
        QCOMPARE( name.count( '/' ), 1 );
        QVERIFY( mime->isType( KST_KMimeType ) );

        const KMimeType::Ptr lookedupMime = KMimeType::mimeType( name );
        QVERIFY( lookedupMime ); // not null
        QCOMPARE( lookedupMime->name(), name ); // if this fails, you have an alias defined as a real mimetype too!
    }
}
Example #27
0
static void printMimeTypes( const TDECmdLineArgs *args )
{
    for ( int i = 0; i < args->count(); i++ )
    {
        KURL url = args->url( i );
        KMimeType::Ptr mt = KMimeType::findByURL( url );
        cout << args->arg(i) << ": " << mt->comment().local8Bit().data() << " ("
             << mt->name().local8Bit().data() << ")" << endl;
    }
}
Example #28
0
bool KDEMMEngine::canDecode( const KURL &url ) const
{
    static QStringList list;

    kdDebug() << "BEGIN " << k_funcinfo << endl;
    kdDebug() << "  Param: url: " << url << endl;
    //kdDebug() << "  url.protocol()   >" << url.protocol() <<"<"<< endl;

    if (url.protocol() == "http" ) return false;

    // TODO determine list of supported MimeTypes/Extensions from KDEMM
    list += QString("audio/x-mp3");

    KFileItem fileItem( KFileItem::Unknown, KFileItem::Unknown, url, false ); //false = determineMimeType straight away
    KMimeType::Ptr mimetype = fileItem.determineMimeType();
    kdDebug() << "mimetype: " << mimetype->name().latin1() << endl;

    return list.contains( mimetype->name().latin1() );
}  // canDecode
Example #29
0
bool TrashProtocol::createUDSEntry(const QString &physicalPath, const QString &fileName, const QString &url, KIO::UDSEntry &entry,
                                   const TrashedFileInfo &info)
{
    QCString physicalPath_c = QFile::encodeName(physicalPath);
    KDE_struct_stat buff;
    if(KDE_lstat(physicalPath_c, &buff) == -1)
    {
        kdWarning() << "couldn't stat " << physicalPath << endl;
        return false;
    }
    if(S_ISLNK(buff.st_mode))
    {
        char buffer2[1000];
        int n = readlink(physicalPath_c, buffer2, 1000);
        if(n != -1)
        {
            buffer2[n] = 0;
        }

        addAtom(entry, KIO::UDS_LINK_DEST, 0, QFile::decodeName(buffer2));
// Follow symlink
// That makes sense in kio_file, but not in the trash, especially for the size
// #136876
#if 0
        if ( KDE_stat( physicalPath_c, &buff ) == -1 ) {
            // It is a link pointing to nowhere
            buff.st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO;
            buff.st_mtime = 0;
            buff.st_atime = 0;
            buff.st_size = 0;
        }
#endif
    }
    mode_t type = buff.st_mode & S_IFMT;  // extract file type
    mode_t access = buff.st_mode & 07777; // extract permissions
    access &= 07555;                      // make it readonly, since it's in the trashcan
    addAtom(entry, KIO::UDS_NAME, 0, fileName);
    addAtom(entry, KIO::UDS_FILE_TYPE, type);
    if(!url.isEmpty())
        addAtom(entry, KIO::UDS_URL, 0, url);

    KMimeType::Ptr mt = KMimeType::findByPath(physicalPath, buff.st_mode);
    addAtom(entry, KIO::UDS_MIME_TYPE, 0, mt->name());
    addAtom(entry, KIO::UDS_ACCESS, access);
    addAtom(entry, KIO::UDS_SIZE, buff.st_size);
    addAtom(entry, KIO::UDS_USER, 0, m_userName);   // assumption
    addAtom(entry, KIO::UDS_GROUP, 0, m_groupName); // assumption
    addAtom(entry, KIO::UDS_MODIFICATION_TIME, buff.st_mtime);
    addAtom(entry, KIO::UDS_ACCESS_TIME, buff.st_atime); // ## or use it for deletion time?
    addAtom(entry, KIO::UDS_EXTRA, 0, info.origPath);
    addAtom(entry, KIO::UDS_EXTRA, 0, info.deletionDate.toString(Qt::ISODate));
    return true;
}
Example #30
0
KService::Ptr ArkViewer::getViewer(const KMimeType::Ptr &mimeType)
{
    // No point in even trying to find anything for application/octet-stream
    if (mimeType->isDefault()) {
        return KService::Ptr();
    }

    // Try to get a read-only kpart for the internal viewer
    KService::List offers = KMimeTypeTrader::self()->query(mimeType->name(), QString::fromLatin1("KParts/ReadOnlyPart"));

    // If we can't find a kpart, try to get an external application
    if (offers.size() == 0) {
        offers = KMimeTypeTrader::self()->query(mimeType->name(), QString::fromLatin1("Application"));
    }

    if (offers.size() > 0) {
        return offers.first();
    } else {
        return KService::Ptr();
    }
}